@wiro-ai/wiro-mcp 1.5.7 → 1.6.0

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 (95) hide show
  1. package/README.md +15 -13
  2. package/dist/client.d.ts +4 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +6 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/instructions.js +2 -2
  7. package/dist/instructions.js.map +1 -1
  8. package/dist/playbooks.d.ts.map +1 -1
  9. package/dist/playbooks.js +45 -40
  10. package/dist/playbooks.js.map +1 -1
  11. package/dist/prompts.js +3 -3
  12. package/dist/prompts.js.map +1 -1
  13. package/dist/tools/apply-agent-skills.d.ts.map +1 -1
  14. package/dist/tools/apply-agent-skills.js +102 -639
  15. package/dist/tools/apply-agent-skills.js.map +1 -1
  16. package/dist/tools/connect-agent-oauth.d.ts.map +1 -1
  17. package/dist/tools/connect-agent-oauth.js +260 -111
  18. package/dist/tools/connect-agent-oauth.js.map +1 -1
  19. package/dist/tools/control-agent.d.ts.map +1 -1
  20. package/dist/tools/control-agent.js +20 -9
  21. package/dist/tools/control-agent.js.map +1 -1
  22. package/dist/tools/deploy-agent.d.ts.map +1 -1
  23. package/dist/tools/deploy-agent.js +54 -28
  24. package/dist/tools/deploy-agent.js.map +1 -1
  25. package/dist/tools/get-agent-activity.d.ts.map +1 -1
  26. package/dist/tools/get-agent-activity.js +3 -1
  27. package/dist/tools/get-agent-activity.js.map +1 -1
  28. package/dist/tools/get-agent-conversation.d.ts.map +1 -1
  29. package/dist/tools/get-agent-conversation.js +15 -0
  30. package/dist/tools/get-agent-conversation.js.map +1 -1
  31. package/dist/tools/get-agent-message.d.ts.map +1 -1
  32. package/dist/tools/get-agent-message.js +8 -1
  33. package/dist/tools/get-agent-message.js.map +1 -1
  34. package/dist/tools/get-agent-template.d.ts.map +1 -1
  35. package/dist/tools/get-agent-template.js +11 -9
  36. package/dist/tools/get-agent-template.js.map +1 -1
  37. package/dist/tools/get-my-agent.js +4 -4
  38. package/dist/tools/get-my-agent.js.map +1 -1
  39. package/dist/tools/list-agent-skills.d.ts.map +1 -1
  40. package/dist/tools/list-agent-skills.js +22 -17
  41. package/dist/tools/list-agent-skills.js.map +1 -1
  42. package/dist/tools/list-agent-templates.d.ts.map +1 -1
  43. package/dist/tools/list-agent-templates.js +16 -10
  44. package/dist/tools/list-agent-templates.js.map +1 -1
  45. package/dist/tools/list-my-agents.d.ts.map +1 -1
  46. package/dist/tools/list-my-agents.js +2 -2
  47. package/dist/tools/list-my-agents.js.map +1 -1
  48. package/dist/tools/manage-agent-billing.d.ts.map +1 -1
  49. package/dist/tools/manage-agent-billing.js +476 -187
  50. package/dist/tools/manage-agent-billing.js.map +1 -1
  51. package/dist/tools/send-agent-message.d.ts.map +1 -1
  52. package/dist/tools/send-agent-message.js +49 -2
  53. package/dist/tools/send-agent-message.js.map +1 -1
  54. package/dist/tools/set-agent-credentials.d.ts.map +1 -1
  55. package/dist/tools/set-agent-credentials.js +24 -6
  56. package/dist/tools/set-agent-credentials.js.map +1 -1
  57. package/dist/tools/update-agent.d.ts.map +1 -1
  58. package/dist/tools/update-agent.js +12 -2
  59. package/dist/tools/update-agent.js.map +1 -1
  60. package/dist/utils/agent-catalog.d.ts +18 -14
  61. package/dist/utils/agent-catalog.d.ts.map +1 -1
  62. package/dist/utils/agent-catalog.js +4 -11
  63. package/dist/utils/agent-catalog.js.map +1 -1
  64. package/dist/utils/agent-config.d.ts +98 -45
  65. package/dist/utils/agent-config.d.ts.map +1 -1
  66. package/dist/utils/agent-config.js +246 -147
  67. package/dist/utils/agent-config.js.map +1 -1
  68. package/dist/utils/agent-message.d.ts +46 -0
  69. package/dist/utils/agent-message.d.ts.map +1 -1
  70. package/dist/utils/agent-message.js +22 -3
  71. package/dist/utils/agent-message.js.map +1 -1
  72. package/dist/utils/agent-setup.d.ts +134 -0
  73. package/dist/utils/agent-setup.d.ts.map +1 -0
  74. package/dist/utils/agent-setup.js +608 -0
  75. package/dist/utils/agent-setup.js.map +1 -0
  76. package/dist/utils/agent-targets.d.ts.map +1 -1
  77. package/dist/utils/agent-targets.js +9 -2
  78. package/dist/utils/agent-targets.js.map +1 -1
  79. package/dist/utils/agent-turns.d.ts +63 -0
  80. package/dist/utils/agent-turns.d.ts.map +1 -1
  81. package/dist/utils/agent-turns.js +162 -2
  82. package/dist/utils/agent-turns.js.map +1 -1
  83. package/dist/utils/api.d.ts +1 -1
  84. package/dist/utils/api.d.ts.map +1 -1
  85. package/dist/utils/api.js +3 -3
  86. package/dist/utils/api.js.map +1 -1
  87. package/dist/utils/quoted-text.d.ts +10 -0
  88. package/dist/utils/quoted-text.d.ts.map +1 -1
  89. package/dist/utils/quoted-text.js +18 -0
  90. package/dist/utils/quoted-text.js.map +1 -1
  91. package/dist/utils/user-agent.d.ts +89 -21
  92. package/dist/utils/user-agent.d.ts.map +1 -1
  93. package/dist/utils/user-agent.js +211 -49
  94. package/dist/utils/user-agent.js.map +1 -1
  95. package/package.json +1 -1
