@andorra-labs/code 0.1.6 → 0.1.7

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 (108) hide show
  1. package/dist/src/agent-execution.js +404 -25
  2. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  3. package/dist/src/agent-mcp-catalog.js +40 -0
  4. package/dist/src/agent-mcp.d.ts +19 -3
  5. package/dist/src/agent-mcp.js +18 -44
  6. package/dist/src/app-server/protocol.d.ts +25 -3
  7. package/dist/src/app-server/protocol.js +5 -1
  8. package/dist/src/app-server/workspace.d.ts +8 -1
  9. package/dist/src/app-server/workspace.js +43 -2
  10. package/dist/src/app-server.js +88 -3
  11. package/dist/src/auth/AuthManager.d.ts +33 -1
  12. package/dist/src/auth/AuthManager.js +138 -10
  13. package/dist/src/auth/callback-page.d.ts +4 -0
  14. package/dist/src/auth/callback-page.js +70 -0
  15. package/dist/src/auth/callback.d.ts +39 -0
  16. package/dist/src/auth/callback.js +146 -22
  17. package/dist/src/auth/index.d.ts +10 -6
  18. package/dist/src/auth/index.js +2 -2
  19. package/dist/src/auth/store.d.ts +142 -3
  20. package/dist/src/auth/store.js +334 -13
  21. package/dist/src/auth/types.d.ts +17 -1
  22. package/dist/src/auth-commands.d.ts +11 -2
  23. package/dist/src/auth-commands.js +14 -7
  24. package/dist/src/automation-tool.js +10 -2
  25. package/dist/src/automations.d.ts +5 -0
  26. package/dist/src/automations.js +10 -0
  27. package/dist/src/capabilities.d.ts +9 -3
  28. package/dist/src/capabilities.js +7 -3
  29. package/dist/src/cli.js +31 -4
  30. package/dist/src/codex-provider.js +12 -0
  31. package/dist/src/coding-tools.d.ts +5 -0
  32. package/dist/src/coding-tools.js +54 -48
  33. package/dist/src/commands.d.ts +5 -1
  34. package/dist/src/commands.js +7 -6
  35. package/dist/src/completion.js +46 -0
  36. package/dist/src/config.d.ts +48 -0
  37. package/dist/src/config.js +248 -10
  38. package/dist/src/context-budget.d.ts +7 -0
  39. package/dist/src/context-budget.js +18 -1
  40. package/dist/src/decision/FactContinuations.d.ts +41 -6
  41. package/dist/src/decision/FactContinuations.js +211 -64
  42. package/dist/src/decision/PreparedSteps.js +3 -1
  43. package/dist/src/decision/checks.d.ts +25 -0
  44. package/dist/src/decision/checks.js +77 -6
  45. package/dist/src/delegation-changes.d.ts +109 -0
  46. package/dist/src/delegation-changes.js +431 -0
  47. package/dist/src/graph-server.d.ts +1 -0
  48. package/dist/src/graph-server.js +15 -3
  49. package/dist/src/graph-sync.d.ts +15 -0
  50. package/dist/src/graph-sync.js +50 -1
  51. package/dist/src/graph-tool.d.ts +52 -0
  52. package/dist/src/graph-tool.js +136 -0
  53. package/dist/src/graph-ui/app.js +212 -43
  54. package/dist/src/graph-ui/controls.js +6 -0
  55. package/dist/src/graph-ui/drafts.js +39 -0
  56. package/dist/src/graph-ui/embed.js +1 -1
  57. package/dist/src/graph-ui/index.html +2 -2
  58. package/dist/src/graph-ui/studio.css +7 -5
  59. package/dist/src/graph-ui/style.css +46 -12
  60. package/dist/src/graphs.d.ts +15 -2
  61. package/dist/src/graphs.js +42 -13
  62. package/dist/src/hardened-runtime.d.ts +4 -4
  63. package/dist/src/hardened-runtime.js +109 -9
  64. package/dist/src/powershell-pool.d.ts +9 -0
  65. package/dist/src/powershell-pool.js +16 -0
  66. package/dist/src/provider-keys.d.ts +48 -0
  67. package/dist/src/provider-keys.js +121 -0
  68. package/dist/src/pull-requests.d.ts +14 -5
  69. package/dist/src/pull-requests.js +28 -10
  70. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  71. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  72. package/dist/src/react-runtime.js +30 -2
  73. package/dist/src/read-image.d.ts +30 -0
  74. package/dist/src/read-image.js +97 -0
  75. package/dist/src/secret-redaction.d.ts +13 -0
  76. package/dist/src/secret-redaction.js +71 -0
  77. package/dist/src/session-summary.d.ts +10 -4
  78. package/dist/src/session-summary.js +14 -7
  79. package/dist/src/sessions.js +4 -1
  80. package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/telemetry/schema.d.ts +1 -1
  83. package/dist/src/telemetry/schema.js +1 -1
  84. package/dist/src/terminal-ui.d.ts +9 -0
  85. package/dist/src/terminal-ui.js +14 -0
  86. package/dist/src/tool-dependencies.js +4 -0
  87. package/dist/src/tools.d.ts +9 -0
  88. package/dist/src/tools.js +116 -11
  89. package/dist/src/transcript.js +5 -0
  90. package/dist/src/types.d.ts +13 -0
  91. package/dist/src/web-search.d.ts +59 -0
  92. package/dist/src/web-search.js +216 -0
  93. package/docs/agents/README.md +2 -2
  94. package/docs/agents/mcp-server.md +15 -2
  95. package/docs/concepts/README.md +1 -1
  96. package/docs/concepts/security.md +2 -2
  97. package/docs/getting-started/accounts.md +15 -4
  98. package/docs/getting-started/configure-providers.md +1 -1
  99. package/docs/guides/README.md +1 -0
  100. package/docs/guides/desktop-app.md +1 -1
  101. package/docs/guides/graph-builder.md +1 -1
  102. package/docs/guides/web-search.md +47 -0
  103. package/docs/reference/cli.md +4 -3
  104. package/docs/reference/config.md +3 -3
  105. package/docs/reference/slash-commands.md +2 -1
  106. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  107. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  108. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { validateEfficiencyConfig } from './efficiency.js';
