@picassohq/cli 1.0.3 → 1.0.5

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 (64) hide show
  1. package/dist/build-info.json +2 -1
  2. package/dist/index.js +1860 -1316
  3. package/package.json +1 -1
  4. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +4 -7
  5. package/runtime/dsh/picasso-sdk.patch.yml +47 -0
  6. package/runtime/engine-manifest.json +37 -16
  7. package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
  8. package/runtime/packages/picasso-compaction/index.js +875 -0
  9. package/runtime/packages/picasso-compaction/package.json +27 -0
  10. package/runtime/packages/picasso-hooks/cordis.patch.yml +4 -0
  11. package/runtime/packages/picasso-hooks/index.js +302 -0
  12. package/runtime/packages/picasso-hooks/lifecycle-events.js +651 -0
  13. package/runtime/packages/picasso-hooks/package.json +29 -0
  14. package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
  15. package/runtime/packages/picasso-lean-context/glob-walk.js +518 -0
  16. package/runtime/packages/picasso-lean-context/index.js +159 -11
  17. package/runtime/packages/picasso-memory/index.js +66 -24
  18. package/runtime/packages/picasso-model-router/connections.js +213 -10
  19. package/runtime/packages/picasso-model-router/index.js +128 -1
  20. package/runtime/packages/picasso-model-router/package.json +3 -1
  21. package/runtime/packages/picasso-model-router/thinking-default.js +236 -0
  22. package/runtime/packages/picasso-progress-reports/index.js +128 -18
  23. package/runtime/packages/picasso-sdk-server/command-runs.js +37 -0
  24. package/runtime/packages/picasso-sdk-server/ignore-file.js +5 -1
  25. package/runtime/packages/picasso-sdk-server/index.js +11 -3
  26. package/runtime/packages/picasso-sdk-server/package.json +1 -0
  27. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +26 -6
  28. package/runtime/packages/picasso-web-search/backends.js +245 -195
  29. package/runtime/packages/picasso-web-search/config.js +75 -27
  30. package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
  31. package/runtime/packages/picasso-web-search/failure.js +7 -1
  32. package/runtime/packages/picasso-web-search/index.js +7 -5
  33. package/runtime/packages/picasso-web-search/package.json +6 -0
  34. package/runtime/packages/picasso-web-search/requests.js +339 -0
  35. package/runtime/packages/picasso-web-search/router.js +17 -12
  36. package/runtime/packages/picasso-x-reader/settings.js +4 -1
  37. package/runtime/plugins/picasso-auto-approve/index.js +21 -8
  38. package/runtime/plugins/picasso-compaction/index.js +875 -0
  39. package/runtime/plugins/picasso-compaction/package.json +27 -0
  40. package/runtime/plugins/picasso-hooks/index.js +302 -0
  41. package/runtime/plugins/picasso-hooks/lifecycle-events.js +651 -0
  42. package/runtime/plugins/picasso-hooks/package.json +29 -0
  43. package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
  44. package/runtime/plugins/picasso-lean-context/glob-walk.js +518 -0
  45. package/runtime/plugins/picasso-lean-context/index.js +159 -11
  46. package/runtime/plugins/picasso-memory/index.js +66 -24
  47. package/runtime/plugins/picasso-model-router/connections.js +213 -10
  48. package/runtime/plugins/picasso-model-router/index.js +128 -1
  49. package/runtime/plugins/picasso-model-router/package.json +3 -1
  50. package/runtime/plugins/picasso-model-router/thinking-default.js +236 -0
  51. package/runtime/plugins/picasso-progress-reports/index.js +128 -18
  52. package/runtime/plugins/picasso-provider-models/index.js +236 -4
  53. package/runtime/plugins/picasso-trackers/index.js +12 -2
  54. package/runtime/plugins/picasso-web-search/backends.js +245 -195
  55. package/runtime/plugins/picasso-web-search/config.js +75 -27
  56. package/runtime/plugins/picasso-web-search/failure.js +7 -1
  57. package/runtime/plugins/picasso-web-search/index.js +7 -5
  58. package/runtime/plugins/picasso-web-search/package.json +6 -0
  59. package/runtime/plugins/picasso-web-search/requests.js +339 -0
  60. package/runtime/plugins/picasso-web-search/router.js +17 -12
  61. package/runtime/plugins/picasso-x-reader/settings.js +4 -1
  62. package/runtime/relay/main.mjs +3877 -1989
  63. package/runtime/relay/model-listing.mjs +337 -26
  64. package/runtime/relay/versions-routes.mjs +86 -20
