@andorra-labs/code 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +37 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +12 -0
  8. package/dist/src/app-server/reasoning.d.ts +0 -8
  9. package/dist/src/app-server/reasoning.js +15 -28
  10. package/dist/src/app-server.d.ts +7 -0
  11. package/dist/src/app-server.js +59 -11
  12. package/dist/src/auth/AuthManager.d.ts +15 -0
  13. package/dist/src/auth/AuthManager.js +66 -7
  14. package/dist/src/browser-runner.js +1 -2
  15. package/dist/src/browser-server.js +10 -2
  16. package/dist/src/browser-session.js +6 -2
  17. package/dist/src/browser-stealth.d.ts +29 -0
  18. package/dist/src/browser-stealth.js +166 -0
  19. package/dist/src/browser-ui/app.js +108 -13
  20. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  21. package/dist/src/browser-ui/index.html +8 -8
  22. package/dist/src/browser-ui/style.css +199 -171
  23. package/dist/src/browser-ui/tokens.css +198 -0
  24. package/dist/src/browser-view.d.ts +57 -9
  25. package/dist/src/browser-view.js +187 -36
  26. package/dist/src/cli.js +21 -4
  27. package/dist/src/coding-tools.js +9 -5
  28. package/dist/src/command-screens.js +4 -4
  29. package/dist/src/commands.d.ts +1 -1
  30. package/dist/src/commands.js +2 -1
  31. package/dist/src/completion-gates.d.ts +35 -0
  32. package/dist/src/completion-gates.js +25 -0
  33. package/dist/src/completion.d.ts +6 -0
  34. package/dist/src/completion.js +36 -3
  35. package/dist/src/config.d.ts +1 -1
  36. package/dist/src/config.js +2 -2
  37. package/dist/src/context-budget.d.ts +11 -0
  38. package/dist/src/context-budget.js +13 -0
  39. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  40. package/dist/src/decision/DecisionManager.d.ts +1 -0
  41. package/dist/src/decision/DecisionManager.js +14 -3
  42. package/dist/src/decision/FactContinuations.d.ts +6 -0
  43. package/dist/src/decision/FactContinuations.js +9 -1
  44. package/dist/src/decision/FactServiceGate.js +1 -1
  45. package/dist/src/decision/hostedSkills.d.ts +37 -0
  46. package/dist/src/decision/hostedSkills.js +64 -0
  47. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  48. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  49. package/dist/src/default-graph.d.ts +11 -0
  50. package/dist/src/default-graph.js +20 -0
  51. package/dist/src/duration.d.ts +13 -2
  52. package/dist/src/duration.js +27 -3
  53. package/dist/src/graph-manager-chat.d.ts +302 -0
  54. package/dist/src/graph-manager-chat.js +940 -0
  55. package/dist/src/graph-runner.js +6 -0
  56. package/dist/src/graph-server.d.ts +9 -0
  57. package/dist/src/graph-server.js +167 -16
  58. package/dist/src/graph-studio-features.js +2 -2
  59. package/dist/src/graph-sync.js +5 -2
  60. package/dist/src/graph-ui/app.js +252 -71
  61. package/dist/src/graph-ui/controls.css +55 -32
  62. package/dist/src/graph-ui/controls.js +85 -9
  63. package/dist/src/graph-ui/edge-router.js +114 -13
  64. package/dist/src/graph-ui/embed.js +23 -8
  65. package/dist/src/graph-ui/index.html +3 -3
  66. package/dist/src/graph-ui/library.css +4 -10
  67. package/dist/src/graph-ui/manager-markdown.js +155 -0
  68. package/dist/src/graph-ui/manager-state.js +191 -0
  69. package/dist/src/graph-ui/manager.css +161 -0
  70. package/dist/src/graph-ui/manager.js +700 -0
  71. package/dist/src/graph-ui/studio-canvas.js +2 -0
  72. package/dist/src/graph-ui/studio.css +24 -23
  73. package/dist/src/graph-ui/studio.js +29 -8
  74. package/dist/src/graph-ui/style.css +125 -92
  75. package/dist/src/graph-ui/tokens.css +217 -151
  76. package/dist/src/graphs.d.ts +69 -1
  77. package/dist/src/graphs.js +160 -7
  78. package/dist/src/hardened-runtime.js +8 -2
  79. package/dist/src/membership-errors.d.ts +14 -0
  80. package/dist/src/membership-errors.js +24 -1
  81. package/dist/src/membership.d.ts +20 -0
  82. package/dist/src/membership.js +45 -16
  83. package/dist/src/palette.d.ts +25 -8
  84. package/dist/src/palette.js +26 -8
  85. package/dist/src/provider-engine.d.ts +4 -4
  86. package/dist/src/provider-engine.js +39 -22
  87. package/dist/src/providers.d.ts +24 -0
  88. package/dist/src/providers.js +47 -2
  89. package/dist/src/qa/guidance.d.ts +26 -0
  90. package/dist/src/qa/guidance.js +59 -0
  91. package/dist/src/qa/index.d.ts +1 -6
  92. package/dist/src/qa/index.js +1 -14
  93. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  94. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  95. package/dist/src/react-runtime.d.ts +11 -0
  96. package/dist/src/react-runtime.js +190 -51
  97. package/dist/src/remote/engine-pool.js +4 -1
  98. package/dist/src/run-progress.d.ts +6 -0
  99. package/dist/src/run-progress.js +7 -0
  100. package/dist/src/runtime.d.ts +8 -0
  101. package/dist/src/session-skills.d.ts +75 -0
  102. package/dist/src/session-skills.js +151 -0
  103. package/dist/src/side-panel.d.ts +1 -1
  104. package/dist/src/side-panel.js +6 -12
  105. package/dist/src/skill-commands.js +1 -1
  106. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  107. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  108. package/dist/src/skills/bundled/provenance.json +3 -3
  109. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  110. package/dist/src/stall-recovery.d.ts +22 -0
  111. package/dist/src/stall-recovery.js +71 -0
  112. package/dist/src/subagent-run.js +1 -2
  113. package/dist/src/terminal-ui.d.ts +2 -2
  114. package/dist/src/terminal-ui.js +18 -13
  115. package/dist/src/transcript.js +9 -1
  116. package/dist/src/types.d.ts +18 -4
  117. package/dist/src/usage-analytics.d.ts +7 -0
  118. package/dist/src/usage-analytics.js +55 -15
  119. package/docs/concepts/README.md +1 -1
  120. package/docs/concepts/limits.md +9 -0
  121. package/docs/guides/desktop-app.md +1 -1
  122. package/docs/guides/graph-builder.md +16 -1
  123. package/docs/reference/slash-commands.md +2 -1
  124. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  125. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  126. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  127. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  128. package/package.json +1 -1
  129. package/tests/chat-side-panel-test-plan.md +1 -1
