@livx.cc/agentx 0.99.166 → 0.99.168
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/dist/cli.d.ts +21 -2
- package/dist/cli.js +486 -156
- package/dist/cli.js.map +1 -1
- package/dist/directives.js +2 -0
- package/dist/directives.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +60 -11
- package/dist/index.js.map +1 -1
- package/dist/{secondChannel-BNDDJv6d.d.ts → secondChannel-CaP6zhH6.d.ts} +9 -0
- package/package.json +2 -2
package/dist/directives.js
CHANGED
|
@@ -209,6 +209,8 @@ function makeModelResolver(engines) {
|
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
211
|
if (hits.length === 1) return hits[0];
|
|
212
|
+
const codex = hits.filter((h) => h.model.toLowerCase().startsWith("codex/"));
|
|
213
|
+
if (codex.length === 1 && hits.every((h) => h === codex[0] || h.model.toLowerCase().startsWith("openai/"))) return codex[0];
|
|
212
214
|
return hits.length > 1 ? { ambiguous: hits.map((h) => h.model) } : null;
|
|
213
215
|
};
|
|
214
216
|
}
|
package/dist/directives.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/models.ts","../src/directives.ts"],"sourcesContent":["/**\n * Model aliasing + mid-conversation switch resolution — pure; aliases come from ai.libx.js's catalog.\n *\n * Harness-level so every agentx consumer (unclaw, para-chat, …) resolves `[opus]`-style\n * aliases, gates by an allow-list, and announces a switch the same way. Policy (which models\n * a caller may use) and session state (the prior model) stay with the consumer; this module\n * is the shared mechanism.\n */\nimport { claudeModelAliases } from 'ai.libx.js';\n\n/** Canonical short aliases → concrete Anthropic model ids — DERIVED from ai.libx.js's catalog (newest entry per\n * family, plus versioned `opus-5`-style aliases). Never hand-pin an id here: a new model = one catalog entry. */\nexport const MODEL_ALIASES: Record<string, string> = { ...claudeModelAliases };\n\n/** Newest catalog model of a Claude family as a provider-qualified id (`'sonnet'` → `'anthropic/claude-sonnet-5-5'`).\n * Use this for every default/tier — a literal dated id goes stale the day the next model ships. */\nexport function latestClaude(family: 'fable' | 'opus' | 'sonnet' | 'haiku', provider = 'anthropic'): string {\n const id = MODEL_ALIASES[family];\n if (!id) throw new Error(`ai.libx.js catalog has no Claude ${family} model`);\n return `${provider}/${id}`;\n}\n\n/** Resolve an alias to a concrete id. A provider prefix (\"anthropic/\") is preserved; unknown ids pass through. */\nexport function resolveModelAlias(input: string): string {\n const slash = input.indexOf('/');\n const prefix = slash === -1 ? '' : input.slice(0, slash + 1);\n const rest = slash === -1 ? input : input.slice(slash + 1);\n // claude-code's catalogue IS the aliases (claude-code/opus); expanding them yields an unknown id.\n if (prefix === 'claude-code/') return input;\n return prefix + (MODEL_ALIASES[rest.toLowerCase()] ?? rest);\n}\n\n/** The provider of a model id (\"cursor/x\" -> \"cursor\"). Provider-specific `providerOptions` are only\n * portable within the same provider — leaking them across is a hard 400.\n *\n * A BARE id is the common case, not the exception: `resolveModelAlias('haiku')` yields\n * `claude-haiku-5-5` with no prefix (ai.libx.js resolves it fuzzily downstream), so reading\n * only the literal \"/\" made every aliased child look like a provider switch and silently dropped the\n * parent's options. The fix belongs HERE — the alias table must keep emitting the ids ai.libx.js\n * expects, and the comparison is provider identity, not string identity.\n *\n * A bare id we can't attribute is UNKNOWN, not a shared provider: it gets a per-id marker so two\n * different unknown ids never compare equal (returning \"\" for both made them look like one provider\n * and would have leaked one host's options onto the other's model). An unknown id still compares\n * equal to ITSELF, so a child staying on the parent's exact model keeps the parent's options. */\nexport function modelProvider(model: string): string {\n const i = model.indexOf('/');\n if (i !== -1) return model.slice(0, i);\n if (/^claude-/i.test(model)) return 'anthropic';\n return `?${model}`; // unknown: identity-scoped, never equal to a different unknown id\n}\n\n/** Short, human-friendly name for a resolved model id (e.g. \"anthropic/claude-opus-4-8\" → \"opus\"). */\nexport function modelShortLabel(model?: string): string {\n if (!model) return 'default';\n const id = model.split('/').pop()!;\n return id.replace(/^claude-/, '').replace(/-\\d.*$/, '');\n}\n\nexport interface ResolveModelSwitchOpts {\n /** Model requested for this turn (e.g. from an inline directive). Undefined = keep `current`. */\n requested?: string;\n /** The turn's default/current model when nothing is requested. */\n current: string;\n /** The session's prior resolved model — drives change detection + the notice. */\n prior?: string;\n /** If set, `requested` must match one of these (by short label) or it's denied and `current` is kept. */\n allowed?: string[];\n /** Announcement formatter. Default: `_[switching from x to y]_\\n\\n`. */\n format?: (from: string, to: string) => string;\n}\n\nexport interface ModelSwitch {\n /** The model to run this turn. */\n model: string;\n /** True when `requested` was rejected by `allowed` and `model` fell back to `current`. */\n denied: boolean;\n /** Inline notice to surface when the model actually changed vs `prior`, else undefined. */\n notice?: string;\n}\n\n/**\n * Resolve which model a turn runs, given an optional request, an allow-list, and the prior model.\n * Comparisons are by short label so provider-prefixed and dated ids unify\n * (\"anthropic/claude-opus-4-8\" ≡ \"claude-opus-4-8\" ≡ \"opus\").\n */\nexport function resolveModelSwitch(opts: ResolveModelSwitchOpts): ModelSwitch {\n const { requested, current, prior, allowed } = opts;\n if (!requested) return { model: current, denied: false };\n if (allowed && !allowed.some((a) => modelShortLabel(a) === modelShortLabel(requested))) {\n return { model: current, denied: true };\n }\n const fmt = opts.format ?? ((from: string, to: string) => `_[switching from ${from} to ${to}]_\\n\\n`);\n const changed = prior !== undefined && modelShortLabel(prior) !== modelShortLabel(requested);\n return {\n model: requested,\n denied: false,\n notice: changed ? fmt(modelShortLabel(prior!), modelShortLabel(requested)) : undefined,\n };\n}\n","/**\n * Inline prompt directives — `[opus] fix x`, `[cc-opus, 50] …`, `[model:openai/gpt-5.5] …` — pure,\n * dependency-free. A message may open with one or more `[..]` groups that pick the model (and, for\n * hosts that honour them, turns/thinking/effort/engine/resume); the rest is the prompt.\n *\n * Shared by every agentx host (unclaw/Shraga, Bare) so the grammar and its edge cases live once:\n * multi-group, strict mode (bracketed prose stays prose), and an unresolvable EXPLICIT model is\n * reported (`unresolvedModel`) rather than dropped — dropping it ran the turn on the previous model.\n *\n * Model tokens resolve through the alias table and an injected `ModelResolver` (the host's catalog,\n * see `makeModelResolver`). `<vendor>-<model>` / `<vendor>/<model>` shorthands (`cc-opus` →\n * `claude-code/opus`, see `VENDOR_SHORTHAND`) select a model only when they resolve (`[cc-by] …` stays prose).\n */\nimport { MODEL_ALIASES } from './models';\n\nexport interface Directives {\n model?: string;\n turns?: number;\n thinking?: 'adaptive' | 'enabled' | 'disabled';\n effort?: 'low' | 'medium' | 'high' | 'max';\n engine?: string;\n /** Session resume for this conversation (host-defined). */\n resume?: boolean;\n /** DELEGATE mode `[planner->worker]` (key `delegate`): the worker model; `model` (the left side) plans. */\n delegate?: string;\n /** ADVISOR mode `[worker<-advisor]` (key `advisor`): the advisor model; `model` (the left side) works. */\n advisor?: string;\n /** `[off]` / `[mode:off]` (key `mode`): clear a sticky delegate/advisor mode. */\n modeOff?: boolean;\n}\n\nexport interface ParsedPrompt {\n prompt: string;\n directives: Directives;\n /** An EXPLICIT model selection nothing could resolve. The caller must fail the turn, never run the old model. */\n unresolvedModel?: string;\n /** When `unresolvedModel` matched several catalog ids: the candidates (use the full id). */\n ambiguous?: string[];\n}\n\nexport type ModelHit = { model: string; engine?: string };\n/** Resolves a model token against a host catalog. `{ ambiguous }` = several ids match; never guess. */\nexport type ModelResolver = (token: string) => ModelHit | { ambiguous: string[] } | null;\n\n/** Vendor shorthand → provider id: `[cc-opus]` / `[cc/opus]` = `claude-code/opus`. Extend per host via options. */\nexport const VENDOR_SHORTHAND: Record<string, string> = { cc: 'claude-code', cur: 'cursor', oa: 'openai' };\n\n/** Every key agentx understands. A host passing its own `keys` must list `delegate` / `advisor` / `mode` to honour\n * `[a->b]` / `[a<-b]` / `[off]` (and their keyed forms `delegate:x`, `advisor:x`, `mode:off`). */\nexport const DIRECTIVE_KEYS = ['model', 'turns', 'thinking', 'think', 'effort', 'engine', 'resume', 'delegate', 'advisor', 'mode'];\n\n/** `a->b` (delegate) / `a<-b` (advisor): the left side may be empty (keep the current model). */\nexport function splitModePair(token: string): { left: string; op: '->' | '<-'; right: string } | null {\n const i = token.search(/->|<-/);\n if (i === -1) return null;\n const right = token.slice(i + 2).trim();\n return right ? { left: token.slice(0, i).trim(), op: token.slice(i, i + 2) as '->' | '<-', right } : null;\n}\nconst isModel = (t: string, p: DirectiveOptions) => { const h = resolveModelToken(t, p); return !!h && 'model' in h; };\n\nexport interface DirectiveOptions {\n /** Host catalog lookup. Default: the one set by `setModelResolver` (none). */\n resolveModel: ModelResolver | null;\n /** Try the catalog before the alias table (Bare: `[opus]` = the catalog's `claude-code/opus`). */\n resolverFirst: boolean;\n aliases: Record<string, string>;\n vendors: Record<string, string>;\n /** Keys this host honours; positional turns/thinking count only when `turns`/`thinking` are listed. */\n keys: string[];\n /** Every group, the first included, must look like directives (else it stays prompt text). */\n strict: boolean;\n /** Resolve to catalog ids ONLY (Bare): no alias-table fallback, a full id the catalog lacks is refused, and a\n * bare word matches an id's tail only when it is a known alias or carries a digit (`[auto]` stays prose). */\n catalogOnly: boolean;\n warn: (msg: string) => void;\n}\n\nlet defaultResolver: ModelResolver | null = null;\n/** Process-wide default resolver (Shraga's engine registry injects it once). Per-call options override. */\nexport function setModelResolver(fn: ModelResolver | null): void { defaultResolver = fn; }\n\nconst opt = (o?: Partial<DirectiveOptions>): DirectiveOptions => ({\n resolveModel: defaultResolver, resolverFirst: false, aliases: MODEL_ALIASES, vendors: VENDOR_SHORTHAND,\n keys: DIRECTIVE_KEYS, strict: false, catalogOnly: false, warn: (m) => console.warn(m), ...o,\n});\n\n// A group ends at whitespace or the end: `[opus](http://x)` is a markdown link, not a directive.\nconst DIRECTIVE_RE = /^\\s*\\[([^\\]]*)\\](?=\\s|$)\\s*([\\s\\S]*)/;\nconst isQualifiedModel = (v: string) => /^[a-z0-9._-]+\\/[a-z0-9./_-]+$/.test(v);\n\n/** `cc-opus` / `cc/opus` → `claude-code/opus`; a full `claude-code/opus` is returned as is. Else null. */\nexport function expandVendor(token: string, vendors: Record<string, string> = VENDOR_SHORTHAND): string | null {\n const v = token.trim().toLowerCase();\n const m = v.match(/^([a-z0-9]+)[-/](.+)$/);\n if (m && vendors[m[1]]) return `${vendors[m[1]]}/${m[2]}`;\n const slash = v.indexOf('/');\n return slash > 0 && Object.values(vendors).includes(v.slice(0, slash)) ? v : null;\n}\n\n/** Resolve one model token: vendor shorthand → catalog exact id; else alias table + catalog in the configured order. */\nexport function resolveModelToken(token: string, o?: Partial<DirectiveOptions>): ModelHit | { ambiguous: string[] } | null {\n const p = opt(o);\n const v = token.trim().toLowerCase();\n const vendored = expandVendor(v, p.vendors);\n if (vendored) return p.resolveModel ? p.resolveModel(vendored) : p.catalogOnly ? null : { model: vendored }; // no catalog: trust the explicit id\n if (p.catalogOnly) return v.includes('/') || p.aliases[v] || /\\d/.test(v) ? p.resolveModel?.(v) ?? null : null;\n const alias = p.aliases[v] ? { model: p.aliases[v] } : null;\n if (!p.resolverFirst) return alias ?? p.resolveModel?.(v) ?? null;\n const hit = p.resolveModel?.(v) ?? null;\n return hit && 'model' in hit ? hit : alias ?? hit;\n}\n\nconst THINK = ['think', 'adaptive', 'nothink', 'nothinking'];\n\n/** Does a bracket group look like directives (vs. prompt text that happens to start with `[`)? */\nexport function isDirectiveGroup(raw: string, o?: Partial<DirectiveOptions>): boolean {\n const p = opt(o);\n const tokens = raw.split(',').map((t) => t.trim()).filter(Boolean);\n if (!tokens.length) return false;\n return tokens.every((t) => {\n const i = t.indexOf(':');\n if (i !== -1) return p.keys.includes(t.slice(0, i).trim().toLowerCase());\n const v = t.toLowerCase();\n const pair = splitModePair(v);\n if (pair) return p.keys.includes(pair.op === '->' ? 'delegate' : 'advisor') && ((!!pair.left && isModel(pair.left, p)) || isModel(pair.right, p)); // one resolved side makes it explicit: the other one's miss is reported\n if (v === 'off') return p.keys.includes('mode');\n return !!resolveModelToken(v, p) || (p.catalogOnly && !!p.aliases[v])\n || (p.keys.includes('turns') && /^\\d+$/.test(v)) || (p.keys.includes('thinking') && THINK.includes(v));\n });\n}\n\n/** Splits the leading `[..]` directive groups off a prompt — EVERY consecutive leading group. */\nexport function splitDirectiveGroups(text: string, o?: Partial<DirectiveOptions>): { groups: string[]; body: string } {\n const p = opt(o);\n let rest = text;\n const groups: string[] = [];\n for (;;) {\n const m = rest.match(DIRECTIVE_RE);\n if (!m) break;\n const g = m[1].trim();\n if ((groups.length || p.strict) && g && !isDirectiveGroup(g, p)) break;\n groups.push(g);\n rest = m[2];\n }\n return { groups, body: rest };\n}\n\nexport function parseDirectives(text: string, o?: Partial<DirectiveOptions>): ParsedPrompt {\n const p = opt(o);\n const { groups, body } = splitDirectiveGroups(text, p);\n if (!groups.length) return { prompt: text, directives: {} };\n const prompt = body.trim();\n const raw = groups.filter(Boolean).join(',');\n if (!raw) return { prompt, directives: {} };\n\n const d: Directives = {};\n const out: ParsedPrompt = { prompt, directives: d };\n const tokens = raw.split(',');\n // A keyed sibling proves the group is directives, so an unresolvable leading model there IS a dropped selection.\n const proven = tokens.some((t) => { const i = t.indexOf(':'); return i !== -1 && p.keys.includes(t.slice(0, i).trim().toLowerCase()); });\n const fail = (tok: string, hit: ReturnType<typeof resolveModelToken>) => {\n out.unresolvedModel ??= tok;\n if (hit && 'ambiguous' in hit) out.ambiguous ??= hit.ambiguous;\n };\n const setModel = (val: string): boolean | ReturnType<typeof resolveModelToken> => {\n const hit = resolveModelToken(val, p);\n if (!hit || !('model' in hit)) return hit;\n d.model = hit.model;\n if (hit.engine && !d.engine) d.engine = hit.engine; // an engine-owned model implies its engine, never over `[engine:x]`\n return true;\n };\n\n let pos = 0;\n for (const token of tokens) {\n const t = token.trim();\n if (!t) continue;\n const i = t.indexOf(':');\n if (i !== -1) {\n const key = t.slice(0, i).trim().toLowerCase(), val = t.slice(i + 1).trim().toLowerCase();\n if (!p.keys.includes(key)) { p.warn(`[directives] Unknown directive key: \"${key}\"`); continue; }\n if (key === 'delegate' || key === 'advisor') {\n const hit = resolveModelToken(val, p);\n if (hit && 'model' in hit) d[key] = hit.model;\n else if (!hit && isQualifiedModel(val) && !p.catalogOnly) d[key] = val;\n else fail(val, hit);\n continue;\n }\n if (key === 'model') {\n const r = setModel(val);\n if (r === true) continue;\n // A plain `provider/model` with no catalog to check is concrete — the engine owns the verdict.\n if (!r && isQualifiedModel(val) && !p.catalogOnly) { d.model = val; continue; }\n fail(val, r as any);\n } else applyKey(d, key, val, p.warn);\n continue;\n }\n const val = t.toLowerCase();\n const pair = splitModePair(val);\n if (pair && p.keys.includes(pair.op === '->' ? 'delegate' : 'advisor')) {\n const lhit = pair.left ? resolveModelToken(pair.left, p) : null, rhit = resolveModelToken(pair.right, p);\n const lok = !pair.left || (!!lhit && 'model' in lhit), rok = !!rhit && 'model' in rhit;\n // Explicit once either side resolves: the other side's miss is a dropped selection, never a silent fallback.\n if (lok && rok) {\n if (pair.left) setModel(pair.left);\n if (pair.op === '->') d.delegate = (rhit as ModelHit).model; else d.advisor = (rhit as ModelHit).model;\n } else if (lok || rok) { if (!lok) fail(pair.left, lhit); else fail(pair.right, rhit); }\n else p.warn(`[directives] Unknown models in \"${t}\"`);\n pos++;\n continue;\n }\n if (val === 'off' && p.keys.includes('mode')) { d.modeOff = true; pos++; continue; }\n const r = pos === 0 ? setModel(val) : null;\n if (r === true) { /* model */ }\n else if (pos <= 1 && /^\\d+$/.test(val) && p.keys.includes('turns')) d.turns = parseInt(val, 10);\n else if (['think', 'adaptive'].includes(val) && p.keys.includes('thinking')) d.thinking = 'adaptive';\n else if (['nothink', 'nothinking'].includes(val) && p.keys.includes('thinking')) d.thinking = 'disabled';\n else if (pos === 0) {\n // Ambiguous tokens (and, catalog-only, a known alias the catalog lacks) are model selections; a plain unknown one\n // only with a keyed sibling. An unresolved vendor form (`[cc-by]`) is not a selection.\n if (r || (p.catalogOnly && p.aliases[val]) || (proven && !isQualifiedModel(val))) fail(t, r as any);\n p.warn(`[directives] Unknown model: \"${t}\"`);\n }\n pos++;\n }\n return out;\n}\n\nfunction applyKey(d: Directives, key: string, val: string, warn: (m: string) => void): void {\n switch (key) {\n case 'turns': if (/^\\d+$/.test(val)) d.turns = parseInt(val, 10); else warn(`[directives] Invalid turns value: \"${val}\"`); break;\n case 'thinking':\n case 'think': if (['adaptive', 'enabled', 'disabled'].includes(val)) d.thinking = val as Directives['thinking']; else warn(`[directives] Invalid thinking value: \"${val}\"`); break;\n case 'effort': if (['low', 'medium', 'high', 'max'].includes(val)) d.effort = val as Directives['effort']; else warn(`[directives] Invalid effort value: \"${val}\"`); break;\n case 'engine': d.engine = val; break;\n case 'mode': if (val === 'off') d.modeOff = true; else warn(`[directives] Invalid mode value: \"${val}\"`); break;\n case 'resume':\n if (['on', 'true', '1'].includes(val)) d.resume = true;\n else if (['off', 'false', '0'].includes(val)) d.resume = false;\n else warn(`[directives] Invalid resume value: \"${val}\"`);\n break;\n }\n}\n\n/** Engine/provider → the model ids it advertises. */\nexport interface EngineModels { name: string; models: { value: string }[] }\n\n/**\n * A resolver over host catalogs: exact id first, then the bare suffix after the provider prefix —\n * ONLY when unambiguous across engines (`{ ambiguous }` otherwise, never the first match).\n */\nexport function makeModelResolver(engines: () => EngineModels[]): ModelResolver {\n return (token) => {\n const t = token.toLowerCase();\n const hits: ModelHit[] = [];\n for (const { name, models } of engines()) {\n for (const m of models) {\n if (!m.value) continue;\n const v = m.value.toLowerCase();\n if (v === t) return { model: m.value, engine: name };\n if (v.slice(v.lastIndexOf('/') + 1) === t && !hits.some((h) => h.model === m.value)) hits.push({ model: m.value, engine: name });\n }\n }\n if (hits.length === 1) return hits[0];\n return hits.length > 1 ? { ambiguous: hits.map((h) => h.model) } : null;\n };\n}\n"],"mappings":";AAQA,SAAS,0BAA0B;AAI5B,IAAM,gBAAwC,EAAE,GAAG,mBAAmB;;;ACiCtE,IAAM,mBAA2C,EAAE,IAAI,eAAe,KAAK,UAAU,IAAI,SAAS;AAIlG,IAAM,iBAAiB,CAAC,SAAS,SAAS,YAAY,SAAS,UAAU,UAAU,UAAU,YAAY,WAAW,MAAM;AAG1H,SAA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M,OAAO,KAAK,QAAQ,GAAG;AACtC,iBAAW,KAAK,QAAQ;AACpB,YAAI,CAAC,EAAE,MAAO;AACd,cAAM,IAAI,EAAE,MAAM,YAAY;AAC9B,YAAI,MAAM,EAAG,QAAO,EAAE,OAAO,EAAE,OAAO,QAAQ,KAAK;AACnD,YAAI,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC,MAAM,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAG,MAAK,KAAK,EAAE,OAAO,EAAE,OAAO,QAAQ,KAAK,CAAC;AAAA,MACnI;AAAA,IACJ;AACA,QAAI,KAAK,WAAW,EAAG,QAAO,KAAK,CAAC;AACpC,WAAO,KAAK,SAAS,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI;AAAA,EACvE;AACJ;","names":["val","r"]}
|
|
1
|
+
{"version":3,"sources":["../src/models.ts","../src/directives.ts"],"sourcesContent":["/**\n * Model aliasing + mid-conversation switch resolution — pure; aliases come from ai.libx.js's catalog.\n *\n * Harness-level so every agentx consumer (unclaw, para-chat, …) resolves `[opus]`-style\n * aliases, gates by an allow-list, and announces a switch the same way. Policy (which models\n * a caller may use) and session state (the prior model) stay with the consumer; this module\n * is the shared mechanism.\n */\nimport { claudeModelAliases } from 'ai.libx.js';\n\n/** Canonical short aliases → concrete Anthropic model ids — DERIVED from ai.libx.js's catalog (newest entry per\n * family, plus versioned `opus-5`-style aliases). Never hand-pin an id here: a new model = one catalog entry. */\nexport const MODEL_ALIASES: Record<string, string> = { ...claudeModelAliases };\n\n/** Newest catalog model of a Claude family as a provider-qualified id (`'sonnet'` → `'anthropic/claude-sonnet-5-5'`).\n * Use this for every default/tier — a literal dated id goes stale the day the next model ships. */\nexport function latestClaude(family: 'fable' | 'opus' | 'sonnet' | 'haiku', provider = 'anthropic'): string {\n const id = MODEL_ALIASES[family];\n if (!id) throw new Error(`ai.libx.js catalog has no Claude ${family} model`);\n return `${provider}/${id}`;\n}\n\n/** Resolve an alias to a concrete id. A provider prefix (\"anthropic/\") is preserved; unknown ids pass through. */\nexport function resolveModelAlias(input: string): string {\n const slash = input.indexOf('/');\n const prefix = slash === -1 ? '' : input.slice(0, slash + 1);\n const rest = slash === -1 ? input : input.slice(slash + 1);\n // claude-code's catalogue IS the aliases (claude-code/opus); expanding them yields an unknown id.\n if (prefix === 'claude-code/') return input;\n return prefix + (MODEL_ALIASES[rest.toLowerCase()] ?? rest);\n}\n\n/** The provider of a model id (\"cursor/x\" -> \"cursor\"). Provider-specific `providerOptions` are only\n * portable within the same provider — leaking them across is a hard 400.\n *\n * A BARE id is the common case, not the exception: `resolveModelAlias('haiku')` yields\n * `claude-haiku-5-5` with no prefix (ai.libx.js resolves it fuzzily downstream), so reading\n * only the literal \"/\" made every aliased child look like a provider switch and silently dropped the\n * parent's options. The fix belongs HERE — the alias table must keep emitting the ids ai.libx.js\n * expects, and the comparison is provider identity, not string identity.\n *\n * A bare id we can't attribute is UNKNOWN, not a shared provider: it gets a per-id marker so two\n * different unknown ids never compare equal (returning \"\" for both made them look like one provider\n * and would have leaked one host's options onto the other's model). An unknown id still compares\n * equal to ITSELF, so a child staying on the parent's exact model keeps the parent's options. */\nexport function modelProvider(model: string): string {\n const i = model.indexOf('/');\n if (i !== -1) return model.slice(0, i);\n if (/^claude-/i.test(model)) return 'anthropic';\n return `?${model}`; // unknown: identity-scoped, never equal to a different unknown id\n}\n\n/** Short, human-friendly name for a resolved model id (e.g. \"anthropic/claude-opus-4-8\" → \"opus\"). */\nexport function modelShortLabel(model?: string): string {\n if (!model) return 'default';\n const id = model.split('/').pop()!;\n return id.replace(/^claude-/, '').replace(/-\\d.*$/, '');\n}\n\nexport interface ResolveModelSwitchOpts {\n /** Model requested for this turn (e.g. from an inline directive). Undefined = keep `current`. */\n requested?: string;\n /** The turn's default/current model when nothing is requested. */\n current: string;\n /** The session's prior resolved model — drives change detection + the notice. */\n prior?: string;\n /** If set, `requested` must match one of these (by short label) or it's denied and `current` is kept. */\n allowed?: string[];\n /** Announcement formatter. Default: `_[switching from x to y]_\\n\\n`. */\n format?: (from: string, to: string) => string;\n}\n\nexport interface ModelSwitch {\n /** The model to run this turn. */\n model: string;\n /** True when `requested` was rejected by `allowed` and `model` fell back to `current`. */\n denied: boolean;\n /** Inline notice to surface when the model actually changed vs `prior`, else undefined. */\n notice?: string;\n}\n\n/**\n * Resolve which model a turn runs, given an optional request, an allow-list, and the prior model.\n * Comparisons are by short label so provider-prefixed and dated ids unify\n * (\"anthropic/claude-opus-4-8\" ≡ \"claude-opus-4-8\" ≡ \"opus\").\n */\nexport function resolveModelSwitch(opts: ResolveModelSwitchOpts): ModelSwitch {\n const { requested, current, prior, allowed } = opts;\n if (!requested) return { model: current, denied: false };\n if (allowed && !allowed.some((a) => modelShortLabel(a) === modelShortLabel(requested))) {\n return { model: current, denied: true };\n }\n const fmt = opts.format ?? ((from: string, to: string) => `_[switching from ${from} to ${to}]_\\n\\n`);\n const changed = prior !== undefined && modelShortLabel(prior) !== modelShortLabel(requested);\n return {\n model: requested,\n denied: false,\n notice: changed ? fmt(modelShortLabel(prior!), modelShortLabel(requested)) : undefined,\n };\n}\n","/**\n * Inline prompt directives — `[opus] fix x`, `[cc-opus, 50] …`, `[model:openai/gpt-5.5] …` — pure,\n * dependency-free. A message may open with one or more `[..]` groups that pick the model (and, for\n * hosts that honour them, turns/thinking/effort/engine/resume); the rest is the prompt.\n *\n * Shared by every agentx host (unclaw/Shraga, Bare) so the grammar and its edge cases live once:\n * multi-group, strict mode (bracketed prose stays prose), and an unresolvable EXPLICIT model is\n * reported (`unresolvedModel`) rather than dropped — dropping it ran the turn on the previous model.\n *\n * Model tokens resolve through the alias table and an injected `ModelResolver` (the host's catalog,\n * see `makeModelResolver`). `<vendor>-<model>` / `<vendor>/<model>` shorthands (`cc-opus` →\n * `claude-code/opus`, see `VENDOR_SHORTHAND`) select a model only when they resolve (`[cc-by] …` stays prose).\n */\nimport { MODEL_ALIASES } from './models';\n\nexport interface Directives {\n model?: string;\n turns?: number;\n thinking?: 'adaptive' | 'enabled' | 'disabled';\n effort?: 'low' | 'medium' | 'high' | 'max';\n engine?: string;\n /** Session resume for this conversation (host-defined). */\n resume?: boolean;\n /** DELEGATE mode `[planner->worker]` (key `delegate`): the worker model; `model` (the left side) plans. */\n delegate?: string;\n /** ADVISOR mode `[worker<-advisor]` (key `advisor`): the advisor model; `model` (the left side) works. */\n advisor?: string;\n /** `[off]` / `[mode:off]` (key `mode`): clear a sticky delegate/advisor mode. */\n modeOff?: boolean;\n}\n\nexport interface ParsedPrompt {\n prompt: string;\n directives: Directives;\n /** An EXPLICIT model selection nothing could resolve. The caller must fail the turn, never run the old model. */\n unresolvedModel?: string;\n /** When `unresolvedModel` matched several catalog ids: the candidates (use the full id). */\n ambiguous?: string[];\n}\n\nexport type ModelHit = { model: string; engine?: string };\n/** Resolves a model token against a host catalog. `{ ambiguous }` = several ids match; never guess. */\nexport type ModelResolver = (token: string) => ModelHit | { ambiguous: string[] } | null;\n\n/** Vendor shorthand → provider id: `[cc-opus]` / `[cc/opus]` = `claude-code/opus`. Extend per host via options. */\nexport const VENDOR_SHORTHAND: Record<string, string> = { cc: 'claude-code', cur: 'cursor', oa: 'openai' };\n\n/** Every key agentx understands. A host passing its own `keys` must list `delegate` / `advisor` / `mode` to honour\n * `[a->b]` / `[a<-b]` / `[off]` (and their keyed forms `delegate:x`, `advisor:x`, `mode:off`). */\nexport const DIRECTIVE_KEYS = ['model', 'turns', 'thinking', 'think', 'effort', 'engine', 'resume', 'delegate', 'advisor', 'mode'];\n\n/** `a->b` (delegate) / `a<-b` (advisor): the left side may be empty (keep the current model). */\nexport function splitModePair(token: string): { left: string; op: '->' | '<-'; right: string } | null {\n const i = token.search(/->|<-/);\n if (i === -1) return null;\n const right = token.slice(i + 2).trim();\n return right ? { left: token.slice(0, i).trim(), op: token.slice(i, i + 2) as '->' | '<-', right } : null;\n}\nconst isModel = (t: string, p: DirectiveOptions) => { const h = resolveModelToken(t, p); return !!h && 'model' in h; };\n\nexport interface DirectiveOptions {\n /** Host catalog lookup. Default: the one set by `setModelResolver` (none). */\n resolveModel: ModelResolver | null;\n /** Try the catalog before the alias table (Bare: `[opus]` = the catalog's `claude-code/opus`). */\n resolverFirst: boolean;\n aliases: Record<string, string>;\n vendors: Record<string, string>;\n /** Keys this host honours; positional turns/thinking count only when `turns`/`thinking` are listed. */\n keys: string[];\n /** Every group, the first included, must look like directives (else it stays prompt text). */\n strict: boolean;\n /** Resolve to catalog ids ONLY (Bare): no alias-table fallback, a full id the catalog lacks is refused, and a\n * bare word matches an id's tail only when it is a known alias or carries a digit (`[auto]` stays prose). */\n catalogOnly: boolean;\n warn: (msg: string) => void;\n}\n\nlet defaultResolver: ModelResolver | null = null;\n/** Process-wide default resolver (Shraga's engine registry injects it once). Per-call options override. */\nexport function setModelResolver(fn: ModelResolver | null): void { defaultResolver = fn; }\n\nconst opt = (o?: Partial<DirectiveOptions>): DirectiveOptions => ({\n resolveModel: defaultResolver, resolverFirst: false, aliases: MODEL_ALIASES, vendors: VENDOR_SHORTHAND,\n keys: DIRECTIVE_KEYS, strict: false, catalogOnly: false, warn: (m) => console.warn(m), ...o,\n});\n\n// A group ends at whitespace or the end: `[opus](http://x)` is a markdown link, not a directive.\nconst DIRECTIVE_RE = /^\\s*\\[([^\\]]*)\\](?=\\s|$)\\s*([\\s\\S]*)/;\nconst isQualifiedModel = (v: string) => /^[a-z0-9._-]+\\/[a-z0-9./_-]+$/.test(v);\n\n/** `cc-opus` / `cc/opus` → `claude-code/opus`; a full `claude-code/opus` is returned as is. Else null. */\nexport function expandVendor(token: string, vendors: Record<string, string> = VENDOR_SHORTHAND): string | null {\n const v = token.trim().toLowerCase();\n const m = v.match(/^([a-z0-9]+)[-/](.+)$/);\n if (m && vendors[m[1]]) return `${vendors[m[1]]}/${m[2]}`;\n const slash = v.indexOf('/');\n return slash > 0 && Object.values(vendors).includes(v.slice(0, slash)) ? v : null;\n}\n\n/** Resolve one model token: vendor shorthand → catalog exact id; else alias table + catalog in the configured order. */\nexport function resolveModelToken(token: string, o?: Partial<DirectiveOptions>): ModelHit | { ambiguous: string[] } | null {\n const p = opt(o);\n const v = token.trim().toLowerCase();\n const vendored = expandVendor(v, p.vendors);\n if (vendored) return p.resolveModel ? p.resolveModel(vendored) : p.catalogOnly ? null : { model: vendored }; // no catalog: trust the explicit id\n if (p.catalogOnly) return v.includes('/') || p.aliases[v] || /\\d/.test(v) ? p.resolveModel?.(v) ?? null : null;\n const alias = p.aliases[v] ? { model: p.aliases[v] } : null;\n if (!p.resolverFirst) return alias ?? p.resolveModel?.(v) ?? null;\n const hit = p.resolveModel?.(v) ?? null;\n return hit && 'model' in hit ? hit : alias ?? hit;\n}\n\nconst THINK = ['think', 'adaptive', 'nothink', 'nothinking'];\n\n/** Does a bracket group look like directives (vs. prompt text that happens to start with `[`)? */\nexport function isDirectiveGroup(raw: string, o?: Partial<DirectiveOptions>): boolean {\n const p = opt(o);\n const tokens = raw.split(',').map((t) => t.trim()).filter(Boolean);\n if (!tokens.length) return false;\n return tokens.every((t) => {\n const i = t.indexOf(':');\n if (i !== -1) return p.keys.includes(t.slice(0, i).trim().toLowerCase());\n const v = t.toLowerCase();\n const pair = splitModePair(v);\n if (pair) return p.keys.includes(pair.op === '->' ? 'delegate' : 'advisor') && ((!!pair.left && isModel(pair.left, p)) || isModel(pair.right, p)); // one resolved side makes it explicit: the other one's miss is reported\n if (v === 'off') return p.keys.includes('mode');\n return !!resolveModelToken(v, p) || (p.catalogOnly && !!p.aliases[v])\n || (p.keys.includes('turns') && /^\\d+$/.test(v)) || (p.keys.includes('thinking') && THINK.includes(v));\n });\n}\n\n/** Splits the leading `[..]` directive groups off a prompt — EVERY consecutive leading group. */\nexport function splitDirectiveGroups(text: string, o?: Partial<DirectiveOptions>): { groups: string[]; body: string } {\n const p = opt(o);\n let rest = text;\n const groups: string[] = [];\n for (;;) {\n const m = rest.match(DIRECTIVE_RE);\n if (!m) break;\n const g = m[1].trim();\n if ((groups.length || p.strict) && g && !isDirectiveGroup(g, p)) break;\n groups.push(g);\n rest = m[2];\n }\n return { groups, body: rest };\n}\n\nexport function parseDirectives(text: string, o?: Partial<DirectiveOptions>): ParsedPrompt {\n const p = opt(o);\n const { groups, body } = splitDirectiveGroups(text, p);\n if (!groups.length) return { prompt: text, directives: {} };\n const prompt = body.trim();\n const raw = groups.filter(Boolean).join(',');\n if (!raw) return { prompt, directives: {} };\n\n const d: Directives = {};\n const out: ParsedPrompt = { prompt, directives: d };\n const tokens = raw.split(',');\n // A keyed sibling proves the group is directives, so an unresolvable leading model there IS a dropped selection.\n const proven = tokens.some((t) => { const i = t.indexOf(':'); return i !== -1 && p.keys.includes(t.slice(0, i).trim().toLowerCase()); });\n const fail = (tok: string, hit: ReturnType<typeof resolveModelToken>) => {\n out.unresolvedModel ??= tok;\n if (hit && 'ambiguous' in hit) out.ambiguous ??= hit.ambiguous;\n };\n const setModel = (val: string): boolean | ReturnType<typeof resolveModelToken> => {\n const hit = resolveModelToken(val, p);\n if (!hit || !('model' in hit)) return hit;\n d.model = hit.model;\n if (hit.engine && !d.engine) d.engine = hit.engine; // an engine-owned model implies its engine, never over `[engine:x]`\n return true;\n };\n\n let pos = 0;\n for (const token of tokens) {\n const t = token.trim();\n if (!t) continue;\n const i = t.indexOf(':');\n if (i !== -1) {\n const key = t.slice(0, i).trim().toLowerCase(), val = t.slice(i + 1).trim().toLowerCase();\n if (!p.keys.includes(key)) { p.warn(`[directives] Unknown directive key: \"${key}\"`); continue; }\n if (key === 'delegate' || key === 'advisor') {\n const hit = resolveModelToken(val, p);\n if (hit && 'model' in hit) d[key] = hit.model;\n else if (!hit && isQualifiedModel(val) && !p.catalogOnly) d[key] = val;\n else fail(val, hit);\n continue;\n }\n if (key === 'model') {\n const r = setModel(val);\n if (r === true) continue;\n // A plain `provider/model` with no catalog to check is concrete — the engine owns the verdict.\n if (!r && isQualifiedModel(val) && !p.catalogOnly) { d.model = val; continue; }\n fail(val, r as any);\n } else applyKey(d, key, val, p.warn);\n continue;\n }\n const val = t.toLowerCase();\n const pair = splitModePair(val);\n if (pair && p.keys.includes(pair.op === '->' ? 'delegate' : 'advisor')) {\n const lhit = pair.left ? resolveModelToken(pair.left, p) : null, rhit = resolveModelToken(pair.right, p);\n const lok = !pair.left || (!!lhit && 'model' in lhit), rok = !!rhit && 'model' in rhit;\n // Explicit once either side resolves: the other side's miss is a dropped selection, never a silent fallback.\n if (lok && rok) {\n if (pair.left) setModel(pair.left);\n if (pair.op === '->') d.delegate = (rhit as ModelHit).model; else d.advisor = (rhit as ModelHit).model;\n } else if (lok || rok) { if (!lok) fail(pair.left, lhit); else fail(pair.right, rhit); }\n else p.warn(`[directives] Unknown models in \"${t}\"`);\n pos++;\n continue;\n }\n if (val === 'off' && p.keys.includes('mode')) { d.modeOff = true; pos++; continue; }\n const r = pos === 0 ? setModel(val) : null;\n if (r === true) { /* model */ }\n else if (pos <= 1 && /^\\d+$/.test(val) && p.keys.includes('turns')) d.turns = parseInt(val, 10);\n else if (['think', 'adaptive'].includes(val) && p.keys.includes('thinking')) d.thinking = 'adaptive';\n else if (['nothink', 'nothinking'].includes(val) && p.keys.includes('thinking')) d.thinking = 'disabled';\n else if (pos === 0) {\n // Ambiguous tokens (and, catalog-only, a known alias the catalog lacks) are model selections; a plain unknown one\n // only with a keyed sibling. An unresolved vendor form (`[cc-by]`) is not a selection.\n if (r || (p.catalogOnly && p.aliases[val]) || (proven && !isQualifiedModel(val))) fail(t, r as any);\n p.warn(`[directives] Unknown model: \"${t}\"`);\n }\n pos++;\n }\n return out;\n}\n\nfunction applyKey(d: Directives, key: string, val: string, warn: (m: string) => void): void {\n switch (key) {\n case 'turns': if (/^\\d+$/.test(val)) d.turns = parseInt(val, 10); else warn(`[directives] Invalid turns value: \"${val}\"`); break;\n case 'thinking':\n case 'think': if (['adaptive', 'enabled', 'disabled'].includes(val)) d.thinking = val as Directives['thinking']; else warn(`[directives] Invalid thinking value: \"${val}\"`); break;\n case 'effort': if (['low', 'medium', 'high', 'max'].includes(val)) d.effort = val as Directives['effort']; else warn(`[directives] Invalid effort value: \"${val}\"`); break;\n case 'engine': d.engine = val; break;\n case 'mode': if (val === 'off') d.modeOff = true; else warn(`[directives] Invalid mode value: \"${val}\"`); break;\n case 'resume':\n if (['on', 'true', '1'].includes(val)) d.resume = true;\n else if (['off', 'false', '0'].includes(val)) d.resume = false;\n else warn(`[directives] Invalid resume value: \"${val}\"`);\n break;\n }\n}\n\n/** Engine/provider → the model ids it advertises. */\nexport interface EngineModels { name: string; models: { value: string }[] }\n\n/**\n * A resolver over host catalogs: exact id first, then the bare suffix after the provider prefix —\n * ONLY when unambiguous across engines (`{ ambiguous }` otherwise, never the first match).\n */\nexport function makeModelResolver(engines: () => EngineModels[]): ModelResolver {\n return (token) => {\n const t = token.toLowerCase();\n const hits: ModelHit[] = [];\n for (const { name, models } of engines()) {\n for (const m of models) {\n if (!m.value) continue;\n const v = m.value.toLowerCase();\n if (v === t) return { model: m.value, engine: name };\n if (v.slice(v.lastIndexOf('/') + 1) === t && !hits.some((h) => h.model === m.value)) hits.push({ model: m.value, engine: name });\n }\n }\n if (hits.length === 1) return hits[0];\n // the Codex subscription and the paid OpenAI API serving the same id: the subscription wins (`openai/<id>` stays explicit)\n const codex = hits.filter((h) => h.model.toLowerCase().startsWith('codex/'));\n if (codex.length === 1 && hits.every((h) => h === codex[0] || h.model.toLowerCase().startsWith('openai/'))) return codex[0];\n return hits.length > 1 ? { ambiguous: hits.map((h) => h.model) } : null;\n };\n}\n"],"mappings":";AAQA,SAAS,0BAA0B;AAI5B,IAAM,gBAAwC,EAAE,GAAG,mBAAmB;;;ACiCtE,IAAM,mBAA2C,EAAE,IAAI,eAAe,KAAK,UAAU,IAAI,SAAS;AAIlG,IAAM,iBAAiB,CAAC,SAAS,SAAS,YAAY,SAAS,UAAU,UAAU,UAAU,YAAY,WAAW,MAAM;AAG1H,SAAS,cAAc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,KAAK,QAAQ,GAAG;AACtC,iBAAW,KAAK,QAAQ;AACpB,YAAI,CAAC,EAAE,MAAO;AACd,cAAM,IAAI,EAAE,MAAM,YAAY;AAC9B,YAAI,MAAM,EAAG,QAAO,EAAE,OAAO,EAAE,OAAO,QAAQ,KAAK;AACnD,YAAI,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC,MAAM,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAG,MAAK,KAAK,EAAE,OAAO,EAAE,OAAO,QAAQ,KAAK,CAAC;AAAA,MACnI;AAAA,IACJ;AACA,QAAI,KAAK,WAAW,EAAG,QAAO,KAAK,CAAC;AAEpC,UAAM,QAAQ,KAAK,OAAO,CAAC,MAAM,EAAE,MAAM,YAAY,EAAE,WAAW,QAAQ,CAAC;AAC3E,QAAI,MAAM,WAAW,KAAK,KAAK,MAAM,CAAC,MAAM,MAAM,MAAM,CAAC,KAAK,EAAE,MAAM,YAAY,EAAE,WAAW,SAAS,CAAC,EAAG,QAAO,MAAM,CAAC;AAC1H,WAAO,KAAK,SAAS,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI;AAAA,EACvE;AACJ;","names":["val","r"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as AgentOptions, H as Hooks, x as RunResult, k as Decider, b as Agent, q as PermissionPolicy, G as Gender, L as LineKind, d as ChannelMode, y as SecondChannelOptions, S as SecondChannel } from './secondChannel-
|
|
2
|
-
export { A as ADVISE_LIMIT, a as AdvisorSetup, C as CC_WRITE_TOOLS, e as ChatFragment, f as ChatUsage, g as Classification, h as Classifier, i as CompactResult, j as ContextFileSpec, D as DEFAULT_MUTATING, l as Decision, M as ModelRouter, m as ModelRouterOptions, P as PLANNER_BLOCKED, n as PLANNER_REFUSAL, o as PLAN_FIRST, p as PermissionOptions, r as PermissionRule, s as PreToolUseDecision, R as ReasoningEffort, t as RecordingHooks, u as RecordingLifecycle, v as RouteDecision, w as RouterState, T as Tier, z as ToolUse, B as ToolUseMeta, W as WRITE_TOOLS, E as advisorFor, F as advisorPrompt, I as ccModeOptions, J as claudeCodeDisallowedTools, K as composeHooks, N as delegatePrompt, O as delegateTools, Q as delegateWorkerFor, U as estimateTokens, V as jevAvailable, X as jevClassifier, Y as loadContextFiles, Z as loadInstructions, _ as makeAdvisor, $ as meterWorkers, a0 as pickTier, a1 as planMode, a2 as plannerBlocks, a3 as reasoningToChatFragment } from './secondChannel-
|
|
1
|
+
import { c as AgentOptions, H as Hooks, x as RunResult, k as Decider, b as Agent, q as PermissionPolicy, G as Gender, L as LineKind, d as ChannelMode, y as SecondChannelOptions, S as SecondChannel } from './secondChannel-CaP6zhH6.js';
|
|
2
|
+
export { A as ADVISE_LIMIT, a as AdvisorSetup, C as CC_WRITE_TOOLS, e as ChatFragment, f as ChatUsage, g as Classification, h as Classifier, i as CompactResult, j as ContextFileSpec, D as DEFAULT_MUTATING, l as Decision, M as ModelRouter, m as ModelRouterOptions, P as PLANNER_BLOCKED, n as PLANNER_REFUSAL, o as PLAN_FIRST, p as PermissionOptions, r as PermissionRule, s as PreToolUseDecision, R as ReasoningEffort, t as RecordingHooks, u as RecordingLifecycle, v as RouteDecision, w as RouterState, T as Tier, z as ToolUse, B as ToolUseMeta, W as WRITE_TOOLS, E as advisorFor, F as advisorPrompt, I as ccModeOptions, J as claudeCodeDisallowedTools, K as composeHooks, N as delegatePrompt, O as delegateTools, Q as delegateWorkerFor, U as estimateTokens, V as jevAvailable, X as jevClassifier, Y as loadContextFiles, Z as loadInstructions, _ as makeAdvisor, $ as meterWorkers, a0 as pickTier, a1 as planMode, a2 as plannerBlocks, a3 as reasoningToChatFragment } from './secondChannel-CaP6zhH6.js';
|
|
3
3
|
export { MODEL_ALIASES, ModelSwitch, ResolveModelSwitchOpts, latestClaude, modelShortLabel, resolveModelAlias, resolveModelSwitch } from './models.js';
|
|
4
4
|
import { IFilesystem, FileMetadata } from '@livx.cc/wcli/core';
|
|
5
5
|
export { CommandExecutor, FileMetadata, IFilesystem, IndexedDbFilesystem, MemFilesystem, registerHeadlessCommands } from '@livx.cc/wcli/core';
|
package/dist/index.js
CHANGED
|
@@ -3195,6 +3195,26 @@ function ccToolServer(name, tools, call) {
|
|
|
3195
3195
|
return { type: "sdk", name, instance };
|
|
3196
3196
|
}
|
|
3197
3197
|
|
|
3198
|
+
// src/runtimes.ts
|
|
3199
|
+
var RUNTIMES = {
|
|
3200
|
+
"claude-code": { keyless: true, ownsTools: true },
|
|
3201
|
+
cursor: { keyless: false, ownsTools: false },
|
|
3202
|
+
// host tools are bridged in through its toolExecutor
|
|
3203
|
+
codex: { keyless: true, ownsTools: true }
|
|
3204
|
+
// `codex app-server` on the ChatGPT subscription login; MCP via per-thread config
|
|
3205
|
+
};
|
|
3206
|
+
function runtimeOf(model) {
|
|
3207
|
+
const p = (model ?? "").split("/")[0];
|
|
3208
|
+
return (model ?? "").includes("/") && p in RUNTIMES ? p : void 0;
|
|
3209
|
+
}
|
|
3210
|
+
var isClaudeCode = (model) => runtimeOf(model) === "claude-code";
|
|
3211
|
+
var isCursor = (model) => runtimeOf(model) === "cursor";
|
|
3212
|
+
var isCodex = (model) => runtimeOf(model) === "codex";
|
|
3213
|
+
var ownsTools = (model) => {
|
|
3214
|
+
const r = runtimeOf(model);
|
|
3215
|
+
return !!r && RUNTIMES[r].ownsTools;
|
|
3216
|
+
};
|
|
3217
|
+
|
|
3198
3218
|
// src/Agent.ts
|
|
3199
3219
|
init_llm();
|
|
3200
3220
|
init_tools();
|
|
@@ -3980,7 +4000,11 @@ var PermissionPolicy = class {
|
|
|
3980
4000
|
preToolUse: async (call) => {
|
|
3981
4001
|
const d = this.decide(call);
|
|
3982
4002
|
if (d === "allow") return;
|
|
3983
|
-
if (d === "deny")
|
|
4003
|
+
if (d === "deny") {
|
|
4004
|
+
const reason = `denied by permission policy (${call.name})`;
|
|
4005
|
+
this.options.onDeny?.(call, reason);
|
|
4006
|
+
return { block: true, reason };
|
|
4007
|
+
}
|
|
3984
4008
|
if (this.options.ask) {
|
|
3985
4009
|
const r = await this.options.ask(call);
|
|
3986
4010
|
const decision = r?.decision ?? "deny";
|
|
@@ -4629,7 +4653,7 @@ function pairOk(kind, main, other) {
|
|
|
4629
4653
|
log8.warn(`${kind} off: both sides are ${main}`);
|
|
4630
4654
|
return false;
|
|
4631
4655
|
}
|
|
4632
|
-
if (main
|
|
4656
|
+
if (isCursor(main) || isCursor(other)) {
|
|
4633
4657
|
log8.warn(`${kind} off: cursor models are not supported (${main} / ${other})`);
|
|
4634
4658
|
return false;
|
|
4635
4659
|
}
|
|
@@ -5032,6 +5056,9 @@ var AgentOptions = class {
|
|
|
5032
5056
|
* caps, MCP soft timeout) live on `JobRegistryOptions`. Completion notices reach the model via `inject` unless
|
|
5033
5057
|
* the host set its own `onExit`. */
|
|
5034
5058
|
jobs;
|
|
5059
|
+
/** Called after every `inject()` (a background job's completion notice, a host steer). A REPL uses it to wake an
|
|
5060
|
+
* IDLE session — between turns nothing drains the queue, so a finished job would otherwise wait for the next prompt. */
|
|
5061
|
+
onInject;
|
|
5035
5062
|
/** Plan mode: block mutating tools until the agent calls `ExitPlanMode` (host-approved). */
|
|
5036
5063
|
planMode = false;
|
|
5037
5064
|
/** Permission policy gating each tool call (allow / ask / deny). */
|
|
@@ -5149,6 +5176,20 @@ var Agent = class _Agent {
|
|
|
5149
5176
|
this.parkedMs += Date.now() - t;
|
|
5150
5177
|
}
|
|
5151
5178
|
}
|
|
5179
|
+
/** codex/*: Codex runs its own tools, so its approval requests (a command, a file change) go through the SAME hooks an
|
|
5180
|
+
* agentx tool call does: permission policy (allow/deny/ask resolver -> live `waiting`/`denied`), plan mode. The wait
|
|
5181
|
+
* holds the stall watchdog (a human may take minutes; Codex is silent meanwhile) and is parked out of the timeout. */
|
|
5182
|
+
async codexApprove(req) {
|
|
5183
|
+
const call = codexApprovalCall(req);
|
|
5184
|
+
const job = this.jobs.track({ kind: "host", label: `approve:${call.name}`, holds: true });
|
|
5185
|
+
try {
|
|
5186
|
+
const r = await this.park(Promise.resolve(this.activeHooks?.preToolUse?.(call, { id: "codex-approval" })));
|
|
5187
|
+
return r?.block ? "decline" : "accept";
|
|
5188
|
+
} finally {
|
|
5189
|
+
job.finish("done");
|
|
5190
|
+
this.stallPoke?.();
|
|
5191
|
+
}
|
|
5192
|
+
}
|
|
5152
5193
|
/** Force the next `send()`/`run()` to rebuild the system prompt, tools, plan-mode and permission hooks
|
|
5153
5194
|
* from `options` — apply mid-conversation changes to `planMode`/`permissions`/`model` etc. (prepare()
|
|
5154
5195
|
* is otherwise memoized per conversation). */
|
|
@@ -5189,6 +5230,7 @@ var Agent = class _Agent {
|
|
|
5189
5230
|
* Pushing onto `transcript` directly from outside would race the loop — this drains inside it. */
|
|
5190
5231
|
inject(content) {
|
|
5191
5232
|
this.pendingInjections.push(content);
|
|
5233
|
+
this.options.onInject?.();
|
|
5192
5234
|
}
|
|
5193
5235
|
/** Drop any queued-but-unconsumed injections. The REPL calls this after a LOCAL command (/cmd, !bash)
|
|
5194
5236
|
* — which runs no send() to drain them — so a mid-command steer can't leak into the next real turn. */
|
|
@@ -5202,7 +5244,7 @@ var Agent = class _Agent {
|
|
|
5202
5244
|
/** claude-code/*: the providerOptions every step adds (and prewarm, so the session it starts is the one step 1 reuses). */
|
|
5203
5245
|
claudeCodePo() {
|
|
5204
5246
|
const o = this.options;
|
|
5205
|
-
if (!o.model
|
|
5247
|
+
if (!isClaudeCode(o.model)) return void 0;
|
|
5206
5248
|
const po = { steer: () => this.drainPendingSteers() };
|
|
5207
5249
|
const mode = ccModeOptions(this.modeKind, o.providerOptions?.hooks, () => this.adv?.used() ?? 0);
|
|
5208
5250
|
const bridged = (t) => o.ccBridge === "all" || CC_BRIDGED.has(t.name) || mode.bridge.has(t.name);
|
|
@@ -5232,7 +5274,7 @@ var Agent = class _Agent {
|
|
|
5232
5274
|
async prewarm() {
|
|
5233
5275
|
const o = this.options;
|
|
5234
5276
|
const api = o.model.startsWith("anthropic/") && o.promptCache;
|
|
5235
|
-
if (!api && (!o.model
|
|
5277
|
+
if (!api && (!isClaudeCode(o.model) || !o.providerOptions?.claudeCodeSession)) return;
|
|
5236
5278
|
await this.ensureFs();
|
|
5237
5279
|
const systemPrompt = await this.prepare(), startCtx = await this.fireSessionStart();
|
|
5238
5280
|
const sys = { role: "system", content: systemPrompt + (startCtx ? "\n\n" + startCtx : "") };
|
|
@@ -5381,7 +5423,7 @@ var Agent = class _Agent {
|
|
|
5381
5423
|
tools: worker ? delegateTools([...o.tools, ...this.injectedTools], o.model, o.delegate?.plannerMay) : [...o.tools, ...this.injectedTools],
|
|
5382
5424
|
systemPrompt: o.systemPrompt,
|
|
5383
5425
|
// A child never resumes the parent's own claude-code session (the host's `resume` link is the parent's).
|
|
5384
|
-
providerOptionsFor: o.providerOptionsFor ?? ((m) => modelProvider(m) === modelProvider(o.model) && o.providerOptions ? { ...o.providerOptions, resume: void 0, onClaudeCodeSession: void 0 } : void 0)
|
|
5426
|
+
providerOptionsFor: o.providerOptionsFor ?? ((m) => modelProvider(m) === modelProvider(o.model) && o.providerOptions ? { ...o.providerOptions, resume: void 0, onClaudeCodeSession: void 0, onCodexThread: void 0 } : void 0)
|
|
5385
5427
|
};
|
|
5386
5428
|
tools = [...tools, makeTaskTool(taskOpts), makeTaskBatchTool(taskOpts)];
|
|
5387
5429
|
}
|
|
@@ -5549,8 +5591,8 @@ var Agent = class _Agent {
|
|
|
5549
5591
|
let res;
|
|
5550
5592
|
let sent = this.trimContext();
|
|
5551
5593
|
const frag = reasoningToChatFragment(o.model, o.reasoning);
|
|
5552
|
-
const sentTools = o.model
|
|
5553
|
-
const isCursorWithTools = o.model
|
|
5594
|
+
const sentTools = ownsTools(o.model) ? [] : wireTools;
|
|
5595
|
+
const isCursorWithTools = isCursor(o.model) && wireTools.length > 0;
|
|
5554
5596
|
const hostToolTimeoutMs = o.providerOptions?.toolTimeoutMs;
|
|
5555
5597
|
const derivedToolTimeoutMs = Math.max(TRANSPORT_TOOL_TIMEOUT_FLOOR_MS, ...this.activeTools.map(transportHeadroomMs));
|
|
5556
5598
|
const effectiveToolTimeoutMs = typeof hostToolTimeoutMs === "number" ? Math.max(hostToolTimeoutMs, derivedToolTimeoutMs) : derivedToolTimeoutMs;
|
|
@@ -5579,16 +5621,17 @@ var Agent = class _Agent {
|
|
|
5579
5621
|
};
|
|
5580
5622
|
const cursorPo = isCursorWithTools ? { toolTimeoutMs: effectiveToolTimeoutMs, toolExecutor: hostExec } : void 0;
|
|
5581
5623
|
const claudeSteerPo = this.claudeCodePo();
|
|
5624
|
+
const codexPo = isCodex(o.model) ? { onApproval: (req) => this.codexApprove(req) } : void 0;
|
|
5582
5625
|
if (this.ccServer) this.ccExec = hostExec;
|
|
5583
|
-
const cursorDeny = o.model
|
|
5584
|
-
if (o.model
|
|
5626
|
+
const cursorDeny = isCursor(o.model) ? o.permissions?.denyRules(true) ?? [] : [];
|
|
5627
|
+
if (isCursor(o.model) && o.permissions?.options.default === "deny")
|
|
5585
5628
|
throw new Error("cursor/* cannot enforce --onlyTools: its native tools bypass it. Refusing to run \u2014 use a claude-code/* or API model.");
|
|
5586
5629
|
if (cursorDeny.length)
|
|
5587
5630
|
throw new Error(`cursor/* cannot enforce --disallowedTools (${cursorDeny.join(", ")}): its native tools bypass them. Refusing to run \u2014 use a claude-code/* or API model, or drop --disallowedTools.`);
|
|
5588
5631
|
const reasonOpts = {
|
|
5589
5632
|
...frag,
|
|
5590
5633
|
...o.promptCache ? { promptCache: true } : {},
|
|
5591
|
-
...o.providerOptions || cursorPo || claudeSteerPo ? { providerOptions: { ...frag.providerOptions, ...o.providerOptions, ...cursorPo, ...claudeSteerPo } } : {}
|
|
5634
|
+
...o.providerOptions || cursorPo || claudeSteerPo || codexPo ? { providerOptions: { ...frag.providerOptions, ...o.providerOptions, ...cursorPo, ...claudeSteerPo, ...codexPo } } : {}
|
|
5592
5635
|
};
|
|
5593
5636
|
try {
|
|
5594
5637
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -6434,6 +6477,12 @@ function toolKey(name) {
|
|
|
6434
6477
|
const k = name.toLowerCase();
|
|
6435
6478
|
return TOOL_ALIASES[k] ?? k;
|
|
6436
6479
|
}
|
|
6480
|
+
function codexApprovalCall(req) {
|
|
6481
|
+
if (req.kind === "command") return { name: "bash", args: { command: req.command ?? "", ...req.cwd ? { cwd: req.cwd } : {} } };
|
|
6482
|
+
if (req.kind === "mcpToolCall") return { name: `mcp__${req.server ?? ""}__${req.tool ?? ""}`, args: req.args ?? {} };
|
|
6483
|
+
const paths = (req.changes ?? []).map((c) => c.path);
|
|
6484
|
+
return { name: "Edit", args: { path: paths[0] ?? "", ...paths.length > 1 ? { paths } : {} } };
|
|
6485
|
+
}
|
|
6437
6486
|
|
|
6438
6487
|
// src/index.ts
|
|
6439
6488
|
init_models();
|
|
@@ -12089,7 +12138,7 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
|
|
|
12089
12138
|
* no other MCP server — the reflex only talks and routes; real work still goes through Act and its policy. */
|
|
12090
12139
|
claudeCodeReflex() {
|
|
12091
12140
|
const o = this.options;
|
|
12092
|
-
if (!o.reflexModel
|
|
12141
|
+
if (!isClaudeCode(o.reflexModel)) return {};
|
|
12093
12142
|
const po = o.providerOptionsFor?.(o.reflexModel) ?? {};
|
|
12094
12143
|
return {
|
|
12095
12144
|
ccBridge: "all",
|