@@ -1,14 +1,13 @@
1
1
  import crypto from 'node:crypto';
2
+ import { DEFAULT_BASE_URL } from '../client.js';
2
3
  import { AGENT_NOT_FOUND_TEXT, ApiResultError, asString, hasErrorCode, isAgentNotFound, isPlainObject, requireApiSuccess, toNumber, truncate, unixToIso, } from './api.js';
3
4
  import { oneLine, quotedSpan } from './quoted-text.js';
4
- import { credentialKeysSetupWaitsFor, isWalletNotRead, nameList, planEndsWithPeriod, skillLabel, STARTER_TASK_KEY, toSkillGroups, WALLET_NOT_READ_NOTE, WIRO_PROJECT_CREDENTIAL, wordsFromKey, } from './user-agent.js';
5
+ import { credentialKeysSetupWaitsFor, nameList, skillLabel, STARTER_TASK_KEY, toSkillGroups, WIRO_PROJECT_CREDENTIAL, wordsFromKey, } from './user-agent.js';
5
6
  // Helpers for configuring a deployed agent: its registry skills, credentials,
6
7
  // sign-in connections and custom skills. The pure functions mirror the server
7
8
  // rules closely so a bad request is caught before anything is written.
8
9
  export const DEFAULT_CRON_INTERVAL = '0 10 * * 1';
9
10
  export const OAUTH_LINK_TTL_SECONDS = 900;
10
- const DASHBOARD_AGENT_URL = 'https://wiro.ai/panel/agents/';
11
- const OAUTH_CALLBACK_BASE = 'https://api.wiro.ai/v1';
12
11
  const REGISTRY_TTL_MS = 5 * 60_000;