@@ -0,0 +1,35 @@
1
+ import type { TodoItem } from './todos.js';
2
+ /**
3
+ * Checks on the completion that ends a run, made by the host before it accepts the handoff.
4
+ *
5
+ * A model's own `complete_agent` call was the only thing that ended a run on the default graph: no
6
+ * guard, no verifier. A live run ended that way with its plan still "in progress" and an envelope
7
+ * that carried no summary, so the transcript closed on the raw output object and a finished-looking
8
+ * turn read as a run cut off halfway. Both conditions are facts the host already holds, so they are
9
+ * checked in code rather than left to the prompt.
10
+ *
11
+ * Each gate sends the handoff back at most `MAX_GATE_ASKS` times and is waived after that. A gate
12
+ * never spends a completion repair and never fails the run: a model that will not write a summary,
13
+ * or that leaves a step open because it cannot be done, ends exactly as it did before the gates
14
+ * existed, with the waiver recorded.
15
+ */
16
+ export type FinalAnswerGateId = 'summary' | 'todos';
17
+ export declare const MAX_GATE_ASKS = 2;
18
+ export interface FinalAnswerGateInput {
19
+ /** The envelope had no summary, so the serialized output is what the user would read. */
20
+ summaryStoodIn: boolean;
21
+ /** The run's plan as it stands after any update sent beside the completion. */
22
+ todos: readonly TodoItem[];
23
+ /** How many times each gate has already sent a handoff back in this run. */
24
+ asked?: Partial<Record<FinalAnswerGateId, number>>;
25
+ }
26
+ export interface FinalAnswerGateResult {
27
+ /** Gates that send this handoff back. Empty when every failed gate is waived. */
28
+ gates: FinalAnswerGateId[];
29
+ /** Gates that failed again after their asks were spent; the handoff is accepted despite them. */
30
+ waived: FinalAnswerGateId[];
31
+ /** What the model is told. Empty when nothing is sent back. */
32
+ message: string;
33
+ }
34
+ /** Undefined when the handoff passes every gate. */
35
+ export declare function finalAnswerGate(input: FinalAnswerGateInput): FinalAnswerGateResult | undefined;
@@ -0,0 +1,25 @@
1
+ export const MAX_GATE_ASKS = 2;
2
+ /** Plan items named in the message; a longer plan is counted, not listed. */
3
+ const MAX_NAMED_TODOS = 8;
4
+ /** Undefined when the handoff passes every gate. */
5
+ export function finalAnswerGate(input) {
6
+ const unfinished = input.todos.filter(todo => todo.status !== 'completed');
7
+ const failed = [...(input.summaryStoodIn ? ['summary'] : []), ...(unfinished.length ? ['todos'] : [])];
8
+ if (!failed.length)
9
+ return undefined;
10
+ const gates = failed.filter(gate => (input.asked?.[gate] ?? 0) < MAX_GATE_ASKS);
11
+ const waived = failed.filter(gate => !gates.includes(gate));
12
+ if (!gates.length)
13
+ return { gates, waived, message: '' };
14
+ const parts = [];
15
+ if (gates.includes('summary')) {
16
+ parts.push('It has no summary. The summary is the final answer the user reads; without one they see only the raw output object. Send summary as markdown (the outcome first, then what changed, how it was verified, and anything not done) and tests as one line per check that ran, or [] when none did, beside outcome and output.');
17
+ }
18
+ if (gates.includes('todos')) {
19
+ // Ids and statuses only: the plan's text is model-authored and is already in the todo snapshot.
20
+ const named = unfinished.slice(0, MAX_NAMED_TODOS).map(todo => `${todo.id} (${todo.status})`).join(', ');
21
+ const more = unfinished.length > MAX_NAMED_TODOS ? `, and ${unfinished.length - MAX_NAMED_TODOS} more` : '';
22
+ parts.push(`The plan still lists ${unfinished.length} unfinished ${unfinished.length === 1 ? 'item' : 'items'}: ${named}${more}. Do the work that is left, using tools. For work that is already done, send update_todos with the true statuses in the same batch as complete_agent. If an item cannot be finished, leave it open and name it under "## Not done" in the summary.`);
23
+ }
24
+ return { gates, waived, message: `Completion not accepted yet. ${parts.join(' ')} Then call complete_agent again.` };
25
+ }
@@ -17,6 +17,12 @@ export declare const SUMMARY_DESCRIPTION = "Markdown shown to the user as the fi
17
17
  export declare const COMPLETION_GUIDANCE = "Finish with complete_agent alone or final JSON. Todos/artifacts do not finish a node. Compare deliverables and verification evidence with acceptance criteria. Fulfill assigned requirements: intake/research nodes hand off downstream work; implementation nodes finish implementation and verification, not a progress checkpoint. Continue available work. For a concrete external blocker, report the blocker and unfinished work honestly. Use a blocked outcome if available; otherwise the sole outcome permits a terminal report, not a claim that the task is done. Only when this node is responsible for producing the final user answer, its summary must satisfy the user's response requirements: include complete requested files and exact formatting, including requested code fences, without abbreviation, path substitution, or offers to provide content later. Each fence opens and closes on its own line; a file written to the workspace that the user did not ask to see in the answer is named by path, not reproduced. Intermediate intake, research, and delegation nodes must instead keep a concise handoff and preserve these final-answer acceptance requirements in the downstream task instruction or output; do not implement or reproduce the final deliverable before handing off. Preserve required fields and valid JSON; escape quotes and Windows backslashes or use C:/repo/file.ts, and write each summary line break as \\n rather than dropping it. Never claim unperformed work.";