2
2
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
- import { join } from 'node:path';
4
+ import { join, resolve } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { isIP } from 'node:net';
7
7
  import { assertProviderCredentials, assertRequestTimeout, assertStreamIdleTimeout, MAX_CODEX_ACCOUNT_KEY_LENGTH, MAX_PROVIDER_NAME_LENGTH, PROVIDER_TYPES, REASONING_EFFORTS } from './providers.js';
@@ -11,6 +11,7 @@ import { validateAnalyticsConfig } from './analytics.js';
11
11
  import { isPermissionMode } from './permissions.js';
12
12
  import { LIMIT_KEYS } from './limits.js';
13
13
  import { acquireSaveLock, SaveLockBusyError } from './save-lock.js';
14
+ import { PROVIDER_KEYS_IN_KEYRING, providerKeysBelongInKeyring, readProviderKeys, removeProviderKeys, restoreProviderKeys, storeProviderKeys } from './provider-keys.js';
14
15
  export const MAX_CAPSOLVER_API_KEY_LENGTH = 256;
15
16
  export function validateBrowserConfig(value) {
16
17
  const c = value;
@@ -23,6 +24,61 @@ export function validateBrowserConfig(value) {
23
24
  }
24
25
  return c;
25
26
  }
27
+ /** The search services the web_search tool can query, in the order "automatic" tries them. */
28
+ export const WEB_SEARCH_PROVIDERS = ['brave', 'tavily', 'exa', 'serper', 'google', 'searxng'];
29
+ /** The configuration field that holds each keyed service's API key. SearXNG takes a URL instead. */
30
+ export const WEB_SEARCH_KEY_FIELDS = {
31
+ brave: 'braveApiKey', tavily: 'tavilyApiKey', exa: 'exaApiKey', serper: 'serperApiKey', google: 'googleApiKey',
32
+ };
33
+ export const WEB_SEARCH_FIELDS = [...Object.values(WEB_SEARCH_KEY_FIELDS), 'defaultProvider', 'googleSearchEngineId', 'searxngUrl'];
34
+ export const MAX_WEB_SEARCH_API_KEY_LENGTH = 256;
35
+ export const MAX_WEB_SEARCH_URL_LENGTH = 2048;
36
+ /** A SearXNG base URL: HTTP(S), no credentials, query or fragment. Returns the normalized URL or an error message. */
37
+ export function checkSearxngUrl(value) {
38
+ let url;
39
+ try {
40
+ url = new URL(value.trim());
41
+ }
42
+ catch {
43
+ return { error: 'webSearch.searxngUrl must be an HTTP(S) URL such as http://localhost:8080' };
44
+ }
45
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
46
+ return { error: 'webSearch.searxngUrl must be an HTTP(S) URL' };
47
+ if (url.username || url.password)
48
+ return { error: 'webSearch.searxngUrl must not contain a user name or password' };
49
+ if (url.search || url.hash)
50
+ return { error: 'webSearch.searxngUrl must be the instance address, without a query or fragment' };
51
+ const normalized = url.href.replace(/\/+$/, '');
52
+ if (normalized.length > MAX_WEB_SEARCH_URL_LENGTH)
53
+ return { error: `webSearch.searxngUrl must be at most ${MAX_WEB_SEARCH_URL_LENGTH} characters` };
54
+ return { url: normalized };
55
+ }
56
+ export function validateWebSearchConfig(value) {
57
+ const c = value;
58
+ if (!c || typeof c !== 'object' || Array.isArray(c))
59
+ throw new Error('Invalid webSearch configuration');
60
+ const unknown = Object.keys(c).filter(key => !WEB_SEARCH_FIELDS.includes(key));
61
+ if (unknown.length)
62
+ throw new Error(`Unsupported webSearch configuration field: ${unknown.join(', ')}`);
63
+ if (c.defaultProvider !== undefined && !WEB_SEARCH_PROVIDERS.includes(c.defaultProvider)) {
64
+ throw new Error(`webSearch.defaultProvider must be one of ${WEB_SEARCH_PROVIDERS.join(', ')}`);
65
+ }
66
+ for (const field of Object.values(WEB_SEARCH_KEY_FIELDS)) {
67
+ const key = c[field];
68
+ if (key !== undefined && (typeof key !== 'string' || !key || key.length > MAX_WEB_SEARCH_API_KEY_LENGTH || /\s/.test(key))) {
69
+ throw new Error(`webSearch.${field} must be a key of 1 to ${MAX_WEB_SEARCH_API_KEY_LENGTH} characters without spaces`);
70
+ }
71
+ }
72
+ if (c.googleSearchEngineId !== undefined && (typeof c.googleSearchEngineId !== 'string' || !/^[A-Za-z0-9:_-]{1,128}$/.test(c.googleSearchEngineId))) {
73
+ throw new Error('webSearch.googleSearchEngineId must be the search engine ID (cx): up to 128 letters, digits, ":", "_" or "-"');
74
+ }
75
+ if (c.searxngUrl !== undefined) {
76
+ const checked = typeof c.searxngUrl === 'string' ? checkSearxngUrl(c.searxngUrl) : { error: 'webSearch.searxngUrl must be a string' };
77
+ if ('error' in checked)
78
+ throw new Error(checked.error);
79
+ }
80
+ return c;
81
+ }
26
82
  /** The longest override the setting accepts: the same bound the workspace guide is clipped to. */