13
12
  function stringList(value) {
14
13
  return Array.isArray(value)
@@ -38,10 +37,42 @@ export function agentStatusLabel(status) {
38
37
  export function isAgentRunning(status) {
39
38
  return status === 3 || status === 4;
40
39
  }
40
+ /** The API base URL a client sends its requests to, without a trailing slash; the public API for one that does not say. */
41
+ export function apiBaseUrlOf(client) {
42
+ const base = client.apiBaseUrl;
43
+ return typeof base === 'string' && base.trim() !== '' ? base.trim().replace(/\/+$/, '') : DEFAULT_BASE_URL;
44
+ }
45
+ /**
46
+ * The base URL when users and sign-in providers can reach it: https on a domain name. A server that calls the API
47
+ * on its own machine or network (plain http, an IP address or a local name) sends people to the public addresses.
48
+ */
49
+ function reachableApiUrl(apiBase) {
50
+ let url;
51
+ try {
52
+ url = new URL(apiBase.trim());
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ const host = url.hostname.replace(/\.$/, '');
58
+ const local = host.startsWith('[') || /^[\d.]+$/.test(host) || !host.includes('.') || host.endsWith('.localhost');
59
+ return url.protocol === 'https:' && !url.username && !url.password && !local ? url : null;
60
+ }
61
+ /**
62
+ * Where the sign-in callbacks and the dashboard's agent pages are for an API base URL: the callbacks under the base
63
+ * URL itself, the dashboard on the API's host without a leading "api." label. The public API gives the public ones.
64
+ */
65
+ function wiroAddresses(apiBase) {
66
+ const url = reachableApiUrl(apiBase) ?? new URL(DEFAULT_BASE_URL);
67
+ return {
68
+ callbackBase: `${url.origin}${url.pathname.replace(/\/+$/, '')}`,
69
+ dashboardAgents: `https://${url.host.replace(/^api\./, '')}/panel/agents/`,
70
+ };
71
+ }
41
72
  /** The agent's page in the Wiro dashboard, in the form the dashboard itself uses as an OAuth return address. */
42
- export function dashboardAgentUrl(agentGuid) {
73
+ export function dashboardAgentUrl(agentGuid, apiBase = DEFAULT_BASE_URL) {
43
74
  const guid = encodeURIComponent(agentGuid);
44
- return `${DASHBOARD_AGENT_URL}${guid}?id=${guid}`;
75
+ return `${wiroAddresses(apiBase).dashboardAgents}${guid}?id=${guid}`;
45
76
  }
46
77
  export function restartNote(status, what = 'change') {
47
78
  switch (status) {
@@ -65,7 +96,11 @@ export function restartNote(status, what = 'change') {
65
96
  export function keyList(keys) {
66
97
  return keys.length > 1 ? `${keys.slice(0, -1).join(', ')} and ${keys[keys.length - 1]}` : keys.join('');
67
98
  }
68
- function afterWriteNote(status) {
99
+ // Wiro restarts nothing for fields of a sign-in that is not connected yet; the connection restarts the agent once.
100
+ const AWAITS_CONNECTION_NOTE = 'The agent kept running: fields saved for a sign-in integration that is not connected yet, '
101
+ + 'such as its app keys or token, do not restart it. It needs no restart now: it restarts once, when '
102
+ + 'connect_agent_oauth completes the connection.';
103
+ function afterWriteNote(status, awaitsConnection) {
69
104
  switch (status) {
70
105
  case 1:
71
106
  return 'The agent restarts to load the new values, which takes about a minute.';
@@ -73,6 +108,8 @@ function afterWriteNote(status) {
73
108
  case 3:
74
109
  return 'The agent is starting and loads the new values.';
75
110
  case 4:
111
+ if (awaitsConnection)
112
+ return AWAITS_CONNECTION_NOTE;
76
113
  // A save that changes a value sets a running agent stopping before Wiro answers.
77
114
  return 'The agent kept running: a save that matches what is stored does not restart it. If it should load new values now, control_agent with action restart does it.';
78
115
  case 6:
@@ -102,13 +139,17 @@ export function setupStillMissingNote(missing) {
102
139
  : steps.map((step, index) => `${index === 0 ? step.verb : step.verb.toLowerCase()} ${keyList(step.names)} with ${step.tool}`).join(', ');
103
140
  return `Setup is not finished: still missing ${keyList(titles(missing))}. ${how}, then check with get_my_agent.`;
104
141
  }
105
- /** When the agent loads the values, and the credentials its setup still waits for, at any status. */
106
- export function afterWriteNotes(status, missing) {
142
+ /**
143
+ * When the agent loads the values, and the credentials its setup still waits for, at any status.
144
+ * awaitsConnection: every credential written is a sign-in that still reads not connected.
145
+ */
146
+ export function afterWriteNotes(status, missing, options = {}) {
147
+ const note = afterWriteNote(status, options.awaitsConnection === true);
107
148
  const setup = setupStillMissingNote(missing);
108
149
  if (!setup)
109
- return [afterWriteNote(status)];
150
+ return [note];
110
151
  // At status 6 the general note says the same without the names.
111
- return status === 6 ? [setup] : [afterWriteNote(status), setup];
152
+ return status === 6 ? [setup] : [note, setup];
112
153
  }
113
154
  export async function readUserAgent(client, agentGuid, signal) {
114
155
  const body = requireApiSuccess(await client.post('/UserAgent/Detail', { guid: agentGuid }, signal), 'Could not read the agent.');
@@ -158,7 +199,6 @@ export function parseSkillRegistry(body) {
158
199
  const name = asString(raw.name);
159
200
  if (!name)
160
201
  continue;
161
- const pricing = isPlainObject(raw.pricing) ? raw.pricing : {};
162
202
  const primary = asString(raw.credential_key);
163
203
  skills.set(name, {
164
204
  name,
@@ -169,7 +209,6 @@ export function parseSkillRegistry(body) {
169
209
  ...(asString(raw.replacement) ? { replacement: asString(raw.replacement) } : {}),
170
210
  requiresCredentials: raw.requires_credentials === true,
171
211
  credentialKeys: [...(primary ? [primary] : []), ...stringList(raw.additional_credential_keys)],
172
- monthlyPriceUsd: toNumber(pricing.monthly_price_weight_usd ?? raw.monthly_price_weight_usd),
173
212
  });
174
213
  }
175
214
  const channels = new Map();
@@ -408,37 +447,24 @@ export async function unusedCredentialNote(client, row, credential, title, signa
408
447
  return null;
409
448
  }
410
449
  }
411
- const IDEMPOTENCY_KEY_RE = /^mcp-[0-9a-f]{16}-([0-9a-f]{10})-([0-9a-f]{8})$/;
450
+ // A key minted by this package: mcp-<random>-<change digest>. Keys from earlier versions also carry a price fingerprint at the end.
451
+ const IDEMPOTENCY_KEY_RE = /^mcp-[0-9a-f]{16}-([0-9a-f]{10})(?:-[0-9a-f]{8})?$/;
412
452
  /** Fingerprint of one logical skill change, independent of the agent's current state. */
413
- export function skillChangeDigest(agentGuid, requested, tier) {
453
+ export function skillChangeDigest(agentGuid, requested) {
414
454
  const entries = Object.keys(requested).sort().map(name => `${name}=${requested[name] ? 1 : 0}`);
415
455
  return crypto.createHash('sha256')
416
- .update([agentGuid, tier ?? '', ...entries].join('\n'))
456
+ .update([agentGuid, '', ...entries].join('\n'))
417
457
  .digest('hex')
418
458
  .slice(0, 10);
419
459
  }
420
- function cents(value) {
421
- return value === null || !Number.isFinite(value) ? 'none' : String(Math.round(value * 100));
422
- }
423
- /**
424
- * Fingerprint of what a quoted charge rests on: the monthly price before and after
425
- * a change and, for a plan paid from the wallet, the period it is charged in. A
426
- * renewal keeps the prices and starts a new period, which changes the charge.
427
- */
428
- export function skillPriceTag(currentUsd, newUsd, periodEndUnix = null) {
429
- const prices = `${cents(currentUsd)}:${cents(newUsd)}`;
430
- return crypto.createHash('sha256')
431
- .update(periodEndUnix === null ? prices : `${prices}:${periodEndUnix}`)
432
- .digest('hex')
433
- .slice(0, 8);
434
- }
435
- export function newSkillChangeKey(digest, priceTag) {
436
- return `mcp-${crypto.randomBytes(8).toString('hex')}-${digest}-${priceTag}`;
460
+ /** A new key for one skill change. Repeating the change with it never applies it twice. */
461
+ export function newSkillChangeKey(digest) {
462
+ return `mcp-${crypto.randomBytes(8).toString('hex')}-${digest}`;
437
463
  }
438
- /** The change and price fingerprints of a key minted by this package, or null for any other key. */
464
+ /** The change fingerprint of a key minted by this package, or null for any other key. */
439
465
  export function parseSkillChangeKey(key) {
440
466
  const match = IDEMPOTENCY_KEY_RE.exec(key.trim());
441
- return match ? { digest: match[1], priceTag: match[2] } : null;
467
+ return match ? { digest: match[1] } : null;
442
468
  }
443
469
  /**
444
470
  * Keys minted by this package carry the fingerprint of their change. Wiro
@@ -449,22 +475,6 @@ export function idempotencyKeyMismatch(key, digest) {
449
475
  const parsed = parseSkillChangeKey(key);
450
476
  return parsed !== null && parsed.digest !== digest;
451
477
  }
452
- export function planBilling(row) {
453
- const wallet = asString(row.teamguid) ? 'team' : 'personal';
454
- const subscription = isPlainObject(row.subscription) ? row.subscription : null;
455
- if (!subscription) {
456
- return { plan: 'none', status: null, periodEnd: null, wallet, cancelAtPeriodEnd: false, switchingToWallet: false };
457
- }
458
- const plan = asString(subscription.provider) === 'prepaid' ? 'prepaid' : 'card';
459
- return {
460
- plan,
461
- status: asString(subscription.status) ?? null,
462
- periodEnd: toNumber(subscription.currentperiodend),
463
- wallet,
464
- cancelAtPeriodEnd: planEndsWithPeriod(subscription, row.stripecancelatperiodend),
465
- switchingToWallet: plan === 'card' && subscription.nextprovider === 'prepaid',
466
- };
467
- }
468
478
  const DAY_SECONDS = 86400;
469
479
  /** The plan change of a pricing answer, or null when the agent has no active plan or Wiro sent none. */
470
480
  export function readPlanChange(value) {
@@ -493,25 +503,11 @@ export function daysLeftText(secondsLeft) {
493
503
  const days = Math.max(1, Math.round(secondsLeft / DAY_SECONDS));
494
504
  return `${days} ${days === 1 ? 'day' : 'days'}`;
495
505
  }
496
- const SKILL_PAYMENT_FAILED = 'The payment for this change did not go through, so the change was undone and nothing was charged.';
497
- const DEPOSIT_PAGE = 'https://wiro.ai/panel/wallet/deposit/credit-card (for a team project, select that team in the dashboard first)';
498
- /**
499
- * What to do after a skill change whose payment failed, for the agent's plan
500
- * when it is known. A wallet that does not cover the charge is refused before
501
- * any payment (code 103), so a wallet plan needs no funds added here.
502
- */
503
- function skillPaymentGuidance(plan) {
504
- if (plan === 'prepaid')
505
- return `${SKILL_PAYMENT_FAILED} The balance is not the cause, so no funds need to be added. Ask for a new quote and confirm it once the user approves.`;
506
- if (plan === 'card')
507
- return `${SKILL_PAYMENT_FAILED} Update the card in the Wiro dashboard, then ask for a new quote.`;
508
- return `${SKILL_PAYMENT_FAILED} For a plan paid by card, update the card in the Wiro dashboard first. Then ask for a new quote.`;
509
- }
510
506
  /**
511
- * Turns a refused SkillsApply into an explanation and the step that fixes it.
512
- * With the agent's plan, a payment failure names only the fix for that plan.
507
+ * Turns a refused SkillsApply into an explanation and the step that fixes it. A skill change moves no money,
508
+ * so none of these is about the wallet.
513
509
  */
514
- export function describeSkillsApplyError(error, plan, titles) {
510
+ export function describeSkillsApplyError(error, titles) {
515
511
  const message = error instanceof Error ? error.message : String(error);
516
512
  const body = error instanceof ApiResultError ? error.body : {};
517
513
  const codes = error instanceof ApiResultError ? error.codes.map(code => toNumber(code)) : [];
@@ -538,58 +534,28 @@ export function describeSkillsApplyError(error, plan, titles) {
538
534
  guidance: `These skills cannot be on together: ${conflicts.map(pair => `${skillLabel(pair.a, titles)} and ${skillLabel(pair.b, titles)}`).join('; ')}. Keep only one of each pair.`,
539
535
  };
540
536
  }
541
- case 103: {
542
- const requiredUsd = toNumber(body.requiredUsd);
543
- const availableUsd = toNumber(body.availableUsd);
544
- return {
545
- ...base,
546
- requiredUsd,
547
- availableUsd,
548
- guidance: `The wallet does not cover the charge for the rest of this period${requiredUsd !== null ? `: it needs ${formatUsd(requiredUsd)}` : ''}${availableUsd !== null ? ` and has ${formatUsd(availableUsd)}` : ''}. Nothing was changed. Funds are added at ${DEPOSIT_PAGE}; once the user has added them and says yes, confirm again.`,
549
- };
550
- }
551
537
  case 104:
552
- // Two refusals share the code: another change to the agent's plan, or another payment from its wallet.
553
- // Skill changes, an upgrade to Pro and a wallet plan's renewal take turns on an agent.
538
+ // Changes to an agent's skills or plan take turns, such as a plan change or a renewal.
554
539
  return {
555
540
  ...base,
556
541
  retrySameKey: true,
557
- guidance: /wallet/i.test(message)
558
- ? 'Another payment from the same wallet was going through, so this change was not made and nothing was charged. It is not a low balance, and no funds need to be added. Offer to try again in a minute: repeat the call with the same idempotency_key.'
559
- : 'Another change to this agent\'s skills or plan, such as an upgrade or a renewal, is still going through, and one runs at a time. Nothing was changed or charged by this call. Wait a few seconds, then repeat the call with the same idempotency_key. If it keeps saying so, it clears within 15 minutes.',
560
- };
561
- case 105:
562
- return {
563
- ...base,
564
- guidance: 'A Pro plan cannot be moved back to Starter here. Cancel the plan with manage_agent_billing and subscribe again at Starter once it ends.',
565
- };
566
- case 106:
567
- return {
568
- ...base,
569
- guidance: 'The agent\'s subscription is not active, so its skills cannot change. Renew it with manage_agent_billing first.',
542
+ guidance: 'Another change to this agent\'s skills or plan, such as a plan change or a renewal, is still going through, and one runs at a time. Nothing was changed by this call. Wait a few seconds, then repeat the call with the same idempotency_key. If it keeps saying so, it clears within 15 minutes.',
570
543
  };
571
544
  case 107:
572
545
  return {
573
546
  ...base,
574
- guidance: 'This idempotency_key cannot be used for this call, and nothing was changed or charged by it. Get a new quote: repeat the call without idempotency_key, show the quote to the user, and confirm with the key it gives.',
547
+ guidance: 'This idempotency_key cannot be used for this call, and nothing was changed by it. Repeat the call without idempotency_key: it then gets a new key.',
575
548
  };
576
549
  case 108:
577
550
  return {
578
551
  ...base,
579
552
  retrySameKey: true,
580
- guidance: 'Wiro could not read or save what this change needs just now, and the wallet balance can be part of that. It is not a low balance, so no funds need to be added. Nothing was changed or charged. Try again: repeat the call with the same idempotency_key.',
581
- };
582
- case 109:
583
- // Wiro's sentence covers cards and wallets alike. The guidance names the fix for this plan.
584
- return {
585
- ...base,
586
- message: 'Payment processing failed for this skill change.',
587
- guidance: skillPaymentGuidance(plan),
553
+ guidance: 'Wiro could not read or save what this change needs just now. Nothing was changed. Try again: repeat the call with the same idempotency_key.',
588
554
  };
589
555
  case 110:
590
556
  return {
591
557
  ...base,
592
- guidance: 'Do not repeat this change. Check the agent\'s skills and monthly price with get_my_agent and the wallet with get_account (recent_transactions) before changing anything, and contact Wiro support if they are not what you expect.',
558
+ guidance: 'Do not repeat this change. Check the agent\'s skills with get_my_agent before changing anything, and contact Wiro support if they are not what you expect.',
593
559
  };
594
560
  case 95:
595
561
  case 96:
@@ -601,20 +567,24 @@ export function describeSkillsApplyError(error, plan, titles) {
601
567
  default:
602
568
  break;
603
569
  }
604
- if (/pricing snapshot|not found in registry/i.test(message)) {
570
+ if (/pricing snapshot|not found in registry|not in the skill registry/i.test(message)) {
605
571
  return {
606
572
  ...base,
607
- guidance: 'The new price could not be computed, so nothing was changed. Check the skill names with list_agent_skills.',
573
+ guidance: 'Wiro could not read one of the skills, so nothing was changed. Check the skill names with list_agent_skills.',
608
574
  };
609
575
  }
610
576
  if (/^unknown skill: /i.test(message)) {
611
577
  return {
612
578
  ...base,
613
- guidance: 'Nothing was changed or charged. Use names from list_agent_skills.',
579
+ guidance: 'Nothing was changed. Use names from list_agent_skills.',
580
+ };
581
+ }
582
+ if (/change the plan with upgradetier/i.test(message)) {
583
+ return {
584
+ ...base,
585
+ guidance: 'A skill change does not change the plan. manage_agent_billing with action change_plan does.',
614
586
  };
615
587
  }
616
- if (isWalletNotRead(error))
617
- return { ...base, guidance: WALLET_NOT_READ_NOTE };
618
588
  return { ...base, guidance: workspaceHint(message) ?? '' };
619
589
  }
620
590
  /**
@@ -623,7 +593,7 @@ export function describeSkillsApplyError(error, plan, titles) {
623
593
  * them apart.
624
594
  */
625
595
  export async function connectionRefusalText(client, agentGuid, message, done, signal) {
626
- const rule = `can only be ${done} with a project created by the person who deployed the agent: `
596
+ const rule = `can only be ${done} with a project of the person who deployed the agent or of a team admin of its team: `
627
597
  + 'connect this server with such a project, by its API key or a browser sign-in.';
628
598
  try {
629
599
  await readUserAgent(client, agentGuid, signal);
@@ -732,6 +702,7 @@ function parsePicker(raw) {
732
702
  }
733
703
  }
734
704
  const nextRaw = isPlainObject(raw.next) && raw.next.enabled !== false ? raw.next : null;
705
+ const maxParents = nextRaw ? toNumber(nextRaw.max_parents) : null;
735
706
  const next = nextRaw && asString(nextRaw.key) && asString(nextRaw.item_value_field)
736
707
  ? {
737
708
  key: asString(nextRaw.key),
@@ -742,6 +713,7 @@ function parsePicker(raw) {
742
713
  itemValueField: asString(nextRaw.item_value_field),
743
714
  itemLabelField: asString(nextRaw.item_label_field) ?? asString(nextRaw.item_value_field),
744
715
  persistField: asString(nextRaw.persist_field) ?? '',
716
+ ...(maxParents !== null && Number.isInteger(maxParents) && maxParents > 0 ? { maxParents } : {}),
745
717
  }
746
718
  : null;
747
719
  return {
@@ -915,6 +887,22 @@ function isEmptyValue(value) {
915
887
  return value.length === 0;
916
888
  return false;
917
889
  }
890
+ // An agent's detail shows a saved secret, such as a key or a token, as exactly eight dots (U+2022), and an unsaved
891
+ // one as "": the dots read as set, and they are never the value. A value that is exactly those dots, spaces around
892
+ // it aside, was copied from there, so it is never sent back. Any other text is a value like any other.
893
+ const SECRET_MASK = '\u2022'.repeat(8);
894
+ /** Whether a value is that mask, or holds it as a list item or an entry's field. */
895
+ export function holdsSecretMask(value) {
896
+ if (typeof value === 'string')
897
+ return value.trim() === SECRET_MASK;
898
+ if (Array.isArray(value))
899
+ return value.some(holdsSecretMask);
900
+ if (isPlainObject(value))
901
+ return Object.values(value).some(holdsSecretMask);
902
+ return false;
903
+ }
904
+ /** What a value that holds the mask holds, for the sentence that refuses it. */
905
+ export const SECRET_MASK_TEXT = 'the dots Wiro shows in place of a saved secret, not the secret itself';
918
906
  // Short values (select options, flags) are not secrets and would garble messages.
919
907
  function collectStrings(value, into) {
920
908
  if (typeof value === 'string') {
@@ -1107,6 +1095,10 @@ export function prepareCredentialWrite(inputs, metas) {
1107
1095
  prepared.errors.push(`${meta.title}: "${fieldName}" is filled by the connection itself. Use connect_agent_oauth.`);
1108
1096
  continue;
1109
1097
  }
1098
+ if (holdsSecretMask(input.value)) {
1099
+ prepared.errors.push(`${meta.title}: "${fieldName}" holds ${SECRET_MASK_TEXT}. Leave it out to keep the saved value, or send the new value.`);
1100
+ continue;
1101
+ }
1110
1102
  if (fieldName === 'authmethod') {
1111
1103
  const usable = usableConnectionModes(meta);
1112
1104
  if (input.parent_field || usable.length === 0) {
@@ -1383,10 +1375,11 @@ export function channelStatuses(row) {
1383
1375
  // ---------------------------------------------------------------------------
1384
1376
  /**
1385
1377
  * Wiro sends the browser to this address after sign-in with the connected
1386
- * account names appended, so only the agent's own dashboard page or an
1387
- * address on the user's own machine is accepted.
1378
+ * account names appended, so only the agent's own dashboard page (for the API
1379
+ * this server talks to, as dashboardAgentUrl gives it) or an address on the
1380
+ * user's own machine is accepted.
1388
1381
  */
1389
- export function isAllowedRedirectUrl(url, agentGuid) {
1382
+ export function isAllowedRedirectUrl(url, agentGuid, apiBase = DEFAULT_BASE_URL) {
1390
1383
  let parsed;
1391
1384
  try {
1392
1385
  parsed = new URL(url.trim());
@@ -1398,16 +1391,40 @@ export function isAllowedRedirectUrl(url, agentGuid) {
1398
1391
  return false;
1399
1392
  if (parsed.protocol === 'http:')
1400
1393
  return parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
1401
- const dashboard = new URL(dashboardAgentUrl(agentGuid));
1394
+ const dashboard = new URL(dashboardAgentUrl(agentGuid, apiBase));
1402
1395
  return parsed.protocol === 'https:'
1403
1396
  && parsed.host === dashboard.host
1404
1397
  && parsed.pathname.replace(/\/+$/, '') === dashboard.pathname
1405
1398
  && (parsed.search === '' || parsed.search === dashboard.search)
1406
1399
  && parsed.hash === '';
1407
1400
  }
1408
- /** The redirect URI a customer registers in their own OAuth app. */
1409
- export function ownAppRedirectUri(meta) {
1410
- return meta.oauth?.callbackPath ? `${OAUTH_CALLBACK_BASE}${meta.oauth.callbackPath}` : undefined;
1401
+ /**
1402
+ * The redirect URI a customer registers in their own OAuth app. Wiro's status gives the one for the host this
1403
+ * server talks to; without it, or when it is not an address for this service's callback, the callback under the
1404
+ * API base URL is used (wiroAddresses).
1405
+ */
1406
+ export function ownAppRedirectUri(meta, fromStatus, apiBase = DEFAULT_BASE_URL) {
1407
+ const callbackPath = meta.oauth?.callbackPath;
1408
+ if (!callbackPath)
1409
+ return undefined;
1410
+ return statusRedirectUri(meta, fromStatus) ?? `${wiroAddresses(apiBase).callbackBase}${callbackPath}`;
1411
+ }
1412
+ /** The redirect URI Wiro's status gave, when it is an address for this service's callback; else undefined. */
1413
+ export function statusRedirectUri(meta, fromStatus) {
1414
+ const callbackPath = meta.oauth?.callbackPath;
1415
+ return callbackPath && fromStatus && isCallbackAddress(fromStatus, callbackPath) ? fromStatus : undefined;
1416
+ }
1417
+ function isCallbackAddress(value, callbackPath) {
1418
+ let parsed;
1419
+ try {
1420
+ parsed = new URL(value);
1421
+ }
1422
+ catch {
1423
+ return false;
1424
+ }
1425
+ return (parsed.protocol === 'https:' || parsed.protocol === 'http:')
1426
+ && !parsed.username && !parsed.password && !parsed.search && !parsed.hash
1427
+ && parsed.pathname.endsWith(callbackPath);
1411
1428
  }
1412
1429
  /** Goes with a list of missing fields that holds app keys, which may be saved already. */
1413
1430
  export function writeOnlyNote(mode) {
@@ -1420,6 +1437,23 @@ export function writeOnlyModesNote(requirements) {
1420
1437
  .map(requirement => requirement.mode);
1421
1438
  return modes.length > 0 ? writeOnlyNote(modes.join(' or ')) : null;
1422
1439
  }
1440
+ /**
1441
+ * What Wiro's status says is saved for the modes that need something saved before they connect: that the keys of
1442
+ * the user's own app are saved (Wiro's no says nothing about them; see parseOAuthStatus), and whether the token a
1443
+ * check reads is. Empty when the status does not say, as from an older Wiro API.
1444
+ */
1445
+ export function savedForModesText(meta, context) {
1446
+ const modes = usableConnectionModes(meta);
1447
+ const sentences = [];
1448
+ if (modes.includes('own') && context.appKeysSaved === true) {
1449
+ sentences.push(`The keys of the user's own ${meta.title} app (mode own) are saved.`);
1450
+ }
1451
+ const probe = meta.oauth?.directProbe;
1452
+ if (probe && modes.includes(probe.mode) && context.tokenSaved !== undefined) {
1453
+ sentences.push(`The ${probe.label ?? 'token'} (mode ${probe.mode}) ${context.tokenSaved ? 'is saved' : 'is not saved yet'}.`);
1454
+ }
1455
+ return sentences.join(' ');
1456
+ }
1423
1457
  function fieldsForMode(meta, mode) {
1424
1458
  if (mode === 'wiro')
1425
1459
  return [];
@@ -1440,17 +1474,37 @@ function fieldsForMode(meta, mode) {
1440
1474
  .map(key => byKey.get(key) ?? { ...parseCredentialField({ key }), required: true })
1441
1475
  .filter(field => isWritableField(field));
1442
1476
  }
1443
- /** What each connection mode needs, with which of those fields are already saved. */
1444
- export function connectionModeRequirements(meta, group) {
1477
+ /** The context of a status read, which may have failed (null): then only the API base URL. */
1478
+ export function modeContext(status, apiBase) {
1479
+ return {
1480
+ ...(status?.redirectUri ? { redirectUri: status.redirectUri } : {}),
1481
+ ...(status?.appKeysSaved === true ? { appKeysSaved: true } : {}),
1482
+ ...(status?.tokenSaved !== undefined ? { tokenSaved: status.tokenSaved } : {}),
1483
+ apiBase,
1484
+ };
1485
+ }
1486
+ /**
1487
+ * What each connection mode needs, with which of those fields are already saved. App keys read as empty in the
1488
+ * agent's detail even once saved, so where Wiro's status says the own app's keys are saved, or whether the token
1489
+ * check's fields are, that decides for them.
1490
+ */
1491
+ export function connectionModeRequirements(meta, group, context = {}) {
1445
1492
  const modes = meta.connectionModes.length > 0 ? meta.connectionModes : ['wiro'];
1446
1493
  return modes.map(mode => {
1494
+ // Mode own only ever has Wiro's yes (see parseOAuthStatus): without it, the app keys keep the hedge below, so a
1495
+ // connect still lets the sign-in route decide whether they are saved.
1496
+ const saved = mode === 'own'
1497
+ ? context.appKeysSaved
1498
+ : mode === meta.oauth?.directProbe?.mode ? context.tokenSaved : undefined;
1447
1499
  const fields = fieldsForMode(meta, mode).map(field => {
1448
- const isSet = group !== null && isFilledValue(group[field.key]);
1500
+ // Wiro's yes on mode own covers its required fields; its word on the token check, every field the check reads.
1501
+ const statusSays = saved !== undefined && (mode !== 'own' || field.required);
1502
+ const isSet = (group !== null && isFilledValue(group[field.key])) || (statusSays && saved === true);
1449
1503
  return {
1450
1504
  field: field.key,
1451
1505
  label: field.label,
1452
1506
  isSet,
1453
- ...(field.oauthManaged && !isSet ? { writeOnly: true } : {}),
1507
+ ...(field.oauthManaged && !isSet && !statusSays ? { writeOnly: true } : {}),
1454
1508
  };
1455
1509
  });
1456
1510
  if (mode === 'wiro') {
@@ -1483,7 +1537,7 @@ export function connectionModeRequirements(meta, group) {
1483
1537
  };
1484
1538
  }
1485
1539
  if (mode === 'own') {
1486
- const redirect = ownAppRedirectUri(meta);
1540
+ const redirect = ownAppRedirectUri(meta, context.redirectUri, context.apiBase);
1487
1541
  const requirements = meta.oauth?.connectRequirements ?? [];
1488
1542
  return {
1489
1543
  mode,
@@ -1538,40 +1592,25 @@ export function toAccountRefs(list, picker) {
1538
1592
  return { id, name };
1539
1593
  }).filter(account => account.id);
1540
1594
  }
1541
- /** Maps {id, name} selections onto the fields the picker saves. */
1542
- export function buildPickerAccounts(picker, accounts) {
1595
+ /**
1596
+ * The ids of the chosen accounts. Wiro saves only accounts from the list its sign-in or token check gave, under the
1597
+ * names in that list, so an id is all it takes.
1598
+ */
1599
+ export function pickedAccountIds(picker, accounts) {
1543
1600
  if (accounts.length === 0)
1544
1601
  return { error: 'Pass at least one account.' };
1545
1602
  if (!picker.multiSelect && accounts.length !== 1)
1546
1603
  return { error: 'This connection uses exactly one account.' };
1547
- const seen = new Set();
1548
- const out = [];
1604
+ const ids = [];
1549
1605
  for (const account of accounts) {
1550
- const id = asString(account.id) ?? asString(account[picker.valueField]) ?? '';
1551
- const name = asString(account.name)
1552
- ?? (picker.labelField ? asString(account[picker.labelField]) : undefined)
1553
- ?? asString(account.title)
1554
- ?? asString(account.displayName)
1555
- ?? '';
1556
- if (!id.trim())
1606
+ const id = (asString(account.id) ?? asString(account[picker.valueField]) ?? '').trim();
1607
+ if (!id)
1557
1608
  return { error: 'Every account needs an id.' };
1558
- if (seen.has(id.trim()))
1609
+ if (ids.includes(id))
1559
1610
  return { error: `Account ${id} is listed twice.` };
1560
- seen.add(id.trim());
1561
- const mapped = {};
1562
- for (const field of picker.fieldsToSave) {
1563
- if (field === picker.valueField)
1564
- mapped[field] = id.trim();
1565
- else if (field === picker.labelField)
1566
- mapped[field] = name;
1567
- else if (asString(account[field]) !== undefined)
1568
- mapped[field] = asString(account[field]);
1569
- else
1570
- mapped[field] = picker.urlItemFields[field] === 'id' ? id.trim() : name;
1571
- }
1572
- out.push(mapped);
1611
+ ids.push(id);
1573
1612
  }
1574
- return { accounts: out };
1613
+ return { ids };
1575
1614
  }
1576
1615
  export function parseDiscoveredGroups(next, groups) {
1577
1616
  if (!Array.isArray(groups))
@@ -1612,7 +1651,7 @@ export function buildChainedSelections(next, groups, selections) {
1612
1651
  if (!group) {
1613
1652
  return {
1614
1653
  skippedParents: [],
1615
- error: `Account "${selection.parent}" is not among the connected accounts (${groups.map(candidate => candidate.parent.id).join(', ') || 'none'}).`,
1654
+ error: `Account "${selection.parent}" is not among the accounts this step lists (${groups.map(candidate => candidate.parent.id).join(', ') || 'none'}).`,
1616
1655
  };
1617
1656
  }
1618
1657
  if (group.errorCode) {
@@ -1649,6 +1688,28 @@ export function buildChainedSelections(next, groups, selections) {
1649
1688
  });
1650
1689
  return { selections: payload, skippedParents };
1651
1690
  }
1691
+ /** Where the latest sign-in or token check for a connection stands, as Wiro keeps it for 15 minutes. */
1692
+ export const OAUTH_FLOW_STATUSES = ['waiting', 'candidates', 'connected', 'saved', 'failed'];
1693
+ const FLOW_ID = /^[a-f0-9]{32}$/;
1694
+ const FLOW_ERROR_CODE = /^[a-z0-9_]{1,80}$/;
1695
+ const FLOW_ACCOUNT_MAX = 120;
1696
+ function parseOAuthFlow(value) {
1697
+ if (!isPlainObject(value))
1698
+ return null;
1699
+ const status = asString(value.status);
1700
+ if (!OAUTH_FLOW_STATUSES.includes(status ?? ''))
1701
+ return null;
1702
+ const mine = value.mine === true;
1703
+ const flowId = asString(value.flowid) ?? '';
1704
+ const errorCode = asString(value.errorcode)?.trim() ?? '';
1705
+ return {
1706
+ status: status,
1707
+ mine,
1708
+ flowId: mine && FLOW_ID.test(flowId) ? flowId : '',
1709
+ errorCode: FLOW_ERROR_CODE.test(errorCode) ? errorCode : '',
1710
+ account: oneLine(asString(value.account) ?? '').slice(0, FLOW_ACCOUNT_MAX),
1711
+ };
1712
+ }
1652
1713
  export function parseOAuthStatus(body, picker) {
1653
1714
  let childStep = null;
1654
1715
  const next = picker?.next;
@@ -1662,12 +1723,21 @@ export function parseOAuthStatus(body, picker) {
1662
1723
  groups: parseDiscoveredGroups(next, step.groups).map(group => ({ parent: group.parent, items: group.items })),
1663
1724
  };
1664
1725
  }
1726
+ const redirectUri = asString(body.redirecturi)?.trim();
1665
1727
  return {
1666
1728
  connected: body.connected === true,
1667
1729
  accounts: toAccountRefs(body.accounts, picker),
1668
1730
  connectedAt: asString(body.connectedat) ?? '',
1669
1731
  tokenExpiresAt: asString(body.tokenexpiresat) ?? '',
1670
1732
  childStep,
1733
+ candidates: toAccountRefs(body.candidates),
1734
+ flow: parseOAuthFlow(body.flow),
1735
+ ...(redirectUri ? { redirectUri } : {}),
1736
+ // Wiro says yes once every required field its own-app setup takes is saved. Its no says less than that the keys
1737
+ // are missing: it is also no for a service whose own-app setup needs a field Wiro manages, such as an approval,
1738
+ // and while any other required field is empty. So only a yes is kept.
1739
+ ...(body.appkeyssaved === true ? { appKeysSaved: true } : {}),
1740
+ ...(typeof body.tokensaved === 'boolean' ? { tokenSaved: body.tokensaved } : {}),
1671
1741
  };
1672
1742
  }
1673
1743
  export async function readOAuthStatus(client, agentGuid, credential, picker, signal) {
@@ -1677,12 +1747,41 @@ export async function readOAuthStatus(client, agentGuid, credential, picker, sig
1677
1747
  }, signal), 'Could not read the connection status.');
1678
1748
  return parseOAuthStatus(body, picker);
1679
1749
  }
1750
+ /**
1751
+ * The latest sign-in or token check this connection's person started decides first: a list of accounts to choose
1752
+ * from, a sign-in still open in the browser, or one that failed. A sign-in that keeps its account list on the
1753
+ * server writes no connectedat until the choice is saved, so only the flow tells it is done.
1754
+ */
1755
+ function ownFlowState(status) {
1756
+ const flow = status.flow;
1757
+ if (!flow?.mine)
1758
+ return null;
1759
+ if (ownCandidates(status).length > 0)
1760
+ return 'pick_accounts';
1761
+ if (flow.status === 'waiting')
1762
+ return 'waiting_for_user';
1763
+ if (flow.status === 'failed')
1764
+ return 'not_connected';
1765
+ return null;
1766
+ }
1767
+ /** The accounts this connection's person can choose from now: the list of their own latest sign-in or token check. */
1768
+ export function ownCandidates(status) {
1769
+ return status.flow?.mine === true && status.flow.status === 'candidates' ? status.candidates ?? [] : [];
1770
+ }
1771
+ /** The latest sign-in or token check of this connection's person, when it failed, so waiting for it ends. */
1772
+ export function ownFailedFlow(status) {
1773
+ return status.flow?.mine === true && status.flow.status === 'failed' ? status.flow : null;
1774
+ }
1680
1775
  /**
1681
1776
  * Wiro reports a picker credential as not connected until an account is
1682
1777
  * saved, so a fresh connectedat with no accounts means "signed in, accounts
1683
1778
  * still to choose". since is the connectedat seen before the sign-in started.
1779
+ * An answer without a flow of this connection's person reads by these rules alone.
1684
1780
  */
1685
1781
  export function connectionState(status, options) {
1782
+ const fromFlow = ownFlowState(status);
1783
+ if (fromFlow)
1784
+ return fromFlow;
1686
1785
  if (options.since !== undefined && status.connectedAt === options.since)
1687
1786
  return 'waiting_for_user';
1688
1787
  if (status.connected) {