18
18
  /** Control-plane completion remains available when the execution-tool budget is exhausted. */
19
19
  export declare function completionTool(options: RunOptions): ToolSchema;
20
+ /**
21
+ * Recorded when an envelope carried no summary and its serialized output is shown as the answer.
22
+ * The node that ends a run sends such a handoff back for a real summary (completion-gates.ts); a
23
+ * handoff between nodes keeps the stand-in, since the next node reads the output itself.
24
+ */
25
+ export declare const OUTPUT_STOOD_IN_NOTE = "completion had no summary; its serialized output stands in as the answer";
20
26
  export declare const COMPLETION_ALONE_ERROR = "complete_agent must be called alone; no tools in this batch were executed.";
21
27
  /**
22
28
  * Only a direct, sole model control call can request completion, never a tool observation.
@@ -81,6 +81,12 @@ export function completionTool(options) {
81
81
  },
82
82
  };
83
83
  }
84
+ /**
85
+ * Recorded when an envelope carried no summary and its serialized output is shown as the answer.
86
+ * The node that ends a run sends such a handoff back for a real summary (completion-gates.ts); a
87
+ * handoff between nodes keeps the stand-in, since the next node reads the output itself.
88
+ */
89
+ export const OUTPUT_STOOD_IN_NOTE = 'completion had no summary; its serialized output stands in as the answer';
84
90
  export const COMPLETION_ALONE_ERROR = 'complete_agent must be called alone; no tools in this batch were executed.';