@@ -7,7 +7,13 @@
7
7
  // list {provider} finds the route in dsh's configurable-provider directory (`ctx.llm.listConfigurableProviders`),
8
8
  // reads its profile from settings (endpoint, protocol, headers, `apiKeyEnv`), resolves the key
9
9
  // through `ctx.credentials` (the path llm-pi-ai's `resolveApiKey` takes), GETs the listing and
10
- // returns only `{models:[{id, contextWindow?, reasoningEfforts?:[level…]}], authenticated}`.
10
+ // returns only `{models:[{id, contextWindow?, maxOutput?, input?, reasoningEfforts?:[level…]}],
11
+ // authenticated}`.
12
+ // check {provider} tries the route's stored key against a free, authenticated endpoint of the route (its account
13
+ // endpoint where one is known, else its model listing, which counts only when the same listing
14
+ // refuses a request with no key) and returns `{provider, state, reason?, status?, via?,
15
+ // sameKeyAs}`. It never sends a generation request, so it costs nothing; when no free endpoint
16
+ // can tell a good key from a bad one the answer is `not-tested`, never `working`.
11
17
  // The key is sent only to the route's own configured endpoint (never a caller-supplied URL), never returned, logged or
12
18
  // put in an error; a reply that would contain it is refused.
13
19
  //
