@wiro-ai/wiro-mcp 1.5.8 → 1.6.1

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 (103) 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 +44 -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 +42 -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 +7 -4
  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 +5 -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 +10 -5
  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 +2 -1
  59. package/dist/tools/update-agent.js.map +1 -1
  60. package/dist/types.d.ts +6 -0
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/types.js.map +1 -1
  63. package/dist/utils/agent-catalog.d.ts +16 -12
  64. package/dist/utils/agent-catalog.d.ts.map +1 -1
  65. package/dist/utils/agent-catalog.js +4 -11
  66. package/dist/utils/agent-catalog.js.map +1 -1
  67. package/dist/utils/agent-config.d.ts +98 -45
  68. package/dist/utils/agent-config.d.ts.map +1 -1
  69. package/dist/utils/agent-config.js +246 -147
  70. package/dist/utils/agent-config.js.map +1 -1
  71. package/dist/utils/agent-message.d.ts +18 -0
  72. package/dist/utils/agent-message.d.ts.map +1 -1
  73. package/dist/utils/agent-setup.d.ts +53 -2
  74. package/dist/utils/agent-setup.d.ts.map +1 -1
  75. package/dist/utils/agent-setup.js +371 -22
  76. package/dist/utils/agent-setup.js.map +1 -1
  77. package/dist/utils/agent-targets.d.ts.map +1 -1
  78. package/dist/utils/agent-targets.js +9 -2
  79. package/dist/utils/agent-targets.js.map +1 -1
  80. package/dist/utils/agent-turns.d.ts +18 -0
  81. package/dist/utils/agent-turns.d.ts.map +1 -1
  82. package/dist/utils/agent-turns.js +73 -14
  83. package/dist/utils/agent-turns.js.map +1 -1
  84. package/dist/utils/api.d.ts +1 -1
  85. package/dist/utils/api.d.ts.map +1 -1
  86. package/dist/utils/api.js +3 -3
  87. package/dist/utils/api.js.map +1 -1
  88. package/dist/utils/format.d.ts +8 -1
  89. package/dist/utils/format.d.ts.map +1 -1
  90. package/dist/utils/format.js +16 -2
  91. package/dist/utils/format.js.map +1 -1
  92. package/dist/utils/quoted-text.d.ts +7 -0
  93. package/dist/utils/quoted-text.d.ts.map +1 -1
  94. package/dist/utils/quoted-text.js +14 -0
  95. package/dist/utils/quoted-text.js.map +1 -1
  96. package/dist/utils/structured.d.ts.map +1 -1
  97. package/dist/utils/structured.js +2 -2
  98. package/dist/utils/structured.js.map +1 -1
  99. package/dist/utils/user-agent.d.ts +76 -18
  100. package/dist/utils/user-agent.d.ts.map +1 -1
  101. package/dist/utils/user-agent.js +202 -49
  102. package/dist/utils/user-agent.js.map +1 -1
  103. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { apiErrorMessage, asString, errorResult, errorText, isPlainObject, requireApiSuccess, } from '../utils/api.js';
3
- import { CONNECTION_NOT_CLEARED, OAUTH_LINK_TTL_SECONDS, accountLabel, agentStatusOf, buildChainedSelections, buildPickerAccounts, chooseConnectionMode, connectionModeRequirements, connectionRefusalText, connectionState, credentialGroup, customSkillEntries, dashboardAgentUrl, entriesTurnedOnBy, isAgentRunning, isAllowedRedirectUrl, isFilledValue, loadCredentialMeta, loadSkillRegistry, ownAppRedirectUri, parseDiscoveredGroups, pausedSkillTitles, readOAuthStatus, readUserAgent, skillTitles, toAccountRefs, turnOnSkillText, unusedCredential, unusedCredentialNote, writeOnlyModesNote, } from '../utils/agent-config.js';
2
+ import { ApiResultError, apiErrorMessage, asString, errorResult, errorText, isPlainObject, requireApiSuccess, } from '../utils/api.js';
3
+ import { CONNECTION_NOT_CLEARED, OAUTH_LINK_TTL_SECONDS, accountLabel, agentStatusOf, apiBaseUrlOf, buildChainedSelections, chooseConnectionMode, connectionModeRequirements, connectionRefusalText, connectionState, credentialGroup, customSkillEntries, dashboardAgentUrl, entriesTurnedOnBy, isAgentRunning, isAllowedRedirectUrl, isFilledValue, loadCredentialMeta, loadSkillRegistry, modeContext, ownAppRedirectUri, ownCandidates, ownFailedFlow, parseDiscoveredGroups, pausedSkillTitles, pickedAccountIds, readOAuthStatus, readUserAgent, savedForModesText, skillTitles, statusRedirectUri, toAccountRefs, turnOnSkillText, unusedCredential, unusedCredentialNote, writeOnlyModesNote, } from '../utils/agent-config.js';
4
4
  import { DEFAULT_WAIT_SECONDS, MAX_WAIT_SECONDS, pollUntil, reportProgress, } from '../utils/poll.js';
5
5
  import { jsonSpan } from '../utils/quoted-text.js';
6
6
  import { readStatusAdvice, skillOffTasksNote, startNeedsPlan, taskLabel, taskNamedByWiro, toAgentDetail, waitingTaskSentence, WIRO_PROJECT_CREDENTIAL } from '../utils/user-agent.js';