85
91
  /**
86
92
  * Only a direct, sole model control call can request completion, never a tool observation.
@@ -511,6 +517,29 @@ function splitFusedArguments(envelope, notes) {
511
517
  notes?.push(`completion fields ${fields.map(([name]) => name).join(', ')} arrived fused into one key by leaked argument markup and were split apart`);
512
518
  }
513
519
  }
520
+ /**
521
+ * A summary that carries the completion envelope itself. GLM-5.3-Flash on GX10 sent its whole
522
+ * envelope, escaped once more, as the single `summary` argument of complete_agent: the answer, then
523
+ * `","tests":[…],"outcome":"completed","output":{…},"artifacts":[]}`, with the envelope nested again
524
+ * under `output.summary`. The double-escape decode made the text readable, the envelope accepted a
525
+ * nonempty summary with no tests, and the transcript showed the answer followed by raw JSON — in
526
+ * three turns of one session. The nesting is recursive, so no unwrap recovers a clean answer; the
527
+ * completion is rejected and the model resends the fields as separate arguments.
528
+ *
529
+ * The test is a field separator — a closing quote, a comma, and an envelope key — outside code, so a
530
+ * summary that shows a completion in inline code or a fenced block is left alone.
531
+ */
532
+ const EMBEDDED_ENVELOPE_FIELD = /"\s*,\s*"(tests|outcome|output|artifacts)"\s*:/;
533
+ function rejectEmbeddedEnvelope(summary) {
534
+ let field;
535
+ mapOutsideCode(summary, prose => {
536
+ field ??= EMBEDDED_ENVELOPE_FIELD.exec(prose)?.[1];
537
+ return prose;
538
+ });
539
+ if (field !== undefined)
540
+ throw new Error(`Completion summary contains the completion envelope itself (its "${field}" field and what follows were written inside the summary string). Send summary, tests, outcome and output as separate complete_agent arguments: summary holds only the answer text in markdown, with no JSON fields after it.`);
541
+ return summary;
542
+ }
514
543
  /**
515
544
  * Parse one completion, accepting mechanically imperfect envelopes that are semantically correct.
516
545
  *
@@ -590,14 +619,18 @@ export function parseCompletion(text, options, reject, notes, stopReason) {
590
619
  // empty output put a bare "{}" on screen as the result of a run that had done its work.
591
620
  if (written === undefined && !Object.keys(output).some(key => key !== 'originalTask' || options.canonicalTask === undefined))
592
621
  throw new Error('Completion has no summary and an empty output, so it hands off nothing; put the final answer in summary');
593
- const summary = written ?? JSON.stringify(output).slice(0, 2000);
594
- return { summary: decodeDoubleEscapedSummary(summary, notes),
622
+ // Only text the model wrote as its answer is checked: the stand-in below is the output itself,
623
+ // serialized, and an output field named `tests` is legitimate there.
624
+ if (written === undefined)
625
+ notes?.push(OUTPUT_STOOD_IN_NOTE);
626
+ const summary = written === undefined ? decodeDoubleEscapedSummary(JSON.stringify(output).slice(0, 2000), notes) : rejectEmbeddedEnvelope(decodeDoubleEscapedSummary(written, notes));
627
+ return { summary,
595
628
  tests: Array.isArray(value.tests) && value.tests.every((item) => typeof item === 'string') ? value.tests : [], outcome, output,
596
629
  artifacts: value.artifacts ?? [] };
597
630
  }
598
631
  if (value && typeof value.summary === 'string' && value.summary.trim()
599
632
  && Array.isArray(value.tests) && value.tests.every((x) => typeof x === 'string')) {
600
- return { summary: decodeDoubleEscapedSummary(value.summary, notes), tests: value.tests };
633
+ return { summary: rejectEmbeddedEnvelope(decodeDoubleEscapedSummary(value.summary, notes)), tests: value.tests };
601
634
  }
602
635
  throw new Error("Completion needs a nonempty summary and a tests array of strings");
603
636
  }
@@ -132,7 +132,7 @@ export declare function validateWebSearchConfig(value: unknown): WebSearchConfig
132
132
  export declare const MAX_SYSTEM_PROMPT_OVERRIDE = 16000;
133
133
  export declare const AUTO_ARCHIVE_MIN_DAYS = 1;
134
134
  export declare const AUTO_ARCHIVE_MAX_DAYS = 30;
135
- export declare function configDirectory(): string;
135
+ export declare function configDirectory(environment?: NodeJS.ProcessEnv): string;
136
136
  export declare function validateConfig(value: unknown): Config;
137
137
  /**
138
138
  * The saved external-subagent pair follows the providers it names.
@@ -83,8 +83,8 @@ export function validateWebSearchConfig(value) {
83
83
  export const MAX_SYSTEM_PROMPT_OVERRIDE = 16_000;
84
84
  export const AUTO_ARCHIVE_MIN_DAYS = 1;
85
85
  export const AUTO_ARCHIVE_MAX_DAYS = 30;
86
- export function configDirectory() {
87
- return process.env.ANDORRACODE_HOME || join(homedir(), '.andorracode');
86
+ export function configDirectory(environment = process.env) {
87
+ return environment.ANDORRACODE_HOME || join(homedir(), '.andorracode');
88
88
  }
89
89
  function privateHttpHost(host) {
90
90
  const address = host.replace(/^\[|\]$/g, '').toLowerCase();
@@ -37,3 +37,14 @@ export declare function microcompactToolResults(messages: Message[], threshold:
37
37
  observations: number;
38
38
  removedChars: number;
39
39
  };
40
+ /**
41
+ * The accounting fields a `decision.turn_bypassed` event carries: the input the skipped request
42
+ * would have sent, and the provider and model it would have gone to. The Usage dashboard counts
43
+ * them as the bypass's avoided input; an event without them falls back to the node's last measured
44
+ * input. An estimate that is missing or not a positive whole number is left out, never sent as zero.
45
+ */
46
+ export declare function bypassAccounting(estimatedInputTokens: number | undefined, providerId: string | undefined, model: string | undefined): {
47
+ estimatedInputTokens?: number;
48
+ providerId?: string;
49
+ model?: string;
50
+ };
@@ -166,3 +166,16 @@ export function microcompactToolResults(messages, threshold, toolChars, inherite
166
166
  }
167
167
  return { observations, removedChars };
168
168
  }