@@ -124,7 +130,8 @@ export function advertisedLevels(entry, api) {
124
130
 
125
131
  /**
126
132
  * A listing body (`{data:[…]}`, Gemini's native `{models:[{name:"models/<id>",…}]}` or `{models:{id:{…}}}`) as
127
- * `[{id, contextWindow?, reasoningEfforts?}]`, or undefined.
133
+ * `[{id, contextWindow?, maxOutput?, input?, reasoningEfforts?}]`, or undefined. `input` is `['text','image']` when the
134
+ * entry lists an image input modality, `['text']` when it lists others only, absent when it lists none.
128
135
  */
129
136
  export function parseListing(body, api, options = {}) {
130
137
  let listed;
@@ -141,8 +148,17 @@ export function parseListing(body, api, options = {}) {
141
148
  const id = options.stripModelsPrefix === true ? named?.replace(/^models\//u, '') : named;
142
149
  if (!id || !chatCapable({ ...raw, id })) return [];
143
150
  const contextWindow = capacity(raw.context_window, raw.context_length, raw.contextWindow, raw.max_input_tokens, raw.max_context_length, raw.inputTokenLimit, isRecord(raw.limit) ? raw.limit.context : undefined, isRecord(raw.top_provider) ? raw.top_provider.context_length : undefined, propertyValues(raw.properties).context_window);
151
+ const top = isRecord(raw.top_provider) ? raw.top_provider : {};
152
+ const maxOutput = capacity(raw.max_output_tokens, raw.max_completion_tokens, raw.outputTokenLimit, raw.maxOutput, raw.max_tokens, isRecord(raw.limit) ? raw.limit.output : undefined, top.max_completion_tokens);
153
+ const input = listedInput(raw);
144
154
  const reasoningEfforts = advertisedLevels(raw, api);
145
- return [{ id, ...(contextWindow !== undefined ? { contextWindow } : {}), ...(reasoningEfforts ? { reasoningEfforts } : {}) }];
155
+ return [{
156
+ id,
157
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
158
+ ...(maxOutput !== undefined ? { maxOutput } : {}),
159
+ ...(input !== undefined ? { input } : {}),
160
+ ...(reasoningEfforts ? { reasoningEfforts } : {}),
161
+ }];
146
162
  });
147
163
  return mergeModels([], models);
148
164
  }
@@ -157,6 +173,17 @@ function mergeModels(earlier, later) {
157
173
  return [...byId.values()];
158
174
  }
159
175
 
176
+ /** The input modalities a listing entry states (mirrors the relay's `listedInput`). */
177
+ function listedInput(raw) {
178
+ const architecture = isRecord(raw.architecture) ? raw.architecture : {};
179
+ const modalities = isRecord(raw.modalities) ? raw.modalities : {};
180
+ const stated = [raw.input_modalities, architecture.input_modalities, raw.supported_input_types, modalities.input].find(
181
+ (value) => Array.isArray(value) && value.some((item) => typeof item === 'string'),
182
+ );
183
+ if (stated === undefined) return undefined;
184
+ return stated.some((item) => typeof item === 'string' && item.toLowerCase() === 'image') ? ['text', 'image'] : ['text'];
185
+ }
186
+
160
187
  /** Workers AI's `properties: [{property_id, value}]` as numbers by name. */
161
188
  function propertyValues(value) {
162
189
  const out = {};
@@ -335,6 +362,170 @@ export class ProviderModels {
335
362
  return reply;
336
363
  }
337
364
 
365
+ /**
366
+ * `providerModels/check {provider}` → `{provider, state, reason?, status?, via?, sameKeyAs}`: whether the route's
367
+ * stored key is accepted, asked of an endpoint that costs nothing.
368
+ * state `working` (an authenticated request succeeded where one without the key is refused),
369
+ * `key-rejected` (401/403), `out-of-credit` (402, or the provider's own balance/quota answer),
370
+ * `unreachable` (no answer, 429 or 5xx), `not-tested` (nothing free could tell).
371
+ * reason why, as a code: `invalid` | `refused` | `rate-limited` | `provider-error` | `no-answer` | `no-key` |
372
+ * `no-key-reference` | `key-unreadable` | `no-endpoint` | `no-listing` | `open-listing` | `inconclusive`.
373
+ * via `account` | `models`: which endpoint answered.
374
+ * sameKeyAs other providers whose stored key is this very value (`[{provider, name}]`); values are compared here
375
+ * and never returned.
376
+ * No response text is ever returned: a provider's error body can repeat the key.
377
+ */
378
+ async check(provider) {
379
+ const route = requireString(provider, 'provider');
380
+ const entries = this.directory();
381
+ const entry = entries.find((candidate) => candidate.provider === route);
382
+ if (!entry) throw new ProviderModelsError('not-found', `No provider named ${route}.`, { provider: route });
383
+ const profile = this.profile(entry);
384
+ const answer = (state, fields = {}, sameKeyAs = []) => ({ provider: route, state, ...fields, sameKeyAs });
385
+ const refs = keyRefs(profile, entry);
386
+ if (refs.length === 0) return answer('not-tested', { reason: 'no-key-reference' });
387
+ let held;
388
+ try {
389
+ held = await this.heldKey(refs);
390
+ } catch {
391
+ return answer('not-tested', { reason: 'key-unreadable' });
392
+ }
393
+ if (held === undefined) return answer('not-tested', { reason: 'no-key' });
394
+ const { ref, key } = held;
395
+ const sameKeyAs = await this.sameKeyAs(entries, entry, ref, key);
396
+ if (/[^\x21-\x7e]/.test(key)) return answer('key-rejected', { reason: 'invalid' }, sameKeyAs);
397
+ const baseURL = text(profile.baseURL) ?? text(entry.defaultBaseURL) ?? (await this.cloudflareEndpoint(route));
398
+ if (!baseURL || !/^https?:\/\//i.test(baseURL)) return answer('not-tested', { reason: 'no-endpoint' }, sameKeyAs);
399
+ const api = text(profile.api) ?? 'openai-completions';
400
+ const headers = (withKey) => {
401
+ const out = new Headers();
402
+ if (isRecord(profile.headers)) for (const [header, value] of Object.entries(profile.headers)) if (typeof value === 'string') out.set(header, value);
403
+ out.set('accept', 'application/json');
404
+ if (api === 'anthropic-messages') out.set('anthropic-version', ANTHROPIC_VERSION);
405
+ if (!withKey) return out;
406
+ if (api === 'anthropic-messages') out.set('x-api-key', key);
407
+ else if (isGeminiNative(baseURL)) out.set('x-goog-api-key', key);
408
+ else out.set('authorization', `Bearer ${key}`);
409
+ return out;
410
+ };
411
+ const failed = (probe, via) => {
412
+ if (probe.status === undefined) return answer('unreachable', { reason: 'no-answer', via }, sameKeyAs);
413
+ const fields = { status: probe.status, via };
414
+ if (probe.status === 402 || SPENT_WORDING.test(probe.body)) return answer('out-of-credit', fields, sameKeyAs);
415
+ if (probe.status === 401 || probe.status === 403) return answer('key-rejected', { reason: INVALID_KEY_WORDING.test(probe.body) ? 'invalid' : 'refused', ...fields }, sameKeyAs);
416
+ if (probe.status === 429) return answer('unreachable', { reason: 'rate-limited', ...fields }, sameKeyAs);
417
+ if (probe.status >= 500) return answer('unreachable', { reason: 'provider-error', ...fields }, sameKeyAs);
418
+ return undefined;
419
+ };
420
+
421
+ // An account endpoint needs the key by definition and says whether there is credit left.
422
+ const account = accountEndpoint(baseURL);
423
+ if (account !== undefined) {
424
+ const probe = await this.probe(account.url, headers(true));
425
+ if (probe.status !== undefined && probe.status >= 200 && probe.status < 300) {
426
+ const spent = account.spent(parseJson(probe.body));
427
+ return answer(spent ? 'out-of-credit' : 'working', { status: probe.status, via: 'account' }, sameKeyAs);
428
+ }
429
+ const verdict = failed(probe, 'account');
430
+ if (verdict !== undefined) return verdict;
431
+ }
432
+
433
+ const listing = listingUrl(baseURL, api);
434
+ const withKey = await this.probe(listing, headers(true));
435
+ if (withKey.status === undefined || withKey.status < 200 || withKey.status >= 300) {
436
+ return failed(withKey, 'models') ?? answer('not-tested', { reason: 'no-listing', status: withKey.status, via: 'models' }, sameKeyAs);
437
+ }
438
+ if (parseListing(parseJson(withKey.body), api, { stripModelsPrefix: isGeminiHost(baseURL) }) === undefined) {
439
+ return answer('not-tested', { reason: 'no-listing', via: 'models' }, sameKeyAs);
440
+ }
441
+ // A listing anyone can read proves nothing about the key: it counts only when the same request without the key is refused.
442
+ const withoutKey = await this.probe(listing, headers(false));
443
+ if (withoutKey.status !== undefined && withoutKey.status >= 200 && withoutKey.status < 300) return answer('not-tested', { reason: 'open-listing', via: 'models' }, sameKeyAs);
444
+ if (withoutKey.status === 401 || withoutKey.status === 403) return answer('working', { status: withKey.status, via: 'models' }, sameKeyAs);
445
+ return answer('not-tested', { reason: 'inconclusive', via: 'models' }, sameKeyAs);
446
+ }
447
+
448
+ /** One GET, same-origin redirects only → `{status, body}` (body capped, for wording only), or `{}` when nothing answered. */
449
+ async probe(url, headers) {
450
+ let target = url;
451
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
452
+ let response;
453
+ try {
454
+ response = await this.fetch(target, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(LISTING_TIMEOUT_MS) });
455
+ } catch {
456
+ return {};
457
+ }
458
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
459
+ if (location === null) {
460
+ let body = '';
461
+ try {
462
+ body = (await readCapped(response, MAX_LISTING_BYTES)) ?? '';
463
+ } catch {
464
+ body = '';
465
+ }
466
+ return { status: response.status, body };
467
+ }
468
+ await response.body?.cancel().catch(() => undefined);
469
+ let next;
470
+ try {
471
+ next = new URL(location, target);
472
+ } catch {
473
+ return {};
474
+ }
475
+ // The key rides in a header the runtime would forward: only the same origin is followed.
476
+ if (next.origin !== new URL(target).origin) return {};
477
+ target = next.href;
478
+ }
479
+ return {};
480
+ }
481
+
482
+ /** The first of `refs` the credential store holds → `{ref, key}`; undefined when it holds none. Throws when unreadable. */
483
+ async heldKey(refs) {
484
+ const credentials = this.credentials();
485
+ if (!credentials || typeof credentials.resolve !== 'function') throw new ProviderModelsError('unavailable', 'dsh\'s credentials service is not mounted.');
486
+ for (const ref of refs) {
487
+ const hit = await credentials.resolve(ref);
488
+ const value = typeof hit?.value === 'string' ? hit.value.trim() : '';
489
+ if (value) return { ref, key: value };
490
+ }
491
+ return undefined;
492
+ }
493
+
494
+ /**
495
+ * Other routes whose stored key is the very value this route holds (a key pasted into the wrong provider is the
496
+ * usual cause of an "invalid key" answer). Routes of the same service (the two Prism routes) and routes naming the
497
+ * same reference are left out. Values are compared, never returned.
498
+ */
499
+ async sameKeyAs(entries, entry, ref, key) {
500
+ const service = (id) => String(id ?? '').replace(/^kiro-/u, '');
501
+ const credentials = this.credentials();
502
+ const out = [];
503
+ for (const other of entries) {
504
+ if (other.provider === entry.provider || service(other.provider) === service(entry.provider)) continue;
505
+ let otherProfile;
506
+ try {
507
+ otherProfile = this.profile(other);
508
+ } catch {
509
+ continue;
510
+ }
511
+ for (const otherRef of keyRefs(otherProfile, other)) {
512
+ if (otherRef === ref) continue;
513
+ let hit;
514
+ try {
515
+ hit = await credentials.resolve(otherRef);
516
+ } catch {
517
+ continue;
518
+ }
519
+ if (typeof hit?.value === 'string' && hit.value.trim() === key) {
520
+ out.push({ provider: other.provider, name: text(other.displayName) ?? other.provider });
521
+ break;
522
+ }
523
+ }
524
+ if (out.length >= 3) break;
525
+ }
526
+ return out;
527
+ }
528
+
338
529
  /**
339
530
  * A Workers AI route stores its account as the credential `CLOUDFLARE_ACCOUNT_ID` and no endpoint (each catalog model
340
531
  * carries its own account URL), so its listing endpoint is built from that credential. Undefined for any other route,
@@ -390,7 +581,48 @@ export class ProviderModels {
390
581
  }
391
582
  }
392
583
 
393
- const REMOTE_METHODS = ['list'];
584
+ /** The credential references a route's key can be stored under: the profile's `apiKeyEnv`, then the route's own (`nativeAuth.env`). */
585
+ function keyRefs(profile, entry) {
586
+ const native = isRecord(entry.nativeAuth) && Array.isArray(entry.nativeAuth.env) ? entry.nativeAuth.env : [];
587
+ return [...new Set([text(profile.apiKeyEnv), ...native.map(text)].filter((ref) => ref !== undefined))];
588
+ }
589
+
590
+ /** A provider's wording for a spent balance or allowance (mirrors @picasso/model-router's quota and billing wording). */
591
+ const SPENT_WORDING = /\binsufficient[\s_-]+(?:quota|balance|credits?|funds)\b|\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b|\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b|\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b|\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b|\bpayment[\s_-]+required\b/i;
592
+ /** A provider's own wording for a key it does not recognise (mirrors @picasso/model-router's). */
593
+ const INVALID_KEY_WORDING = /\b(?:invalid|incorrect|unrecogni[sz]ed|malformed)[\s_-]*(?:api[\s_-]*)?key\b|\binvalid_api_key\b|\bapi[\s_-]*key[\s_-]*(?:is[\s_-]*)?(?:invalid|not[\s_-]*valid|incorrect)\b/iu;
594
+
595
+ function parseJson(raw) {
596
+ try {
597
+ return JSON.parse(raw);
598
+ } catch {
599
+ return undefined;
600
+ }
601
+ }
602
+
603
+ /**
604
+ * A free endpoint that only answers a valid key and reports the account's credit, for the hosts that document one:
605
+ * DeepSeek's `GET /user/balance` (`is_available`) and OpenRouter's `GET /api/v1/key` (`data.limit_remaining`).
606
+ * `spent(body)` is true when the provider says nothing is left.
607
+ */
608
+ export function accountEndpoint(baseURL) {
609
+ let host;
610
+ try {
611
+ host = new URL(baseURL).hostname;
612
+ } catch {
613
+ return undefined;
614
+ }
615
+ if (host === 'api.deepseek.com') return { url: 'https://api.deepseek.com/user/balance', spent: (body) => isRecord(body) && body.is_available === false };
616
+ if (host === 'openrouter.ai') {
617
+ return {
618
+ url: 'https://openrouter.ai/api/v1/key',
619
+ spent: (body) => isRecord(body) && isRecord(body.data) && typeof body.data.limit_remaining === 'number' && body.data.limit_remaining <= 0,
620
+ };
621
+ }
622
+ return undefined;
623
+ }
624
+
625
+ const REMOTE_METHODS = ['list', 'check'];
394
626
 
395
627
  Object.defineProperty(ProviderModels.prototype, REMOTE_METHOD_DESCRIPTOR, {
396
628
  configurable: true,
@@ -52,7 +52,7 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs';
52
52
  import { mkdir, rename, writeFile } from 'node:fs/promises';
53
53
  import { createRequire } from 'node:module';
54
54
  import { homedir } from 'node:os';
55
- import { delimiter, dirname, join, resolve } from 'node:path';
55
+ import { basename, delimiter, dirname, join, resolve } from 'node:path';
56
56
 
57
57
  export const name = 'picasso-trackers';
58
58
  /** The dsh release this plugin is written and tested against (Picasso pins the engine to it). */
@@ -247,6 +247,14 @@ function authAccount(output) {
247
247
  return match?.[1] ?? match?.[2];
248
248
  }
249
249
 
250
+ /** Test-only hermetic mode (`PICASSO_TEST_HERMETIC=1`): the developer's own `gh`/`glab` sign-ins are never asked. */
251
+ function hermeticTest(env) {
252
+ return String(env?.PICASSO_TEST_HERMETIC ?? process.env.PICASSO_TEST_HERMETIC ?? '').trim() === '1';
253
+ }
254
+
255
+ /** What the real exec answers for a `gh`/`glab` call in hermetic mode: not signed in, without running it. */
256
+ const HERMETIC_SIGNED_OUT = Object.freeze({ code: 1, output: 'not logged in (hermetic test)' });
257
+
250
258
  function requireTool(path, provider, tool) {
251
259
  if (path === undefined) {
252
260
  throw new TrackerError('provider-unconfigured', `${tool} is not installed — install it, then sign in.`, { provider, tool });
@@ -564,7 +572,9 @@ export class TrackerRegistry {
564
572
  this.dataDir = resolve(options.dataDir);
565
573
  this.sidecar = join(this.dataDir, SIDECAR_FILENAME);
566
574
  this.now = options.now ?? Date.now;
567
- this.exec = options.exec ?? ((file, args, opts = {}) => execArgv(file, args, { ...opts, env: opts.env ?? cliEnv(this.env) }));
575
+ this.exec = options.exec ?? ((file, args, opts = {}) => (hermeticTest(this.env) && /^(?:gh|glab)$/u.test(basename(String(file)))
576
+ ? Promise.resolve(HERMETIC_SIGNED_OUT)
577
+ : execArgv(file, args, { ...opts, env: opts.env ?? cliEnv(this.env) })));
568
578
  this.http = options.http ?? httpRequest;
569
579
  this.env = options.env ?? process.env;
570
580
  this.providerConfigSource = typeof options.providers === 'function' ? options.providers : () => options.providers ?? {};