@@ -49,15 +49,42 @@ const outputSchema = {
49
49
  note: z.string(),
50
50
  })).optional(),
51
51
  ownAppRedirectUri: z.string().optional(),
52
+ appKeysSaved: z.boolean().optional()
53
+ .describe('status: true when Wiro says the keys of the user\'s own app (mode own) are saved. They are never shown. Left out otherwise, which does not mean they are missing.'),
54
+ tokenSaved: z.boolean().optional()
55
+ .describe('status: whether the token, or every field the token check reads, is saved, as Wiro says.'),
52
56
  message: z.string(),
53
57
  nextAction: nextActionSchema.optional(),
54
58
  };
55
59
  const DONE_STATES = new Set(['connected', 'pick_accounts', 'pick_child_items']);
56
- function oauthHint(message, meta) {
60
+ // Wiro keeps the accounts a sign-in or token check found for 15 minutes, only for the person who started it, and
61
+ // saves only accounts from that list. These codes say the list is gone or someone else's.
62
+ const FLOW_GONE_CODES = new Set(['flow_expired', 'flow_other_person', 'flow_replaced']);
63
+ // A sign-in still open in the browser has no list yet. A new connect would replace it, and that sign-in would then
64
+ // save nothing, so the user finishes it instead.
65
+ const FLOW_WAITING_HINT = 'The sign-in is still open: ask the user to finish it in the browser, then call select_accounts '
66
+ + 'again (connect_agent_oauth status with wait_seconds waits until it is done). Do not start a new connect, which '
67
+ + 'would replace the open sign-in.';
68
+ // Wiro words these refusals for a sign-in or for a token check, as the list they are about, the saved mode or the
69
+ // service's first way to connect says. The hints after them fit both.
70
+ function oauthHint(message, meta, code) {
71
+ if (code === 'not_listed')
72
+ return 'Save only accounts from the list connect_agent_oauth gave after the sign-in or token check.';
73
+ if (code === 'flow_waiting')
74
+ return FLOW_WAITING_HINT;
75
+ if (code && FLOW_GONE_CODES.has(code)) {
76
+ return 'Connect again: the list is kept 15 minutes and only for the person who started the sign-in or token check.';
77
+ }
78
+ if (code === 'flow_failed')
79
+ return 'Connect again with action connect.';
80
+ if (code === 'next_expired')
81
+ return 'Call select_accounts again; it lists the items afresh before saving.';
57
82
  if (/credentials not configured/i.test(message)) {
58
83
  return `Save your own ${meta.title} app keys with set_agent_credentials first (call it with credential "${meta.key}" to see the fields).`;
59
84
  }
60
- if (/wiro-managed oauth is not enabled/i.test(message)) {
85
+ // A sign-in with Wiro's own app that is not open for this service: "Sign-in with the platform's app is not enabled
86
+ // for <title>", as Wiro words it now, or "Wiro-managed OAuth is not enabled for <title>", as it did.
87
+ if (/(sign-in with the platform's app|wiro-managed oauth) is not enabled/i.test(message)) {
61
88
  return 'Connect this service with mode own (your own app) or api_key where offered.';
62
89
  }
63
90
  if (/no pending .* connection/i.test(message)) {
@@ -72,7 +99,8 @@ function oauthHint(message, meta) {
72
99
  /** Wiro's message, then the hint as a paragraph of its own, so the two read as separate sentences. */
73
100
  function withHint(error, meta) {
74
101
  const message = errorText(error);
75
- const hint = meta ? oauthHint(message, meta) : undefined;
102
+ const code = error instanceof ApiResultError ? asString(error.body.errorcode) : undefined;
103
+ const hint = meta ? oauthHint(message, meta, code) : undefined;
76
104
  return new Error(hint ? `${message}\n\n${hint}` : message);
77
105
  }
78
106
  function childStepOf(picker, groups, configured) {
@@ -167,8 +195,12 @@ async function connect(context, input) {
167
195
  if (refusal)
168
196
  return errorResult(new Error(refusal));
169
197
  const group = credentialGroup(row, credential);
170
- const modes = connectionModeRequirements(meta, group);
171
- const redirectUri = meta.connectionModes.includes('own') ? ownAppRedirectUri(meta) : undefined;
198
+ const apiBase = apiBaseUrlOf(client);
199
+ // One status read gives the connection time before this sign-in, the redirect URI Wiro gives for the user's own
200
+ // app, whether Wiro says the app keys are saved and whether the token is. A connect still goes ahead without it.
201
+ const before = await readOAuthStatus(client, agentGuid, credential, oauth.picker, signal).catch(() => null);
202
+ const modes = connectionModeRequirements(meta, group, modeContext(before, apiBase));
203
+ const redirectUri = meta.connectionModes.includes('own') ? ownAppRedirectUri(meta, before?.redirectUri, apiBase) : undefined;
172
204
  const setupExtra = { connectionModes: modes, ...(redirectUri ? { ownAppRedirectUri: redirectUri } : {}) };
173
205
  const describeAction = {
174
206
  tool: 'set_agent_credentials',
@@ -256,15 +288,22 @@ async function connect(context, input) {
256
288
  // An error result reads as nothing done, so it says what the check still did.
257
289
  if (modeSaved)
258
290
  parts.push(`The mode is saved as ${mode}.`);
259
- if ((modeSaved || code) && isAgentRunning(agentStatusOf(row))) {
291
+ // Wiro restarts a running agent after a failed check only when the check cleared a connection that read
292
+ // connected before it, and says so in restart. Saving the mode restarts it only when the service read
293
+ // connected. An answer without restart, from an older Wiro API, goes by the saved mode and the code.
294
+ const restart = asString(body.restart);
295
+ const restarts = restart === undefined
296
+ ? modeSaved || Boolean(code)
297
+ : restart === 'scheduled' || (modeSaved && connectedBefore);
298
+ if (restarts && isAgentRunning(agentStatusOf(row))) {
260
299
  parts.push('The running agent restarts, which takes about a minute.');
261
300
  }
262
301
  return errorResult(new Error(parts.join(' ')));
263
302
  }
264
303
  const candidates = toAccountRefs(body.accounts, oauth.picker);
265
304
  if (oauth.picker && candidates.length > 0) {
266
- const pending = oauth.picker.pendingCache ? ' Save the choice within 15 minutes; after that, connect again.' : '';
267
- return result('connect', context, 'pick_accounts', `${meta.title} accepted the ${oauth.directProbe.label ?? 'credentials'}. Choose which of these accounts the agent should use.${pending}`, {
305
+ // Wiro keeps this list 15 minutes, only for the person who ran the check, and saves only accounts from it.
306
+ return result('connect', context, 'pick_accounts', `${meta.title} accepted the ${oauth.directProbe.label ?? 'credentials'}. Choose which of these accounts the agent should use. Save the choice within 15 minutes; after that, connect again.`, {
268
307
  mode,
269
308
  candidates,
270
309
  nextAction: {
@@ -278,17 +317,11 @@ async function connect(context, input) {
278
317
  }
279
318
  return result('connect', context, 'connected', `${meta.title} is connected. A running agent restarts to use it.`, { mode });
280
319
  }
281
- const redirectUrl = input.redirectUrl?.trim() || dashboardAgentUrl(agentGuid);
282
- if (!isAllowedRedirectUrl(redirectUrl, agentGuid)) {
283
- return errorResult(new Error(`redirect_url can only be the agent's page in the Wiro dashboard (${dashboardAgentUrl(agentGuid)}) or a local address on the user's own machine (http://localhost or http://127.0.0.1, any port). Leave it out to use the dashboard page.`));
284
- }
285
- let since = '';
286
- try {
287
- since = (await readOAuthStatus(client, agentGuid, credential, oauth.picker, signal)).connectedAt;
288
- }
289
- catch {
290
- since = '';
320
+ const redirectUrl = input.redirectUrl?.trim() || dashboardAgentUrl(agentGuid, apiBase);
321
+ if (!isAllowedRedirectUrl(redirectUrl, agentGuid, apiBase)) {
322
+ return errorResult(new Error(`redirect_url can only be the agent's page in the Wiro dashboard (${dashboardAgentUrl(agentGuid, apiBase)}) or a local address on the user's own machine (http://localhost or http://127.0.0.1, any port). Leave it out to use the dashboard page.`));
291
323
  }
324
+ const since = before?.connectedAt ?? '';
292
325
  const answer = await client.post('/UserAgentOAuth/OAuthConnect', {
293
326
  useragentguid: agentGuid,
294
327
  credentialkey: credential,
@@ -303,7 +336,7 @@ async function connect(context, input) {
303
336
  const goneText = gone.length > 0
304
337
  ? ` The sign-in did not start, and this call removed the saved ${gone.map(field => field.label).join(', ')}${connectedBefore && groupNow?._connected !== true ? `, so ${meta.title} is no longer connected` : ''}. To go back to it, save it again with set_agent_credentials.`
305
338
  : '';
306
- return result('connect', context, 'setup_needed', `Mode ${mode} needs these saved first with set_agent_credentials: ${appKeys.map(field => `${field.label} (${field.field})`).join(', ')}. ${requirement.note}${goneText}`, { ...setupExtra, connectionModes: connectionModeRequirements(meta, groupNow), mode, nextAction: describeAction });
339
+ return result('connect', context, 'setup_needed', `Mode ${mode} needs these saved first with set_agent_credentials: ${appKeys.map(field => `${field.label} (${field.field})`).join(', ')}. ${requirement.note}${goneText}`, { ...setupExtra, connectionModes: connectionModeRequirements(meta, groupNow, modeContext(before, apiBase)), mode, nextAction: describeAction });
307
340
  }
308
341
  const body = requireApiSuccess(answer, `Could not start the ${meta.title} sign-in.`);
309
342
  const authorizeUrl = asString(body.authorizeUrl);
@@ -311,7 +344,7 @@ async function connect(context, input) {
311
344
  throw new Error(`Wiro did not return a sign-in link for ${meta.title}.`);
312
345
  const usesDashboard = !/^http:/i.test(redirectUrl);
313
346
  const after = usesDashboard
314
- ? `After approving, the browser returns to the agent's page in the Wiro dashboard${oauth.picker ? ', which asks which accounts the agent should use' : ''}. Use a browser where the user is signed in to wiro.ai as the agent's owner.`
347
+ ? `After approving, the browser returns to the agent's page in the Wiro dashboard.${oauth.picker ? ' Then status lists the accounts the sign-in found, to choose from within 15 minutes.' : ''}`
315
348
  : `After approving, the browser goes to ${redirectUrl}.`;
316
349
  const turnsOn = entriesTurnedOnBy(row, credential);
317
350
  const titles = await skillTitles(client, [...turnsOn.paused, ...turnsOn.waiting].flatMap(task => task.groups.flat()), signal);
@@ -360,17 +393,31 @@ function statusMessage(state, meta, snapshot, unusedNote, row) {
360
393
  return `${meta.title} is connected${snapshot.accounts.length > 0 ? ` for ${accountsLine(snapshot.accounts)}` : ''}.${optionalStep}`;
361
394
  }
362
395
  case 'pick_accounts':
363
- return 'The user approved access. The accounts to use are chosen on the agent\'s page in the Wiro dashboard that opened after the sign-in. If that page was closed, connect again, or save account IDs the user gives you with action select_accounts.';
396
+ if (ownCandidates(snapshot).length > 0) {
397
+ return 'The user approved access. Ask which of these accounts the agent should use, then save them with '
398
+ + 'select_accounts within 15 minutes. If the agent\'s page in the Wiro dashboard is open, it offers the same list.';
399
+ }
400
+ // Wiro keeps the list 15 minutes, only for the person who started the sign-in, so here it is gone or someone else's.
401
+ return snapshot.flow && !snapshot.flow.mine
402
+ ? `The ${meta.title} sign-in finished, but another admin of this agent's team started a newer one, so the account list goes only to them. Connect again to choose the accounts yourself.`
403
+ : `The ${meta.title} sign-in finished, but its account list is no longer kept: Wiro keeps it 15 minutes, only for the person who started the sign-in. Connect again to choose the accounts.`;
364
404
  case 'pick_child_items':
365
405
  return `Access is approved, but ${next?.label ?? 'the second step'} still has to be chosen for each account. Call select_accounts with picker "${next?.key ?? ''}" to list them.`;
366
406
  case 'waiting_for_user':
367
407
  return `The ${meta.title} sign-in has not finished yet. The link from connect works for ${OAUTH_LINK_TTL_SECONDS / 60} minutes; after that, connect again.`;
368
408
  case 'token_expired':
369
409
  return `The saved ${meta.title} access has expired.${saved ? ` The connection is still saved, so get_my_agent lists ${meta.title} as connected.` : ''} ${unusedNote ?? expiredAdvice(row)}`;
370
- default:
410
+ default: {
411
+ const failed = ownFailedFlow(snapshot);
412
+ if (failed) {
413
+ return `The latest ${meta.title} connection attempt did not finish${failed.errorCode ? ` (${failed.errorCode})` : ''}.`
414
+ + `${saved ? ` The ${meta.title} connection saved before it is still there, so get_my_agent lists it as connected.` : ''}`
415
+ + ` ${unusedNote ?? 'Connect again with action connect.'}`;
416
+ }
371
417
  return saved
372
418
  ? `This check found no current ${meta.title} sign-in, but a ${meta.title} connection is saved on this agent, so get_my_agent lists it as connected. ${unusedNote ?? 'If the agent cannot use it, connect again: that replaces the saved connection and asks for confirm: true.'}`
373
419
  : `${meta.title} is not connected. ${unusedNote ?? 'Start with action connect.'}`;
420
+ }
374
421
  }
375
422
  }
376
423
  async function status(context, input, extra) {
@@ -379,7 +426,8 @@ async function status(context, input, extra) {
379
426
  const stateOf = (snapshot) => connectionState(snapshot, { hasPicker: picker !== null, since: input.since });
380
427
  const polled = await pollUntil({
381
428
  read: readSignal => readOAuthStatus(client, agentGuid, credential, picker, readSignal),
382
- isDone: snapshot => DONE_STATES.has(stateOf(snapshot)),
429
+ // A failed sign-in or token check of this person ends the wait: nothing more comes from it.
430
+ isDone: snapshot => DONE_STATES.has(stateOf(snapshot)) || ownFailedFlow(snapshot) !== null,
383
431
  timeoutMs: input.waitSeconds * 1000,
384
432
  signal,
385
433
  interval: () => 5_000,
@@ -389,10 +437,26 @@ async function status(context, input, extra) {
389
437
  if (!snapshot)
390
438
  throw new Error(`Could not read the ${meta.title} connection status.`);
391
439
  const state = stateOf(snapshot);
440
+ const candidates = state === 'pick_accounts' ? ownCandidates(snapshot) : [];
392
441
  let nextAction;
393
442
  let unusedNote = null;
394
443
  let row = null;
395
- if (state === 'waiting_for_user') {
444
+ if (state === 'pick_accounts') {
445
+ nextAction = candidates.length > 0
446
+ ? {
447
+ tool: 'connect_agent_oauth',
448
+ arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, accounts: candidates },
449
+ reason: candidates.length === 1
450
+ ? 'Save the only available account.'
451
+ : 'Ask the user which accounts to use, then save only those.',
452
+ }
453
+ : {
454
+ tool: 'connect_agent_oauth',
455
+ arguments: { action: 'connect', agent_guid: agentGuid, credential },
456
+ reason: `Connect ${meta.title} again for a new account list.`,
457
+ };
458
+ }
459
+ else if (state === 'waiting_for_user') {
396
460
  nextAction = {
397
461
  tool: 'connect_agent_oauth',
398
462
  arguments: {
@@ -439,13 +503,156 @@ async function status(context, input, extra) {
439
503
  const childStep = snapshot.childStep
440
504
  ? { ...snapshot.childStep, label: picker?.next?.label ?? snapshot.childStep.picker }
441
505
  : undefined;
442
- return result('status', context, state, `${statusMessage(state, meta, snapshot, unusedNote, row)}${pausedNote}`, {
506
+ const setup = setupFromStatus(meta, snapshot);
507
+ // Where connect is offered, the message says what is saved for it and the redirect URI the user's own app allows.
508
+ const setupNote = (state === 'not_connected' || state === 'token_expired') && setup.text ? ` ${setup.text}` : '';
509
+ return result('status', context, state, `${statusMessage(state, meta, snapshot, unusedNote, row)}${setupNote}${pausedNote}`, {
443
510
  ...(snapshot.connectedAt ? { connectedAt: snapshot.connectedAt } : {}),
444
511
  ...(snapshot.tokenExpiresAt ? { tokenExpiresAt: snapshot.tokenExpiresAt } : {}),
445
512
  accounts: snapshot.accounts,
513
+ ...(candidates.length > 0 ? { candidates } : {}),
446
514
  ...(childStep ? { childStep } : {}),
515
+ ...setup.extra,
447
516
  ...(nextAction ? { nextAction } : {}),
448
- });
517
+ }, candidates.length > 0 ? ['', ...candidates.map(account => `- ${accountLabel(account)}`)] : []);
518
+ }
519
+ /**
520
+ * What Wiro's status says about the setup the connection modes need: that the keys of the user's own app are saved
521
+ * (only a yes is kept; see parseOAuthStatus), whether the token is, and the redirect URI to allow in that app. An
522
+ * older Wiro API says none of it.
523
+ */
524
+ function setupFromStatus(meta, snapshot) {
525
+ const ownMode = meta.connectionModes.includes('own');
526
+ const probe = meta.oauth?.directProbe;
527
+ const redirect = ownMode ? statusRedirectUri(meta, snapshot.redirectUri) : undefined;
528
+ const extra = {
529
+ ...(redirect ? { ownAppRedirectUri: redirect } : {}),
530
+ ...(ownMode && snapshot.appKeysSaved === true ? { appKeysSaved: true } : {}),
531
+ ...(probe && snapshot.tokenSaved !== undefined ? { tokenSaved: snapshot.tokenSaved } : {}),
532
+ };
533
+ const text = [
534
+ savedForModesText(meta, snapshot),
535
+ redirect ? `With mode own, the user's own app must allow ${redirect} as a redirect URI.` : '',
536
+ ].filter(Boolean).join(' ');
537
+ return { extra, text };
538
+ }
539
+ /** The child step's items as Wiro saved them, under each readable account. */
540
+ function savedChildGroups(next, groups, saved) {
541
+ const mappings = Array.isArray(saved[next.persistField]) ? saved[next.persistField].filter(isPlainObject) : [];
542
+ const savedGroups = groups.filter(group => !group.errorCode).map(group => ({
543
+ ...group,
544
+ items: mappings
545
+ .filter(mapping => asString(mapping[next.parentValueField]) === group.parent.id)
546
+ .map(mapping => ({
547
+ id: asString(mapping[next.itemValueField]) ?? '',
548
+ name: asString(mapping[next.itemLabelField]) ?? '',
549
+ })),
550
+ }));
551
+ return { mappings, savedGroups };
552
+ }
553
+ function childStepLines(groups) {
554
+ return ['', ...groups.flatMap(group => [
555
+ `- ${accountLabel(group.parent)}${group.errorCode ? `: could not be read (${group.errorCode})` : ''}`,
556
+ ...group.items.map(item => ` - ${accountLabel(item)}`),
557
+ ])];
558
+ }
559
+ function preselected(groups) {
560
+ return groups.filter(group => !group.errorCode).map(group => ({ parent: group.parent.id, items: group.items.map(item => item.id) }));
561
+ }
562
+ /** The extra step alone, for accounts saved before: it lists the items, or saves the ones chosen. */
563
+ async function childStepAlone(context, picker, next, selections) {
564
+ const { client, agentGuid, credential, signal } = context;
565
+ // Discovery runs before every save: the API only accepts items, with their exact labels, from a fresh list.
566
+ const discovered = requireApiSuccess(await client.post('/UserAgentOAuth/DiscoverPickerItems', {
567
+ useragentguid: agentGuid,
568
+ credentialkey: credential,
569
+ pickerkey: next.key,
570
+ }, signal), `Could not list the ${next.label}.`);
571
+ const groups = parseDiscoveredGroups(next, discovered.groups);
572
+ if (!selections) {
573
+ return result('select_accounts', context, 'pick_child_items', `Choose the ${next.label} to use under each account.${next.optional ? ' This step is optional.' : ''} Then call select_accounts again with picker "${next.key}" and selections.`, {
574
+ childStep: childStepOf(picker, groups),
575
+ nextAction: {
576
+ tool: 'connect_agent_oauth',
577
+ arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, picker: next.key, selections: preselected(groups) },
578
+ reason: 'Ask the user which ones to keep; this preselects all of them.',
579
+ },
580
+ }, childStepLines(groups));
581
+ }
582
+ const built = buildChainedSelections(next, groups, selections);
583
+ if (built.error || !built.selections)
584
+ return errorResult(new Error(built.error ?? 'Nothing to save.'));
585
+ const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
586
+ useragentguid: agentGuid,
587
+ credentialkey: credential,
588
+ pickerkey: next.key,
589
+ selections: built.selections,
590
+ }, signal), `Could not save the ${next.label}.`);
591
+ const { mappings, savedGroups } = savedChildGroups(next, groups, saved);
592
+ const skipped = built.skippedParents.length > 0
593
+ ? ` Nothing was chosen for ${accountsLine(built.skippedParents)}.`
594
+ : '';
595
+ return result('select_accounts', context, 'connected', `Saved the ${next.label} selection (${mappings.length} selected).${skipped} A running agent restarts to use it.`, { childStep: { ...childStepOf(picker, savedGroups, mappings.length > 0) } });
596
+ }
597
+ /**
598
+ * The id of this person's latest sign-in or token check, or empty. Wiro keeps the extra step it lists for the
599
+ * accounts of that flow, so the listing and the save both name it. Without it, Wiro goes by its current flow alone.
600
+ */
601
+ async function ownFlowId({ client, agentGuid, credential, signal }, picker) {
602
+ const snapshot = await readOAuthStatus(client, agentGuid, credential, picker, signal).catch(() => null);
603
+ return snapshot?.flow?.mine ? snapshot.flow.flowId : '';
604
+ }
605
+ /**
606
+ * Accounts from the list a sign-in or token check gave, with the extra step some providers have. Wiro lists that
607
+ * step for the chosen accounts before they are saved, so the accounts and the step are saved in one call and a
608
+ * running agent restarts once.
609
+ */
610
+ async function accountsWithChildStep(context, picker, next, accounts, ids, selections) {
611
+ const { client, agentGuid, credential, signal } = context;
612
+ if (next.maxParents !== undefined && ids.length > next.maxParents) {
613
+ const most = `${next.maxParents} account${next.maxParents === 1 ? '' : 's'}`;
614
+ return errorResult(new Error(`Choose at most ${most} to go on: Wiro lists the ${next.label} for at most ${most} at once.`));
615
+ }
616
+ const flowId = await ownFlowId(context, picker);
617
+ const flow = flowId ? { flowid: flowId } : {};
618
+ const discovered = requireApiSuccess(await client.post('/UserAgentOAuth/DiscoverPickerItems', {
619
+ useragentguid: agentGuid,
620
+ credentialkey: credential,
621
+ pickerkey: next.key,
622
+ parents: ids,
623
+ ...flow,
624
+ }, signal), `Could not list the ${next.label}.`);
625
+ const groups = parseDiscoveredGroups(next, discovered.groups);
626
+ if (!selections) {
627
+ return result('select_accounts', context, 'pick_child_items', `Nothing is saved yet. Choose the ${next.label} to use under each account.${next.optional ? ` This step is optional: empty selections save the accounts without any ${next.label}.` : ''} Then call select_accounts again with these accounts, picker "${next.key}" and selections within 15 minutes of the sign-in or token check: it saves both at once, so a running agent restarts only once.`, {
628
+ childStep: childStepOf(picker, groups),
629
+ nextAction: {
630
+ tool: 'connect_agent_oauth',
631
+ arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, accounts, picker: next.key, selections: preselected(groups) },
632
+ reason: 'Ask the user which ones to keep; this preselects all of them.',
633
+ },
634
+ }, childStepLines(groups));
635
+ }
636
+ const built = buildChainedSelections(next, groups, selections);
637
+ if (built.error || !built.selections)
638
+ return errorResult(new Error(built.error ?? 'Nothing to save.'));
639
+ const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
640
+ useragentguid: agentGuid,
641
+ credentialkey: credential,
642
+ ...flow,
643
+ accountids: ids,
644
+ pickerkey: next.key,
645
+ selections: built.selections.map(selection => ({
646
+ parentvalue: selection.parentvalue,
647
+ itemids: selection.items.map(item => item[next.itemValueField]),
648
+ })),
649
+ }, signal), 'Could not save the accounts.');
650
+ const savedAccounts = toAccountRefs(saved.accounts, picker);
651
+ const { mappings, savedGroups } = savedChildGroups(next, groups, saved);
652
+ const skipped = built.skippedParents.length > 0
653
+ ? ` Nothing was chosen for ${accountsLine(built.skippedParents)}.`
654
+ : '';
655
+ return result('select_accounts', context, 'connected', `Saved ${savedAccounts.length} account${savedAccounts.length === 1 ? '' : 's'}: ${accountsLine(savedAccounts)}, and the ${next.label} selection (${mappings.length} selected).${skipped} A running agent restarts once to use them.`, { accounts: savedAccounts, childStep: { ...childStepOf(picker, savedGroups, mappings.length > 0) } });
449
656
  }
450
657
  async function selectAccounts(context, input) {
451
658
  const { client, agentGuid, credential, meta, signal } = context;
@@ -453,88 +660,28 @@ async function selectAccounts(context, input) {
453
660
  if (!picker) {
454
661
  return errorResult(new Error(`${meta.title} has no account choice to make; its connection is complete once connected.`));
455
662
  }
456
- if (input.picker) {
457
- const next = picker.next;
458
- if (!next || next.key !== input.picker) {
459
- return errorResult(new Error(`${meta.title} has no step "${input.picker}".${next ? ` Its extra step is "${next.key}".` : ''}`));
460
- }
461
- // Discovery runs before every save: the API only accepts items, with their exact labels, from a fresh list.
462
- const discovered = requireApiSuccess(await client.post('/UserAgentOAuth/DiscoverPickerItems', {
463
- useragentguid: agentGuid,
464
- credentialkey: credential,
465
- pickerkey: next.key,
466
- }, signal), `Could not list the ${next.label}.`);
467
- const groups = parseDiscoveredGroups(next, discovered.groups);
468
- if (!input.selections) {
469
- const readable = groups.filter(group => !group.errorCode);
470
- return result('select_accounts', context, 'pick_child_items', `Choose the ${next.label} to use under each account.${next.optional ? ' This step is optional.' : ''} Then call select_accounts again with picker "${next.key}" and selections.`, {
471
- childStep: childStepOf(picker, groups),
472
- nextAction: {
473
- tool: 'connect_agent_oauth',
474
- arguments: {
475
- action: 'select_accounts',
476
- agent_guid: agentGuid,
477
- credential,
478
- picker: next.key,
479
- selections: readable.map(group => ({ parent: group.parent.id, items: group.items.map(item => item.id) })),
480
- },
481
- reason: 'Ask the user which ones to keep; this preselects all of them.',
482
- },
483
- }, ['', ...groups.flatMap(group => [
484
- `- ${accountLabel(group.parent)}${group.errorCode ? `: could not be read (${group.errorCode})` : ''}`,
485
- ...group.items.map(item => ` - ${accountLabel(item)}`),
486
- ])]);
487
- }
488
- const built = buildChainedSelections(next, groups, input.selections);
489
- if (built.error || !built.selections)
490
- return errorResult(new Error(built.error ?? 'Nothing to save.'));
491
- const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
492
- useragentguid: agentGuid,
493
- credentialkey: credential,
494
- pickerkey: next.key,
495
- selections: built.selections,
496
- }, signal), `Could not save the ${next.label}.`);
497
- const mappings = Array.isArray(saved[next.persistField]) ? saved[next.persistField].filter(isPlainObject) : [];
498
- const savedGroups = groups.filter(group => !group.errorCode).map(group => ({
499
- ...group,
500
- items: mappings
501
- .filter(mapping => asString(mapping[next.parentValueField]) === group.parent.id)
502
- .map(mapping => ({
503
- id: asString(mapping[next.itemValueField]) ?? '',
504
- name: asString(mapping[next.itemLabelField]) ?? '',
505
- })),
506
- }));
507
- const skipped = built.skippedParents.length > 0
508
- ? ` Nothing was chosen for ${accountsLine(built.skippedParents)}.`
509
- : '';
510
- return result('select_accounts', context, 'connected', `Saved the ${next.label} selection (${mappings.length} selected).${skipped} A running agent restarts to use it.`, { childStep: { ...childStepOf(picker, savedGroups, mappings.length > 0) } });
663
+ const next = picker.next;
664
+ if (input.picker && (!next || next.key !== input.picker)) {
665
+ return errorResult(new Error(`${meta.title} has no step "${input.picker}".${next ? ` Its extra step is "${next.key}".` : ''}`));
511
666
  }
512
- if (!input.accounts || input.accounts.length === 0) {
667
+ const accounts = input.accounts ?? [];
668
+ if (next && input.picker && accounts.length === 0)
669
+ return childStepAlone(context, picker, next, input.selections);
670
+ if (accounts.length === 0) {
513
671
  return errorResult(new Error('Pass accounts (each {id, name}) to save, or picker to run the extra step.'));
514
672
  }
515
- const built = buildPickerAccounts(picker, input.accounts);
516
- if (built.error || !built.accounts)
517
- return errorResult(new Error(built.error ?? 'Nothing to save.'));
673
+ const picked = pickedAccountIds(picker, accounts);
674
+ if (picked.error || !picked.ids)
675
+ return errorResult(new Error(picked.error ?? 'Nothing to save.'));
676
+ if (next)
677
+ return accountsWithChildStep(context, picker, next, accounts, picked.ids, input.selections);
518
678
  const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
519
679
  useragentguid: agentGuid,
520
680
  credentialkey: credential,
521
- accounts: built.accounts,
681
+ accountids: picked.ids,
522
682
  }, signal), 'Could not save the accounts.');
523
- const accounts = toAccountRefs(saved.accounts, picker);
524
- const next = picker.next;
525
- if (next) {
526
- return result('select_accounts', context, next.optional ? 'connected' : 'pick_child_items', `Saved ${accounts.length} account${accounts.length === 1 ? '' : 's'}: ${accountsLine(accounts)}. ${next.optional ? `Optionally, also choose ${next.label}.` : `Next, choose the ${next.label} for each account.`} A running agent restarts to use the account${accounts.length === 1 ? '' : 's'}.`, {
527
- accounts,
528
- nextAction: {
529
- tool: 'connect_agent_oauth',
530
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, picker: next.key },
531
- reason: next.optional
532
- ? `Optional: list the ${next.label} if the user wants to choose them.`
533
- : `List the ${next.label} to choose from.`,
534
- },
535
- });
536
- }
537
- return result('select_accounts', context, 'connected', `Saved ${accounts.length} account${accounts.length === 1 ? '' : 's'}: ${accountsLine(accounts)}. A running agent restarts to use the account${accounts.length === 1 ? '' : 's'}.`, { accounts });
683
+ const savedAccounts = toAccountRefs(saved.accounts, picker);
684
+ return result('select_accounts', context, 'connected', `Saved ${savedAccounts.length} account${savedAccounts.length === 1 ? '' : 's'}: ${accountsLine(savedAccounts)}. A running agent restarts to use the account${savedAccounts.length === 1 ? '' : 's'}.`, { accounts: savedAccounts });
538
685
  }
539
686
  export function registerConnectAgentOauth(server, client) {
540
687
  server.registerTool('connect_agent_oauth', {
@@ -549,16 +696,18 @@ export function registerConnectAgentOauth(server, client) {
549
696
  + 'the accounts it can use, with no browser. Without mode the tool picks the one that '
550
697
  + 'works; when a provider needs the user\'s own app keys or a token first, it says which to '
551
698
  + 'save. action status: whether the sign-in finished (wait_seconds waits for '
552
- + 'the user). action select_accounts: saves which accounts the agent uses ({id, name} from '
553
- + 'connect), and with picker runs the extra step some providers have (Meta Ads pages, '
554
- + 'Google Business locations). Connecting again replaces an existing connection, and a sign-in removes a token saved for another mode; both need '
699
+ + 'the user) and, once it did, lists the accounts to choose from. action select_accounts: saves which accounts the agent uses ({id, name} from '
700
+ + 'the list connect or status gave). Where a provider has an extra step (Meta Ads pages, Google Business locations), '
701
+ + 'it first lists that step for the chosen accounts and saves nothing, then saves the accounts and the selections '
702
+ + 'in one call, so a running agent restarts once; picker without accounts changes the extra step of accounts saved '
703
+ + 'before. Connecting again replaces an existing connection, and a sign-in removes a token saved for another mode; both need '
555
704
  + 'confirm: true. A running agent restarts when a connection or selection is saved. Connecting a service '
556
705
  + 'turns on the scheduled tasks that need it, and the result names any that stay paused until a skill they need is on; '
557
706
  + 'turn off any you do not want. '
558
707
  + 'Remove a connection with disconnect_agent_oauth. A credential that none of the agent\'s active '
559
708
  + 'skills use, that no custom skill or scheduled task of the agent requires, and that its setup does not wait for, is refused before any link is made (get_my_agent '
560
- + 'lists the skills; apply_agent_skills turns one on). Only the person who deployed the agent can connect, so the '
561
- + 'connected project must be one that person created. The agents playbook (get_playbook) has the '
709
+ + 'lists the skills; apply_agent_skills turns one on). The person who deployed the agent or a team admin of its '
710
+ + 'team can connect; the account list after a sign-in goes only to the person who started it. The agents playbook (get_playbook) has the '
562
711
  + 'full setup walkthrough.',
563
712
  inputSchema: strictInput({
564
713
  action: z.enum(['connect', 'status', 'select_accounts']).default('connect')
@@ -575,14 +724,14 @@ export function registerConnectAgentOauth(server, client) {
575
724
  wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).default(0)
576
725
  .describe(`status: how long to wait for the sign-in to finish, 0 to ${MAX_WAIT_SECONDS} seconds (default 0, a single check).`),
577
726
  accounts: z.array(z.record(z.string(), z.union([z.string(), z.number()]))).optional()
578
- .describe('select_accounts: the accounts to use, each {id, name}, as returned by connect.'),
727
+ .describe('select_accounts: the accounts to use, each {id, name}, from the list connect or status gave. Wiro saves only accounts from that list, for 15 minutes after the sign-in or token check.'),
579
728
  picker: z.string().optional()
580
- .describe('select_accounts: the extra step\'s key ("pages" for Meta Ads, "locations" for Google Business). Without selections it lists the choices.'),
729
+ .describe('select_accounts: the extra step\'s key ("pages" for Meta Ads, "locations" for Google Business). With accounts it may be left out. Without accounts it works on the accounts saved before. Without selections it lists the choices.'),
581
730
  selections: z.array(z.object({
582
731
  parent: z.string().describe('An account id from the earlier step.'),
583
732
  items: z.array(z.string()).describe('The ids of the items to use under that account.'),
584
733
  })).optional()
585
- .describe('select_accounts with picker: what to use under each account. Accounts left out get nothing.'),
734
+ .describe('select_accounts: what to use under each account in the extra step. With accounts, both are saved in one call. Accounts left out get nothing.'),
586
735
  confirm: z.boolean().default(false)
587
736
  .describe('connect: true to replace an existing connection or a token saved for another mode, after the user agreed.'),
588
737
  }),