169
+ /**
170
+ * The accounting fields a `decision.turn_bypassed` event carries: the input the skipped request
171
+ * would have sent, and the provider and model it would have gone to. The Usage dashboard counts
172
+ * them as the bypass's avoided input; an event without them falls back to the node's last measured
173
+ * input. An estimate that is missing or not a positive whole number is left out, never sent as zero.
174
+ */
175
+ export function bypassAccounting(estimatedInputTokens, providerId, model) {
176
+ return {
177
+ ...(estimatedInputTokens !== undefined && Number.isSafeInteger(estimatedInputTokens) && estimatedInputTokens > 0 ? { estimatedInputTokens } : {}),
178
+ ...(providerId ? { providerId } : {}),
179
+ ...(model ? { model } : {}),
180
+ };
181
+ }
@@ -14,8 +14,12 @@ export type DecisionObservation = {
14
14
  latencyMs?: number;
15
15
  };
16
16
  export type DecisionObserver = (observation: DecisionObservation) => void;
17
+ /** The caller's absolute deadline (epoch ms); work past it is discarded. */
18
+ export type DecisionRequestOptions = {
19
+ deadlineAt?: number;
20
+ };
17
21
  export interface DecisionProvider {
18
- evaluate(state: DecisionState, questions: DecisionQuestion[], signal?: AbortSignal, observe?: DecisionObserver): Promise<DecisionBatch>;
22
+ evaluate(state: DecisionState, questions: DecisionQuestion[], signal?: AbortSignal, observe?: DecisionObserver, options?: DecisionRequestOptions): Promise<DecisionBatch>;
19
23
  /** Optional compact, versioned tool-menu evidence; never execution authority. */
20
24
  evaluateToolMenu?(request: ToolRouteRequest, signal?: AbortSignal, observe?: DecisionObserver): Promise<ToolRouteEvidence>;
21
25
  /** One literal fact on its own minimal state; resolves to the probability that it is true. */
@@ -13,6 +13,7 @@ export declare class DecisionManager {
13
13
  private readonly provider;
14
14
  private readonly onEvent?;
15
15
  private readonly factGates;
16
+ private warnedSkillLimit;
16
17
  constructor(options?: {
17
18
  config?: DecisionConfig;
18
19
  provider?: DecisionProvider;
@@ -6,6 +6,7 @@ import { NoOpDecisionProvider } from './providers/NoOpDecisionProvider.js';
6
6
  import { DECISION_DEFAULTS } from './types.js';
7
7
  import { factProbability } from './facts.js';
8
8
  import { FactServiceGate } from './FactServiceGate.js';
9
+ import { HOSTED_SKILL_LIMIT, hostedSkillLimitNotice, rankHostedSkills } from './hostedSkills.js';
9
10
  import { markFactGuidance } from './guidancePolicy.js';
10
11
  import { actionablePreflightQuestion, answerOnlyTask } from './optimizationPolicy.js';
11
12
  import { parseToolRouteEvidence } from './routeTools.js';
@@ -60,6 +61,7 @@ export class DecisionManager {
60
61
  provider;
61
62
  onEvent;
62
63
  factGates = new Map();
64
+ warnedSkillLimit = false;
63
65
  constructor(options = {}) {
64
66
  validateDecisionConfig(options.config ?? {});
65
67
  this.config = structuredClone({ ...options.config, mode: options.config?.mode ?? DECISION_DEFAULTS.mode, provider: options.config?.provider ?? DECISION_DEFAULTS.provider, requestTimeoutMs: options.config?.requestTimeoutMs ?? DECISION_DEFAULTS.requestTimeoutMs });
@@ -103,6 +105,10 @@ export class DecisionManager {
103
105
  const snapshot = structuredClone(state);
104
106
  snapshot.capabilities.subagentRoles = decisionRoleChoices(snapshot.capabilities.subagentRoles, this.config.provider);
105
107
  const emit = this.events(identity, 'preflight', sink, applicationSink);
108
+ const installedSkills = snapshot.capabilities.skills?.length ?? 0;
109
+ if (this.config.provider === 'andorra' && snapshot.capabilities.skills && installedSkills > HOSTED_SKILL_LIMIT) {
110
+ snapshot.capabilities.skills = rankHostedSkills(snapshot.capabilities.skills, snapshot.task);
111
+ }
106
112
  const questions = preflightQuestions(this.config, snapshot.capabilities.subagentRoles, snapshot.capabilities)
107
113
  .filter(question => !this.active || this.config.provider !== 'laya' || question.id === 'needs_codegraph' || question.id === 'needs_memory')
108
114
  .filter(question => !this.active || this.config.provider !== 'andorra' || (question.id === 'needs_codegraph' ? snapshot.repository.codeGraphAvailable : question.id === 'needs_memory' ? snapshot.repository.memoryAvailable : true))
@@ -113,6 +119,11 @@ export class DecisionManager {
113
119
  emit('decision.skipped', { reason: 'no_actionable_consumer' });
114
120
  return baseline;
115
121
  }
122
+ if (installedSkills > HOSTED_SKILL_LIMIT && !this.warnedSkillLimit && questions.some(question => question.id === 'skill_role')) {
123
+ // Once per manager: the limit is a property of the installation, not of each request.
124
+ this.warnedSkillLimit = true;
125
+ emit('decision.skills_truncated', { installed: installedSkills, considered: HOSTED_SKILL_LIMIT, text: hostedSkillLimitNotice(installedSkills) });
126
+ }
116
127
  const batch = await this.request(snapshot, questions, signal, emit);
117
128
  if (!batch || signal.aborted)
118
129
  return baseline;
@@ -220,7 +231,7 @@ export class DecisionManager {
220
231
  return undefined;
221
232
  snapshot = structuredClone(snapshot);
222
233
  delete snapshot.consumers;
223
- return this.settle(questions.map(q => q.id), controllerSignal => this.provider.evaluate(structuredClone(snapshot), structuredClone(questions), controllerSignal, this.observer(emit)), value => validateBatch(value, questions), batch => Object.fromEntries(Object.entries(batch).map(([id, r]) => [id, r.type === 'noul' ? { probability: r.probability } : r.type === 'score' ? { score: r.score, confidence: r.confidence } : { ...(id === 'verification_tier' ? { choice: r.choice } : {}), confidence: r.confidence, selected: r.probabilities[r.choice] ?? 0 }])), signal, emit, this.config.requestTimeoutMs ?? DECISION_DEFAULTS.requestTimeoutMs);
234
+ return this.settle(questions.map(q => q.id), (controllerSignal, deadlineAt) => this.provider.evaluate(structuredClone(snapshot), structuredClone(questions), controllerSignal, this.observer(emit), { deadlineAt }), value => validateBatch(value, questions), batch => Object.fromEntries(Object.entries(batch).map(([id, r]) => [id, r.type === 'noul' ? { probability: r.probability } : r.type === 'score' ? { score: r.score, confidence: r.confidence } : { ...(id === 'verification_tier' ? { choice: r.choice } : {}), confidence: r.confidence, selected: r.probabilities[r.choice] ?? 0 }])), signal, emit, this.config.requestTimeoutMs ?? DECISION_DEFAULTS.requestTimeoutMs);
224
235
  }
225
236
  async settle(questionIds, evaluate, validate, describe, signal, emit, timeoutMs) {
226
237
  emit('decision.requested', { questions: questionIds });
@@ -249,7 +260,7 @@ export class DecisionManager {
249
260
  cancel();
250
261
  return;
251
262
  }
252
- void Promise.resolve().then(() => finished ? undefined : evaluate(controller.signal)).then(value => {
263
+ void Promise.resolve().then(() => finished ? undefined : evaluate(controller.signal, started + timeoutMs)).then(value => {
253
264
  if (finished)
254
265
  return;
255
266
  let validated;
@@ -268,7 +279,7 @@ export class DecisionManager {
268
279
  if (finished)
269
280
  return;
270
281
  cleanup();
271
- const safe = ['authentication_required', 'decision_daily_limit_reached', 'decision_service_unavailable', 'decision_protocol_unsupported', 'decision_input_too_large', 'invalid_response'];
282
+ const safe = ['authentication_required', 'decision_daily_limit_reached', 'decision_window_limit_reached', 'decision_service_unavailable', 'decision_protocol_unsupported', 'decision_input_too_large', 'invalid_response'];
272
283
  const reason = this.config.provider === 'andorra' && error instanceof Error && safe.includes(error.message) ? error.message : 'provider_error';
273
284
  const status = error && typeof error === 'object' ? error.httpStatus : undefined;
274
285
  const details = typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599 ? { httpStatus: status } : {};
@@ -137,6 +137,12 @@ export declare class FactContinuations {
137
137
  private followUps;
138
138
  private followUpPassed?;
139
139
  private nextNudge?;
140
+ /**
141
+ * The model has run a check of its own and read the result. Until then a finish reminder after an
142
+ * edit invites a plan whose checks the model never sees run: on Terminal-Bench runs it finished
143
+ * after its first write, on checks that passed but did not test what the task asked.
144
+ */
145
+ private modelSawCheck;
140
146
  /** The final answer the model already wrote; a later plan may omit it instead of sending it again. */
141
147
  private draft?;
142
148
  /** Commands the model named as its verification that no runner pattern recognizes, by check key. */
@@ -219,6 +219,12 @@ export class FactContinuations {
219
219
  followUps = 0;
220
220
  followUpPassed;
221
221
  nextNudge;
222
+ /**
223
+ * The model has run a check of its own and read the result. Until then a finish reminder after an
224
+ * edit invites a plan whose checks the model never sees run: on Terminal-Bench runs it finished
225
+ * after its first write, on checks that passed but did not test what the task asked.
226
+ */
227
+ modelSawCheck = false;
222
228
  /** The final answer the model already wrote; a later plan may omit it instead of sending it again. */
223
229
  draft;
224
230
  /** Commands the model named as its verification that no runner pattern recognizes, by check key. */
@@ -458,6 +464,8 @@ export class FactContinuations {
458
464
  this.checks.delete(key); // Re-inserted last, so the map's order is the order checks ran.
459
465
  this.checks.set(key, { call, passed, pure, source, revision: this.revision, seq: ++this.checkSeq, evidence: `${description(call).split('\n')[0].slice(0, 200)}: ${passed === true ? 'passed' : passed === false ? 'failed' : 'unconfirmed'}` });
460
466
  }
467
+ if (modelChecked)
468
+ this.modelSawCheck = true;
461
469
  if (automatic?.kind === 'recheck' && automatic.tool && !failed.length) {
462
470
  const evidence = this.checks.get(checkKey(automatic.tool));
463
471
  if (evidence?.passed === true && evidence.revision === this.revision)
@@ -537,7 +545,7 @@ export class FactContinuations {
537
545
  if (!this.taskUpdated && !this.plan && !this.staged && !unstarted && !this.constraints.noChecks) {
538
546
  if (!automatic && [...this.checks.values()].some(e => e.passed === false && e.revision === this.revision && e.seq > this.checkSeq - work.length) && modelChecked)
539
547
  this.nextNudge = 'after_failed_check';
540
- else if (!failed.length && wrote && !modelChecked)
548
+ else if (!failed.length && wrote && !modelChecked && this.modelSawCheck)
541
549
  this.nextNudge = 'after_write';
542
550
  }
543
551
  // After edits the model's next move is most often its own check again. Running it here costs
@@ -31,7 +31,7 @@ export class FactServiceGate {
31
31
  this.reason = reason;
32
32
  // A new run gets a fresh gate. An unsupported protocol or rejected credentials cannot be
33
33
  // repaired by repeatedly issuing the same request inside the current run.
34
- this.until = ['decision_protocol_unsupported', 'authentication_required', 'decision_daily_limit_reached', 'provider_unavailable'].includes(reason)
34
+ this.until = ['decision_protocol_unsupported', 'authentication_required', 'decision_daily_limit_reached', 'decision_window_limit_reached', 'provider_unavailable'].includes(reason)
35
35
  ? Infinity : this.now() + 30_000;
36
36
  }
37
37
  }
@@ -0,0 +1,37 @@
1
+ import type { DecisionResult } from './types.js';
2
+ /** Skills one hosted request may describe: the proxy's 32-choice limit less the `none` choice. */
3
+ export declare const HOSTED_SKILLS_PER_REQUEST = 31;
4
+ /** Proxies deployed before the 31-skill contract reject a request describing more than 16 skills. */
5
+ export declare const LEGACY_HOSTED_SKILLS_PER_REQUEST = 16;
6
+ /** Parallel skill requests per preflight; each one counts against the account's daily decisions. */
7
+ export declare const HOSTED_SKILL_BATCHES = 4;
8
+ export declare const HOSTED_SKILL_LIMIT: number;
9
+ type ChoiceAnswer = Extract<DecisionResult, {
10
+ type: 'choice';
11
+ }>;
12
+ /**
13
+ * The skills Jev considers when more are installed than it can evaluate: the ones whose name and
14
+ * description share the most words with the task, ties kept in discovery order.
15
+ */
16
+ export declare function rankHostedSkills<T extends {
17
+ id: string;
18
+ description: string;
19
+ }>(skills: T[], task: string, limit?: number): T[];
20
+ /** The one-time warning when more skills are installed than Jev evaluates; the CLI and desktop show it as written. */
21
+ export declare function hostedSkillLimitNotice(installed: number): string;
22
+ /**
23
+ * Batches covering the first HOSTED_SKILL_LIMIT skills. At the contract size that is HOSTED_SKILL_BATCHES
24
+ * requests; against a proxy still limited to 16 it takes more, so no skill below the limit is dropped.
25
+ */
26
+ export declare function chunkSkills(ids: string[], size: number): string[][];
27
+ /** A batch's answer restated over every original choice; skills it did not see score zero. */
28
+ export declare function expandSkillAnswer(answer: ChoiceAnswer, choices: string[]): ChoiceAnswer;
29
+ /**
30
+ * When no batch picked a skill: `none` keeps the least certain batch's probability, and the rest is
31
+ * shared across the skills in proportion to their batch scores, so the routing threshold still sees
32
+ * the weakest batch's doubt.
33
+ */
34
+ export declare function mergeNoSkill(answers: ChoiceAnswer[], choices: string[]): ChoiceAnswer;
35
+ /** No skill, stated with zero confidence so routing never acts on it. */
36
+ export declare function abstainSkill(choices: string[]): ChoiceAnswer;
37
+ export {};
@@ -0,0 +1,64 @@
1
+ /** Skills one hosted request may describe: the proxy's 32-choice limit less the `none` choice. */
2
+ export const HOSTED_SKILLS_PER_REQUEST = 31;
3
+ /** Proxies deployed before the 31-skill contract reject a request describing more than 16 skills. */
4
+ export const LEGACY_HOSTED_SKILLS_PER_REQUEST = 16;
5
+ /** Parallel skill requests per preflight; each one counts against the account's daily decisions. */
6
+ export const HOSTED_SKILL_BATCHES = 4;
7
+ export const HOSTED_SKILL_LIMIT = HOSTED_SKILLS_PER_REQUEST * HOSTED_SKILL_BATCHES;
8
+ const words = (text) => new Set(text.toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) ?? []);
9
+ /**
10
+ * The skills Jev considers when more are installed than it can evaluate: the ones whose name and
11
+ * description share the most words with the task, ties kept in discovery order.
12
+ */
13
+ export function rankHostedSkills(skills, task, limit = HOSTED_SKILL_LIMIT) {
14
+ if (skills.length <= limit)
15
+ return skills;
16
+ const taskWords = words(task);
17
+ const score = (skill) => { let hits = 0; for (const word of words(`${skill.id} ${skill.description}`))
18
+ if (taskWords.has(word))
19
+ hits++; return hits; };
20
+ return skills.map((skill, index) => ({ skill, index, score: score(skill) }))
21
+ .sort((a, b) => b.score - a.score || a.index - b.index).slice(0, limit).map(entry => entry.skill);
22
+ }
23
+ /** The one-time warning when more skills are installed than Jev evaluates; the CLI and desktop show it as written. */
24
+ export function hostedSkillLimitNotice(installed) {
25
+ return `[Jev] ${installed} skills are installed, but Jev evaluates at most ${HOSTED_SKILL_LIMIT} `
26
+ + `(${HOSTED_SKILL_BATCHES} batches of ${HOSTED_SKILLS_PER_REQUEST}). It uses the ${HOSTED_SKILL_LIMIT} that best match the task; `
27
+ + `the other ${installed - HOSTED_SKILL_LIMIT} are not considered.`;
28
+ }
29
+ /**
30
+ * Batches covering the first HOSTED_SKILL_LIMIT skills. At the contract size that is HOSTED_SKILL_BATCHES
31
+ * requests; against a proxy still limited to 16 it takes more, so no skill below the limit is dropped.
32
+ */
33
+ export function chunkSkills(ids, size) {
34
+ const covered = ids.slice(0, HOSTED_SKILL_LIMIT), chunks = [];
35
+ for (let start = 0; start < covered.length; start += size)
36
+ chunks.push(covered.slice(start, start + size));
37
+ return chunks;
38
+ }
39
+ /** A batch's answer restated over every original choice; skills it did not see score zero. */
40
+ export function expandSkillAnswer(answer, choices) {
41
+ return { type: 'choice', choice: answer.choice, confidence: answer.confidence,
42
+ probabilities: Object.fromEntries(choices.map(choice => [choice, answer.probabilities[choice] ?? 0])) };
43
+ }
44
+ /**
45
+ * When no batch picked a skill: `none` keeps the least certain batch's probability, and the rest is
46
+ * shared across the skills in proportion to their batch scores, so the routing threshold still sees
47
+ * the weakest batch's doubt.
48
+ */
49
+ export function mergeNoSkill(answers, choices) {
50
+ const none = Math.min(...answers.map(answer => answer.probabilities.none ?? 0));
51
+ const scores = new Map();
52
+ for (const answer of answers)
53
+ for (const [choice, probability] of Object.entries(answer.probabilities))
54
+ if (choice !== 'none')
55
+ scores.set(choice, probability);
56
+ const total = [...scores.values()].reduce((sum, value) => sum + value, 0);
57
+ const rest = 1 - none;
58
+ return { type: 'choice', choice: 'none', confidence: Math.min(...answers.map(answer => answer.confidence)),
59
+ probabilities: Object.fromEntries(choices.map(choice => [choice, choice === 'none' ? (total > 0 ? none : 1) : total > 0 ? rest * (scores.get(choice) ?? 0) / total : 0])) };
60
+ }
61
+ /** No skill, stated with zero confidence so routing never acts on it. */
62
+ export function abstainSkill(choices) {
63
+ return { type: 'choice', choice: 'none', confidence: 0, probabilities: Object.fromEntries(choices.map(choice => [choice, choice === 'none' ? 1 : 0])) };
64
+ }
@@ -1,4 +1,4 @@
1
- import type { DecisionProvider, DecisionObserver } from '../DecisionEngine.js';
1
+ import type { DecisionProvider, DecisionObserver, DecisionRequestOptions } from '../DecisionEngine.js';
2
2
  import type { DecisionBatch, DecisionQuestion, DecisionState } from '../types.js';
3
3
  import { type FactRequest } from '../facts.js';
4
4
  import { type ToolRouteRequest, type ToolRouteEvidence } from '../routeTools.js';
@@ -10,7 +10,15 @@ export declare class AndorraDecisionProvider implements DecisionProvider {
10
10
  apiBaseUrl: string;
11
11
  fetch: typeof fetch;
12
12
  } | undefined);
13
- evaluate(state: DecisionState, questions: DecisionQuestion[], signal?: AbortSignal, observe?: DecisionObserver): Promise<DecisionBatch>;
13
+ evaluate(state: DecisionState, questions: DecisionQuestion[], signal?: AbortSignal, observe?: DecisionObserver, options?: DecisionRequestOptions): Promise<DecisionBatch>;
14
+ /**
15
+ * The skill question split into parallel requests of `size` skills, covering at most HOSTED_SKILL_LIMIT
16
+ * skills. The first request also carries every other question and runs on the caller's signal; the
17
+ * skill-only ones run on `skillSignal`. Each batch's probabilities only compare the skills it saw, so
18
+ * when two or more batches pick a skill their winners go to one final request.
19
+ */
20
+ private evaluateBatched;
21
+ private evaluateOnce;
14
22
  evaluateFact(fact: FactRequest, signal?: AbortSignal, observe?: DecisionObserver): Promise<number>;
15
23
  evaluateToolMenu(request: ToolRouteRequest, signal?: AbortSignal, observe?: DecisionObserver): Promise<ToolRouteEvidence>;
16
24
  private post;