27
83
  export const MAX_SYSTEM_PROMPT_OVERRIDE = 16_000;
28
84
  export const AUTO_ARCHIVE_MIN_DAYS = 1;
@@ -82,6 +138,8 @@ export function validateConfig(value) {
82
138
  validateLimitsConfig(c.limits);
83
139
  if (c.browser !== undefined)
84
140
  validateBrowserConfig(c.browser);
141
+ if (c.webSearch !== undefined)
142
+ validateWebSearchConfig(c.webSearch);
85
143
  if (c.extensions !== undefined) {
86
144
  if (!c.extensions || typeof c.extensions !== 'object' || Array.isArray(c.extensions))
87
145
  throw new Error('Invalid extensions configuration');
@@ -406,15 +464,128 @@ export function resolveMemoryConfig(config, env = process.env) {
406
464
  validateMemoryConfig(memory);
407
465
  return memory;
408
466
  }
409
- export async function loadConfig(directory = configDirectory()) {
467
+ /** Whether stored configuration text says its provider keys are in the OS credential store. */
468
+ function keysInKeyring(text) {
469
+ try {
470
+ return JSON.parse(text)?.providerKeys === PROVIDER_KEYS_IN_KEYRING;
471
+ }
472
+ catch {
473
+ return false;
474
+ }
475
+ }
476
+ /**
477
+ * Provider ids whose saved keys a save removed from the configuration but could not yet delete from
478
+ * the OS credential store. The file names them until a later save deletes them, because once the
479
+ * file stops naming a provider nothing else could find its key.
480
+ */
481
+ const PENDING_DELETION = 'providerKeysPendingDeletion';
482
+ function pendingDeletions(value) {
483
+ return Array.isArray(value) && value.every(id => typeof id === 'string') ? value : undefined;
484
+ }
485
+ function storedPendingDeletions(text) {
486
+ if (text === undefined)
487
+ return [];
410
488
  try {
411
- return validateConfig(JSON.parse(await readFile(join(directory, 'config.json'), 'utf8')));
489
+ return pendingDeletions(JSON.parse(text)?.[PENDING_DELETION]) ?? [];
490
+ }
491
+ catch {
492
+ return [];
493
+ }
494
+ }
495
+ /** Write configuration text and publish it with one rename. */
496
+ async function publishConfig(directory, text) {
497
+ const temporary = join(directory, `config-${randomUUID()}.tmp`);
498
+ await writeFile(temporary, text, { mode: 0o600 });
499
+ await rename(temporary, join(directory, 'config.json'));
500
+ }
501
+ /** The provider ids stored configuration text names, whatever else it holds. */
502
+ function storedProviderIds(text) {
503
+ try {
504
+ const providers = JSON.parse(text)?.providers;
505
+ return Array.isArray(providers) ? providers.flatMap(provider => typeof provider?.id === 'string' ? [provider.id] : []) : [];
506
+ }
507
+ catch {
508
+ return [];
509
+ }
510
+ }
511
+ /** A provider entry as written to disk once its key is in the OS credential store. */
512
+ function withoutApiKey(provider) {
513
+ const copy = { ...provider };
514
+ delete copy.apiKey;
515
+ return copy;
516
+ }
517
+ async function readStoredConfig(directory) {
518
+ let text;
519
+ try {
520
+ text = await readFile(join(directory, 'config.json'), 'utf8');
412
521
  }
413
522
  catch (error) {
414
523
  if (error.code === 'ENOENT')
415
- return { version: 1, provider: '', providers: [] };
524
+ return { config: { version: 1, provider: '', providers: [] }, plaintextKeys: false };
416
525
  throw error;
417
526
  }
527
+ const raw = JSON.parse(text);
528
+ // The marker is an on-disk detail: it is checked and removed here, so no configuration in memory carries it.
529
+ const marker = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw.providerKeys : undefined;
530
+ if (marker !== undefined) {
531
+ if (marker !== PROVIDER_KEYS_IN_KEYRING)
532
+ throw new Error('Invalid providerKeys configuration: the only value is "keyring"');
533
+ delete raw.providerKeys;
534
+ }
535
+ // Keys a save removed but could not yet delete: they are not read back, or the next save would
536
+ // take them for keys the user still has and cancel their deletion.
537
+ let pending = new Set();
538
+ if (raw && typeof raw === 'object' && !Array.isArray(raw) && raw[PENDING_DELETION] !== undefined) {
539
+ const ids = pendingDeletions(raw[PENDING_DELETION]);
540
+ if (!ids)
541
+ throw new Error(`Invalid ${PENDING_DELETION} configuration: expected a list of provider ids`);
542
+ pending = new Set(ids);
543
+ delete raw[PENDING_DELETION];
544
+ }
545
+ const config = validateConfig(raw);
546
+ const plaintextKeys = config.providers.some(provider => provider.apiKey !== undefined);
547
+ if (marker === PROVIDER_KEYS_IN_KEYRING) {
548
+ const keys = await readProviderKeys(directory, config.providers.filter(provider => provider.apiKey === undefined && !pending.has(provider.id)).map(provider => provider.id));
549
+ for (const provider of config.providers) {
550
+ const key = keys.get(provider.id);
551
+ // A key typed into the file by hand is newer than the saved one, and is moved on the next save.
552
+ if (key === undefined || provider.apiKey !== undefined)
553
+ continue;
554
+ // A provider edited by hand into a type that takes no key loads without it rather than failing.
555
+ try {
556
+ assertProviderCredentials({ ...provider, apiKey: key });
557
+ provider.apiKey = key;
558
+ }
559
+ catch { /* Left out; the next save drops it from the store. */ }
560
+ }
561
+ }
562
+ return { config, plaintextKeys };
563
+ }
564
+ /** Directories whose plaintext keys this process could not move, so a load does not retry on every call. */
565
+ const unmovedKeys = new Set();
566
+ /**
567
+ * The installation's configuration, with saved provider API keys read back from the OS credential
568
+ * store. A `config.json` that still holds keys in plaintext (written before keys moved to the
569
+ * store, or edited by hand) has them moved on this load; where that cannot happen, the keys stay in
570
+ * the file and the configuration loads exactly as before.
571
+ */
572
+ export async function loadConfig(directory = configDirectory()) {
573
+ const stored = await readStoredConfig(directory);
574
+ const key = resolve(directory);
575
+ if (stored.plaintextKeys && providerKeysBelongInKeyring() && !unmovedKeys.has(key)) {
576
+ try {
577
+ const moved = await withConfigLock(directory, async () => {
578
+ const current = await readStoredConfig(directory);
579
+ return current.plaintextKeys ? await writeConfig(current.config, directory) : true;
580
+ });
581
+ if (!moved)
582
+ unmovedKeys.add(key);
583
+ }
584
+ catch {
585
+ unmovedKeys.add(key);
586
+ }
587
+ }
588
+ return stored.config;
418
589
  }
419
590
  /**
420
591
  * The anonymous-feedback preference this installation has saved right now.
@@ -445,13 +616,79 @@ export async function loadSavedAnalytics(directory = configDirectory()) {
445
616
  validateAnalyticsConfig(parsed.analytics);
446
617
  return parsed.analytics;
447
618
  }
448
- /** Write the configuration and publish it with one rename; the caller owns the lock, or is the only writer. */
619
+ /**
620
+ * Write the configuration and publish it with one rename; the caller owns the lock, or is the only writer.
621
+ *
622
+ * Provider API keys go to the OS credential store first and the file records only that they are
623
+ * there, so a reader that sees the new file finds the keys it names. A key this configuration no
624
+ * longer holds is deleted from the store only after the file that drops it is published, so a save
625
+ * that fails or is interrupted leaves the previous configuration's keys in place; a save whose
626
+ * publication fails also puts back the keys it had already overwritten. Until that deletion
627
+ * succeeds the published file lists the providers in `providerKeysPendingDeletion`, so a save
628
+ * that could not delete them (a locked store, an interrupted process) is finished by the next one.
629
+ * Where keys cannot go to the
630
+ * store (see `storeProviderKeys`), they are written into the file as before.
631
+ * @returns whether every key this configuration holds is in the OS credential store.
632
+ */
449
633
  async function writeConfig(config, directory) {
450
634
  validateConfig(config);
451
635
  await mkdir(directory, { recursive: true });
452
- const temporary = join(directory, `config-${randomUUID()}.tmp`);
453
- await writeFile(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
454
- await rename(temporary, join(directory, 'config.json'));
636
+ const path = join(directory, 'config.json');
637
+ const previousText = await readFile(path, 'utf8').catch(() => undefined);
638
+ const previouslyInKeyring = previousText !== undefined && keysInKeyring(previousText);
639
+ const keys = new Map(config.providers.flatMap(provider => provider.apiKey === undefined ? [] : [[provider.id, provider.apiKey]]));
640
+ const previousIds = previouslyInKeyring ? storedProviderIds(previousText) : [];
641
+ // What the store holds now, so unchanged keys are not rewritten and a failed save can be undone;
642
+ // undefined when it cannot be read, and then every key is written and nothing is put back.
643
+ const current = previouslyInKeyring
644
+ ? await readProviderKeys(directory, [...new Set([...previousIds, ...keys.keys()])]).catch(() => undefined)
645
+ : new Map();
646
+ const heldBefore = current ? [...current.keys()] : previousIds;
647
+ let onDisk = config;
648
+ let inKeyring = true;
649
+ let drop = heldBefore;
650
+ let written = [];
651
+ const pendingBefore = storedPendingDeletions(previousText);
652
+ if (keys.size) {
653
+ if (await storeProviderKeys(directory, keys, current)) {
654
+ onDisk = { ...config, providers: config.providers.map(withoutApiKey), providerKeys: PROVIDER_KEYS_IN_KEYRING };
655
+ drop = heldBefore.filter(provider => !keys.has(provider));
656
+ written = [...keys].filter(([provider, key]) => current?.get(provider) !== key).map(([provider]) => provider);
657
+ }
658
+ else
659
+ inKeyring = false; // The keys go into the file, and the store's copies are dropped once it is published.
660
+ }
661
+ // Deletions an earlier save could not finish are retried, except for a provider whose key this
662
+ // save has just stored again.
663
+ drop = [...new Set([...drop, ...pendingBefore])].filter(provider => !inKeyring || !keys.has(provider));
664
+ const settled = JSON.stringify(onDisk, null, 2) + '\n';
665
+ const text = drop.length ? JSON.stringify({ ...onDisk, [PENDING_DELETION]: drop }, null, 2) + '\n' : settled;
666
+ if (text !== previousText) {
667
+ try {
668
+ await publishConfig(directory, text);
669
+ }
670
+ catch (error) {
671
+ if (current)
672
+ await restoreProviderKeys(directory, written, current);
673
+ throw error;
674
+ }
675
+ }
676
+ if (!drop.length)
677
+ return inKeyring;
678
+ // A key the user removed must not outlive the save that removed it; one that only moved into the
679
+ // file is already safe there, so failing to drop the store's copy does not fail the save. Either
680
+ // way the file keeps naming it, and the next save tries again.
681
+ try {
682
+ await removeProviderKeys(directory, drop);
683
+ }
684
+ catch (error) {
685
+ if (inKeyring)
686
+ throw error;
687
+ return inKeyring;
688
+ }
689
+ // Best-effort: a list left behind only makes the next save delete entries that are already gone.
690
+ await publishConfig(directory, settled).catch(() => { });
691
+ return inKeyring;
455
692
  }
456
693
  /** How long a write waits for another process's write before reporting the collision. */
457
694
  const LOCK_ATTEMPTS = 6;
@@ -503,11 +740,12 @@ export async function changeConfigFile(directory, change, attempts = 3) {
503
740
  return await withConfigLock(directory, async () => {
504
741
  for (let attempt = 0; attempt < attempts; attempt++) {
505
742
  const before = await read();
506
- const next = change(await loadConfig(directory));
743
+ // Read without moving plaintext keys: that move takes this same lock, and the write below makes it anyway.
744
+ const next = change((await readStoredConfig(directory)).config);
507
745
  if (await read() !== before)
508
746
  continue;
509
747
  await writeConfig(next, directory);
510
- return await loadConfig(directory);
748
+ return (await readStoredConfig(directory)).config;
511
749
  }
512
750
  throw new ConfigConflictError();
513
751
  });
@@ -2,6 +2,13 @@ import type { Message } from './types.js';
2
2
  /** Text budget projection: bounded native image bytes are never text tokens. */
3
3
  export declare function serializeContext(messages: Message[]): string;
4
4
  export declare function pruneHistoricalImages(messages: Message[], keepToolTurns?: number): number;
5
+ export declare const IMAGE_INPUT_REJECTED_NOTE = "[Image omitted: this model endpoint rejected image input. Inspect the image with a script or command instead.]";
6
+ /**
7
+ * Remove every native image once the provider has refused a request that carried one. The text
8
+ * of each message stays, with a note saying why its picture is gone, so the model changes
9
+ * approach instead of asking for the same image again.
10
+ */
11
+ export declare function dropRejectedImages(messages: Message[]): number;
5
12
  /** Conservative fallback including opaque continuation state (never returned). */
6
13
  export declare function estimateContextTokens(messages: Message[], toolChars: number): number;
7
14
  export declare function contextThreshold(contextWindow: number, outputReserve: number): number;
@@ -32,11 +32,28 @@ export function pruneHistoricalImages(messages, keepToolTurns = 5) {
32
32
  if (message.role === 'tool' && message.images?.length && (!retained || !calls.has(message.toolCallId ?? ''))) {
33
33
  images += message.images.length;
34
34
  delete message.images;
35
- message.content += '\n[Older screenshot omitted from active context; request a new screenshot for current visual state.]';
35
+ message.content += '\n[Older image omitted from active context; Read the file or take a new screenshot to see it again.]';
36
36
  }
37
37
  }
38
38
  return images;
39
39
  }
40
+ export const IMAGE_INPUT_REJECTED_NOTE = '[Image omitted: this model endpoint rejected image input. Inspect the image with a script or command instead.]';
41
+ /**
42
+ * Remove every native image once the provider has refused a request that carried one. The text
43
+ * of each message stays, with a note saying why its picture is gone, so the model changes
44
+ * approach instead of asking for the same image again.
45
+ */
46
+ export function dropRejectedImages(messages) {
47
+ let images = 0;
48
+ for (const message of messages) {
49
+ if (!message.images?.length)
50
+ continue;
51
+ images += message.images.length;
52
+ delete message.images;
53
+ message.content += `\n${IMAGE_INPUT_REJECTED_NOTE}`;
54
+ }
55
+ return images;
56
+ }
40
57
  /** Conservative fallback including opaque continuation state (never returned). */
41
58
  export function estimateContextTokens(messages, toolChars) {
42
59
  const contentTokens = estimateMessageTokens(messages.map(message => ({ role: message.role, content: message.content + (message.reasoningContent ?? '') + (message.providerContinuation ? JSON.stringify(message.providerContinuation) : ''), toolCalls: message.toolCalls?.map(call => { let input; try {
@@ -1,12 +1,16 @@
1
1
  export declare const PREPARE_FINISH = "prepare_finish";
2
- export declare const FACT_CONTINUATION_GUIDANCE = "Minimize model turns: batch independent reads and related file writes. Do not spend a turn only announcing a plan. When prepare_finish is available, implementation is finished and the verification is test, build, lint or typecheck commands, call prepare_finish LAST in the final edit batch (its description says how); for any other verification, finish normally. Do not add discretionary QA after the requested verification is sufficient. User instructions, workspace requirements and graph completion contracts still apply.";
2
+ export declare const FACT_CONTINUATION_GUIDANCE = "Minimize model turns: batch independent reads and related file writes. Do not spend a turn only announcing a plan. When prepare_finish is available, finish through it: put it LAST in the batch that makes your final edits, with the commands that verify the work and your final summary. The runtime runs them and completes the task without another model call, so do not run those commands yourself first, do not call complete_agent afterwards and do not add discretionary QA: one passing run of the checks the project already has is sufficient, so do not write throwaway scripts to prove the same thing again. If the verification is not a command, verify first, then call prepare_finish alone with checks []. After you edit files the runtime runs your latest check again by itself, so do not spend a turn rerunning it or marking todos done. Keep the final summary short, whatever other formatting guidance says: one or two sentences with the outcome, then at most five short bullets on what changed and how it was verified, about 100 words in all, with no headings, no code blocks, no restated diff and no remarks on things the task did not ask about (such as a pull request that was never requested), unless the user asked for that content. User instructions, workspace requirements and graph completion contracts still apply.";
3
+ /** What the model writes once as its final answer; a retry reuses it instead of sending it again. */
4
+ export declare const FINISH_SUMMARY_DESCRIPTION = "Final answer shown to the user, as Markdown with \\n line breaks: one or two sentences with the outcome, then at most five short bullets on what changed and how it was verified. About 100 words, no headings. Omit it on a retry to reuse the one already saved.";
3
5
  /** The tool description, naming the shell the model actually has. */
4
6
  export declare function prepareFinishDescription(shell?: string): string;
5
7
  /**
6
- * Repairs shape slips that would otherwise cost a whole coding-model turn, without changing what
7
- * runs: a note beside a check (`justification`, `description`), a check whose arguments were written
8
- * beside its name, a bare command given as the tool name, and evidence lines in completion.tests,
9
- * which the runtime fills in itself. Everything else is left for validation to reject.
8
+ * Brings what a model sends into the one shape `stage` validates, repairing slips that would
9
+ * otherwise cost a whole coding-model turn without changing what is verified: a check written as a
10
+ * command line (the advertised form), as `{command}`, with its arguments beside its name or with a
11
+ * note beside it; an output filter that would hide the exit status; the final answer written flat
12
+ * (`summary`) or as a JSON string; and evidence lines in `tests`, which the runtime fills in itself.
13
+ * Everything else is left for validation to reject.
10
14
  */
11
15
  export declare function prepareFinishArguments(args: unknown, tools: {
12
16
  has(name: string): boolean;
@@ -72,6 +76,8 @@ export interface Observation {
72
76
  localCheckStatus?: boolean;
73
77
  /** Runtime-derived exit status, for shells whose text output omits it (`Tool.exitZeroOnReturn`). */
74
78
  exitCode?: number;
79
+ /** How long the call ran, when the runtime measured it. */
80
+ durationMs?: number;
75
81
  }
76
82
  export type ContinuationEvidence = 'deterministic' | 'jev';
77
83
  export interface Continuation {
@@ -126,17 +132,46 @@ export declare class FactContinuations {
126
132
  private constraints;
127
133
  private syntheticCount;
128
134
  private finishHint;
135
+ /** The model's own most recent check, in the form the runtime may run again after an edit. */
136
+ private lastCheck?;
137
+ private followUps;
138
+ private followUpPassed?;
139
+ private nextNudge?;
140
+ /** The final answer the model already wrote; a later plan may omit it instead of sending it again. */
141
+ private draft?;
142
+ /** Commands the model named as its verification that no runner pattern recognizes, by check key. */
143
+ private declared;
129
144
  constructor(options: FactContinuationOptions);
130
145
  get finishing(): boolean;
131
146
  get proposed(): boolean;
147
+ /**
148
+ * Where the model stands when nothing was run for it: it just edited files and has not checked
149
+ * them, or its own check just failed. In both places the cheapest next move is one plan that
150
+ * carries the checks and the answer, and a reminder there is what makes the model take it.
151
+ */
152
+ get nudge(): 'after_write' | 'after_failed_check' | undefined;
153
+ /** The check the runtime ran after the latest edits, when it passed on the current workspace. */
154
+ get followUp(): string | undefined;
155
+ /** The model already wrote its final answer in an earlier plan. */
156
+ get hasDraft(): boolean;
132
157
  private emit;
133
158
  invalidate(reason: string, update?: string): void;
134
159
  /** An actual model call expires unexecuted proposals; it does not discard check failures. */
135
160
  modelResumed(): void;
136
- stage(args: Record<string, unknown>, lastInBatch: boolean): void;
161
+ stage(args: Record<string, unknown>, lastInBatch: boolean, alone?: boolean): void;
162
+ private stagePlan;
137
163
  private coversRequirements;
164
+ /**
165
+ * The current workspace is verified: a check passed on it, and no earlier failure is left
166
+ * unanswered. A failed test, lint or typecheck is answered by a later pass of the same kind on the
167
+ * current workspace; a failed build or other command by any later pass, since a check that ran
168
+ * built what it needed. A command whose result is unknown proves nothing either way: the model
169
+ * saw its output and named the checks that decide.
170
+ */
138
171
  private verified;
139
172
  private ask;
173
+ /** `answered` is false when the service gave no answer at all, as opposed to an unsure one. */
174
+ private consult;
140
175
  private needsChecks;
141
176
  observe(batch: Observation[], signal: AbortSignal): Promise<void>;
142
177
  private verificationSource;