@wiro-ai/wiro-mcp 1.9.1 → 2.0.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 (213) hide show
  1. package/README.md +94 -42
  2. package/dist/index.js +7 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/instructions.js +5 -5
  5. package/dist/instructions.js.map +1 -1
  6. package/dist/playbooks.d.ts.map +1 -1
  7. package/dist/playbooks.js +109 -92
  8. package/dist/playbooks.js.map +1 -1
  9. package/dist/prompts.js +7 -7
  10. package/dist/prompts.js.map +1 -1
  11. package/dist/tools/answer-agent-approval.d.ts +4 -0
  12. package/dist/tools/answer-agent-approval.d.ts.map +1 -0
  13. package/dist/tools/answer-agent-approval.js +354 -0
  14. package/dist/tools/answer-agent-approval.js.map +1 -0
  15. package/dist/tools/apply-agent-skills.d.ts.map +1 -1
  16. package/dist/tools/apply-agent-skills.js +81 -30
  17. package/dist/tools/apply-agent-skills.js.map +1 -1
  18. package/dist/tools/bind-agent-project.d.ts.map +1 -1
  19. package/dist/tools/bind-agent-project.js +29 -28
  20. package/dist/tools/bind-agent-project.js.map +1 -1
  21. package/dist/tools/cancel-agent-message.js +1 -1
  22. package/dist/tools/cancel-agent-message.js.map +1 -1
  23. package/dist/tools/check-model-access.d.ts.map +1 -1
  24. package/dist/tools/check-model-access.js +14 -11
  25. package/dist/tools/check-model-access.js.map +1 -1
  26. package/dist/tools/connect-agent-connector.d.ts +4 -0
  27. package/dist/tools/connect-agent-connector.d.ts.map +1 -0
  28. package/dist/tools/connect-agent-connector.js +634 -0
  29. package/dist/tools/connect-agent-connector.js.map +1 -0
  30. package/dist/tools/control-agent.d.ts.map +1 -1
  31. package/dist/tools/control-agent.js +30 -31
  32. package/dist/tools/control-agent.js.map +1 -1
  33. package/dist/tools/delete-agent.d.ts.map +1 -1
  34. package/dist/tools/delete-agent.js +12 -5
  35. package/dist/tools/delete-agent.js.map +1 -1
  36. package/dist/tools/deploy-agent.d.ts.map +1 -1
  37. package/dist/tools/deploy-agent.js +96 -44
  38. package/dist/tools/deploy-agent.js.map +1 -1
  39. package/dist/tools/disconnect-agent-connector.d.ts +4 -0
  40. package/dist/tools/disconnect-agent-connector.d.ts.map +1 -0
  41. package/dist/tools/disconnect-agent-connector.js +184 -0
  42. package/dist/tools/disconnect-agent-connector.js.map +1 -0
  43. package/dist/tools/get-account.d.ts.map +1 -1
  44. package/dist/tools/get-account.js +24 -8
  45. package/dist/tools/get-account.js.map +1 -1
  46. package/dist/tools/get-agent-activity.d.ts.map +1 -1
  47. package/dist/tools/get-agent-activity.js +285 -138
  48. package/dist/tools/get-agent-activity.js.map +1 -1
  49. package/dist/tools/get-agent-connector-permissions.d.ts +145 -0
  50. package/dist/tools/get-agent-connector-permissions.d.ts.map +1 -0
  51. package/dist/tools/get-agent-connector-permissions.js +194 -0
  52. package/dist/tools/get-agent-connector-permissions.js.map +1 -0
  53. package/dist/tools/get-agent-conversation.d.ts.map +1 -1
  54. package/dist/tools/get-agent-conversation.js +39 -10
  55. package/dist/tools/get-agent-conversation.js.map +1 -1
  56. package/dist/tools/get-agent-message.d.ts.map +1 -1
  57. package/dist/tools/get-agent-message.js +13 -5
  58. package/dist/tools/get-agent-message.js.map +1 -1
  59. package/dist/tools/get-agent-template.d.ts.map +1 -1
  60. package/dist/tools/get-agent-template.js +13 -15
  61. package/dist/tools/get-agent-template.js.map +1 -1
  62. package/dist/tools/get-my-agent.d.ts.map +1 -1
  63. package/dist/tools/get-my-agent.js +38 -5
  64. package/dist/tools/get-my-agent.js.map +1 -1
  65. package/dist/tools/get-task-price.d.ts.map +1 -1
  66. package/dist/tools/get-task-price.js +4 -4
  67. package/dist/tools/get-task-price.js.map +1 -1
  68. package/dist/tools/get-task.d.ts.map +1 -1
  69. package/dist/tools/get-task.js +4 -4
  70. package/dist/tools/get-task.js.map +1 -1
  71. package/dist/tools/index.d.ts +8 -3
  72. package/dist/tools/index.d.ts.map +1 -1
  73. package/dist/tools/index.js +17 -6
  74. package/dist/tools/index.js.map +1 -1
  75. package/dist/tools/kill-task.js +1 -1
  76. package/dist/tools/kill-task.js.map +1 -1
  77. package/dist/tools/list-agent-connectors.d.ts +4 -0
  78. package/dist/tools/list-agent-connectors.d.ts.map +1 -0
  79. package/dist/tools/list-agent-connectors.js +325 -0
  80. package/dist/tools/list-agent-connectors.js.map +1 -0
  81. package/dist/tools/list-agent-skills.d.ts.map +1 -1
  82. package/dist/tools/list-agent-skills.js +59 -40
  83. package/dist/tools/list-agent-skills.js.map +1 -1
  84. package/dist/tools/list-agent-templates.d.ts.map +1 -1
  85. package/dist/tools/list-agent-templates.js +7 -5
  86. package/dist/tools/list-agent-templates.js.map +1 -1
  87. package/dist/tools/list-my-agents.d.ts.map +1 -1
  88. package/dist/tools/list-my-agents.js +7 -3
  89. package/dist/tools/list-my-agents.js.map +1 -1
  90. package/dist/tools/list-projects.d.ts.map +1 -1
  91. package/dist/tools/list-projects.js +7 -4
  92. package/dist/tools/list-projects.js.map +1 -1
  93. package/dist/tools/list-studio-results.d.ts.map +1 -1
  94. package/dist/tools/list-studio-results.js +3 -2
  95. package/dist/tools/list-studio-results.js.map +1 -1
  96. package/dist/tools/list-tasks.d.ts.map +1 -1
  97. package/dist/tools/list-tasks.js +6 -3
  98. package/dist/tools/list-tasks.js.map +1 -1
  99. package/dist/tools/manage-agent-billing.d.ts.map +1 -1
  100. package/dist/tools/manage-agent-billing.js +216 -359
  101. package/dist/tools/manage-agent-billing.js.map +1 -1
  102. package/dist/tools/manage-agent-custom-skill.d.ts.map +1 -1
  103. package/dist/tools/manage-agent-custom-skill.js +77 -30
  104. package/dist/tools/manage-agent-custom-skill.js.map +1 -1
  105. package/dist/tools/manage-model-access.js +1 -1
  106. package/dist/tools/manage-model-access.js.map +1 -1
  107. package/dist/tools/manage-spend-limit.js +1 -1
  108. package/dist/tools/manage-spend-limit.js.map +1 -1
  109. package/dist/tools/run-model.d.ts.map +1 -1
  110. package/dist/tools/run-model.js +4 -4
  111. package/dist/tools/run-model.js.map +1 -1
  112. package/dist/tools/schemas.d.ts +11 -0
  113. package/dist/tools/schemas.d.ts.map +1 -1
  114. package/dist/tools/schemas.js +19 -1
  115. package/dist/tools/schemas.js.map +1 -1
  116. package/dist/tools/send-agent-message.d.ts.map +1 -1
  117. package/dist/tools/send-agent-message.js +45 -20
  118. package/dist/tools/send-agent-message.js.map +1 -1
  119. package/dist/tools/set-agent-connector-accounts.d.ts +4 -0
  120. package/dist/tools/set-agent-connector-accounts.d.ts.map +1 -0
  121. package/dist/tools/set-agent-connector-accounts.js +263 -0
  122. package/dist/tools/set-agent-connector-accounts.js.map +1 -0
  123. package/dist/tools/set-agent-connector-permissions.d.ts +4 -0
  124. package/dist/tools/set-agent-connector-permissions.d.ts.map +1 -0
  125. package/dist/tools/set-agent-connector-permissions.js +280 -0
  126. package/dist/tools/set-agent-connector-permissions.js.map +1 -0
  127. package/dist/tools/set-agent-credentials.d.ts.map +1 -1
  128. package/dist/tools/set-agent-credentials.js +52 -169
  129. package/dist/tools/set-agent-credentials.js.map +1 -1
  130. package/dist/tools/update-agent.d.ts.map +1 -1
  131. package/dist/tools/update-agent.js +39 -18
  132. package/dist/tools/update-agent.js.map +1 -1
  133. package/dist/tools/wait-for-task.d.ts.map +1 -1
  134. package/dist/tools/wait-for-task.js +4 -4
  135. package/dist/tools/wait-for-task.js.map +1 -1
  136. package/dist/tools/wait-for-workflow-run.d.ts.map +1 -1
  137. package/dist/tools/wait-for-workflow-run.js +6 -3
  138. package/dist/tools/wait-for-workflow-run.js.map +1 -1
  139. package/dist/utils/agent-approvals.d.ts +328 -0
  140. package/dist/utils/agent-approvals.d.ts.map +1 -0
  141. package/dist/utils/agent-approvals.js +620 -0
  142. package/dist/utils/agent-approvals.js.map +1 -0
  143. package/dist/utils/agent-catalog.d.ts +15 -25
  144. package/dist/utils/agent-catalog.d.ts.map +1 -1
  145. package/dist/utils/agent-catalog.js +27 -36
  146. package/dist/utils/agent-catalog.js.map +1 -1
  147. package/dist/utils/agent-config.d.ts +87 -292
  148. package/dist/utils/agent-config.d.ts.map +1 -1
  149. package/dist/utils/agent-config.js +150 -787
  150. package/dist/utils/agent-config.js.map +1 -1
  151. package/dist/utils/agent-connectors.d.ts +197 -0
  152. package/dist/utils/agent-connectors.d.ts.map +1 -0
  153. package/dist/utils/agent-connectors.js +415 -0
  154. package/dist/utils/agent-connectors.js.map +1 -0
  155. package/dist/utils/agent-message.d.ts +106 -4
  156. package/dist/utils/agent-message.d.ts.map +1 -1
  157. package/dist/utils/agent-message.js +84 -14
  158. package/dist/utils/agent-message.js.map +1 -1
  159. package/dist/utils/agent-setup.d.ts +19 -14
  160. package/dist/utils/agent-setup.d.ts.map +1 -1
  161. package/dist/utils/agent-setup.js +171 -106
  162. package/dist/utils/agent-setup.js.map +1 -1
  163. package/dist/utils/agent-targets.d.ts.map +1 -1
  164. package/dist/utils/agent-targets.js +40 -14
  165. package/dist/utils/agent-targets.js.map +1 -1
  166. package/dist/utils/agent-turns.d.ts +256 -7
  167. package/dist/utils/agent-turns.d.ts.map +1 -1
  168. package/dist/utils/agent-turns.js +260 -71
  169. package/dist/utils/agent-turns.js.map +1 -1
  170. package/dist/utils/connector-permissions.d.ts +184 -0
  171. package/dist/utils/connector-permissions.d.ts.map +1 -0
  172. package/dist/utils/connector-permissions.js +439 -0
  173. package/dist/utils/connector-permissions.js.map +1 -0
  174. package/dist/utils/controls.d.ts +6 -2
  175. package/dist/utils/controls.d.ts.map +1 -1
  176. package/dist/utils/controls.js +20 -9
  177. package/dist/utils/controls.js.map +1 -1
  178. package/dist/utils/format.d.ts +10 -0
  179. package/dist/utils/format.d.ts.map +1 -1
  180. package/dist/utils/format.js +42 -3
  181. package/dist/utils/format.js.map +1 -1
  182. package/dist/utils/quoted-text.d.ts +2 -0
  183. package/dist/utils/quoted-text.d.ts.map +1 -1
  184. package/dist/utils/quoted-text.js +5 -0
  185. package/dist/utils/quoted-text.js.map +1 -1
  186. package/dist/utils/structured.d.ts +3 -0
  187. package/dist/utils/structured.d.ts.map +1 -1
  188. package/dist/utils/structured.js +7 -2
  189. package/dist/utils/structured.js.map +1 -1
  190. package/dist/utils/studio-runs.d.ts.map +1 -1
  191. package/dist/utils/studio-runs.js +6 -4
  192. package/dist/utils/studio-runs.js.map +1 -1
  193. package/dist/utils/user-agent.d.ts +271 -100
  194. package/dist/utils/user-agent.d.ts.map +1 -1
  195. package/dist/utils/user-agent.js +434 -159
  196. package/dist/utils/user-agent.js.map +1 -1
  197. package/dist/utils/wiro-project.d.ts +25 -0
  198. package/dist/utils/wiro-project.d.ts.map +1 -1
  199. package/dist/utils/wiro-project.js +76 -2
  200. package/dist/utils/wiro-project.js.map +1 -1
  201. package/dist/utils/workspace.d.ts +3 -1
  202. package/dist/utils/workspace.d.ts.map +1 -1
  203. package/dist/utils/workspace.js +2 -1
  204. package/dist/utils/workspace.js.map +1 -1
  205. package/package.json +1 -1
  206. package/dist/tools/connect-agent-oauth.d.ts +0 -4
  207. package/dist/tools/connect-agent-oauth.d.ts.map +0 -1
  208. package/dist/tools/connect-agent-oauth.js +0 -778
  209. package/dist/tools/connect-agent-oauth.js.map +0 -1
  210. package/dist/tools/disconnect-agent-oauth.d.ts +0 -4
  211. package/dist/tools/disconnect-agent-oauth.d.ts.map +0 -1
  212. package/dist/tools/disconnect-agent-oauth.js +0 -138
  213. package/dist/tools/disconnect-agent-oauth.js.map +0 -1
@@ -1,13 +1,12 @@
1
1
  import crypto from 'node:crypto';
2
- import { DEFAULT_BASE_URL } from '../client.js';
3
- import { AGENT_NOT_FOUND_TEXT, ApiResultError, asString, hasErrorCode, isAgentNotFound, isPlainObject, requireApiSuccess, toNumber, truncate, unixToIso, } from './api.js';
4
- import { oneLine, quotedSpan } from './quoted-text.js';
5
- import { credentialKeysSetupWaitsFor, nameList, skillLabel, STARTER_TASK_KEY, toSkillGroups, WIRO_PROJECT_CREDENTIAL, wordsFromKey, } from './user-agent.js';
6
- // Helpers for configuring a deployed agent: its registry skills, credentials,
7
- // sign-in connections and custom skills. The pure functions mirror the server
2
+ import { AGENT_NOT_FOUND_TEXT, ApiResultError, asString, hasErrorCode, isPlainObject, requireApiSuccess, toNumber, truncate, unixToIso, } from './api.js';
3
+ import { centsToUsd, credentialKeysSetupWaitsFor, nameList, skillLabel, STARTER_TASK_KEY, toSkillGroups, WIRO_PROJECT_CREDENTIAL, wordsFromKey, } from './user-agent.js';
4
+ import { CONNECTOR_SLUG } from './agent-connectors.js';
5
+ // Helpers for configuring a deployed agent: its registry skills, its credentials
6
+ // (chat channels, Twilio Voice, settings and the Wiro project) and its custom
7
+ // skills. Outside services are connectors (agent-connectors.ts). The pure functions mirror the server
8
8
  // rules closely so a bad request is caught before anything is written.
9
9
  export const DEFAULT_CRON_INTERVAL = '0 10 * * 1';
10
- export const OAUTH_LINK_TTL_SECONDS = 900;
11
10
  const REGISTRY_TTL_MS = 5 * 60_000;
12
11
  function stringList(value) {
13
12
  return Array.isArray(value)
@@ -33,52 +32,54 @@ export const AGENT_STATUS_LABELS = {
33
32
  export function agentStatusLabel(status) {
34
33
  return status !== null && AGENT_STATUS_LABELS[status] ? AGENT_STATUS_LABELS[status] : 'unknown';
35
34
  }
36
- /** Configuration writes restart an agent only while it is starting or running. */
35
+ /** Whether the agent is starting or running: a configuration write acts on it at once only then. */
37
36
  export function isAgentRunning(status) {
38
37
  return status === 3 || status === 4;
39
38
  }
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
39
  /**
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.
40
+ * A change Wiro applied to the running agent with no restart, as its answer says (live: true, or restart "live"). It
41
+ * names no direction, so it also reads right for a change that takes something away.
48
42
  */
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
- }
43
+ export const LIVE_CHANGE_NOTE = 'The running agent has the change from its next message, with no restart.';
44
+ /** A live change that gives the running agent something it uses: a connector connected, a custom skill turned on. */
45
+ export const LIVE_ADDED_NOTE = 'The running agent uses it from its next message, with no restart.';
46
+ /** A live change that takes something away: a connector disconnected, a custom skill turned off or deleted. */
47
+ export const LIVE_REMOVED_NOTE = 'The running agent stops using it from its next message, with no restart.';
61
48
  /**
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.
49
+ * The live sentence for a change to one custom skill or scheduled task, from whether its switch is on before and after
50
+ * the change (a new entry is off before it, a deleted one off after it). A scheduled task runs on its own time, not
51
+ * at the agent's next message.
64
52
  */
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
- };
53
+ export function liveEntryNote(kind, onBefore, onAfter) {
54
+ if (kind === 'scheduled_task') {
55
+ if (onAfter)
56
+ return 'The running agent has the change with no restart; it applies from the task\'s next run.';
57
+ return onBefore
58
+ ? 'The running agent has the change with no restart; the task stops running.'
59
+ : 'The running agent has the change with no restart.';
60
+ }
61
+ if (onAfter)
62
+ return LIVE_ADDED_NOTE;
63
+ return onBefore ? LIVE_REMOVED_NOTE : LIVE_CHANGE_NOTE;
71
64
  }
72
- /** The agent's page in the Wiro dashboard, in the form the dashboard itself uses as an OAuth return address. */
73
- export function dashboardAgentUrl(agentGuid, apiBase = DEFAULT_BASE_URL) {
74
- const guid = encodeURIComponent(agentGuid);
75
- return `${wiroAddresses(apiBase).dashboardAgents}${guid}?id=${guid}`;
65
+ /**
66
+ * Before a change that can reach a running agent with no restart. Wiro decides when it applies it: most go live, the
67
+ * few that need a restart (or a live change that cannot finish) restart the agent.
68
+ */
69
+ export const LIVE_OR_RESTART_NOTE = 'A running agent gets most changes without a restart; a few restart it, which takes a minute or two.';
70
+ /** Whether Wiro's answer says a running agent got the change with no restart. */
71
+ export function answeredLive(body) {
72
+ return body.live === true || body.restart === 'live';
76
73
  }
74
+ /**
75
+ * What a change does to the agent, by its status before the change. A change Wiro's answer says the running agent
76
+ * got with no restart takes a live sentence instead.
77
+ */
77
78
  export function restartNote(status, what = 'change') {
78
79
  switch (status) {
79
80
  case 3:
80
81
  case 4:
81
- return `The agent restarts to load the ${what}, which takes about a minute. Follow it with get_my_agent.`;
82
+ return `The agent restarts to load the ${what}, which takes a minute or two. Follow it with get_my_agent.`;
82
83
  case 1:
83
84
  return `The agent is already stopping or restarting; it loads the ${what} when it starts again.`;
84
85
  case 2:
@@ -96,20 +97,14 @@ export function restartNote(status, what = 'change') {
96
97
  export function keyList(keys) {
97
98
  return keys.length > 1 ? `${keys.slice(0, -1).join(', ')} and ${keys[keys.length - 1]}` : keys.join('');
98
99
  }
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) {
100
+ function afterWriteNote(status) {
104
101
  switch (status) {
105
102
  case 1:
106
- return 'The agent restarts to load the new values, which takes about a minute.';
103
+ return 'The agent restarts to load the new values, which takes a minute or two.';
107
104
  case 2:
108
105
  case 3:
109
106
  return 'The agent is starting and loads the new values.';
110
107
  case 4:
111
- if (awaitsConnection)
112
- return AWAITS_CONNECTION_NOTE;
113
108
  // A save that changes a value sets a running agent stopping before Wiro answers.
114
109
  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.';
115
110
  case 6:
@@ -122,15 +117,14 @@ function afterWriteNote(status, awaitsConnection) {
122
117
  return `The agent is ${agentStatusLabel(status)}; the values are used when it starts.`;
123
118
  }
124
119
  }
125
- /** What the setup still waits for and the tool that gives each one: a Wiro project, a sign-in or saved fields. */
120
+ /** What the setup still waits for and the tool that gives each one: a Wiro project or saved fields. */
126
121
  export function setupStillMissingNote(missing) {
127
122
  if (missing.length === 0)
128
123
  return null;
129
124
  const titles = (items) => items.map(item => item.title);
130
125
  const isProject = (item) => item.key === WIRO_PROJECT_CREDENTIAL;
131
126
  const steps = [
132
- { verb: 'Set', names: titles(missing.filter(item => !item.oauth && !isProject(item))), tool: 'set_agent_credentials' },
133
- { verb: 'Connect', names: titles(missing.filter(item => item.oauth && !isProject(item))), tool: 'connect_agent_oauth' },
127
+ { verb: 'Set', names: titles(missing.filter(item => !isProject(item))), tool: 'set_agent_credentials' },
134
128
  { verb: 'Connect', names: titles(missing.filter(isProject)), tool: 'bind_agent_project' },
135
129
  ].filter(step => step.names.length > 0);
136
130
  const first = steps[0];
@@ -139,12 +133,9 @@ export function setupStillMissingNote(missing) {
139
133
  : steps.map((step, index) => `${index === 0 ? step.verb : step.verb.toLowerCase()} ${keyList(step.names)} with ${step.tool}`).join(', ');
140
134
  return `Setup is not finished: still missing ${keyList(titles(missing))}. ${how}, then check with get_my_agent.`;
141
135
  }
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);
136
+ /** When the agent loads the values, and the credentials its setup still waits for, at any status. */
137
+ export function afterWriteNotes(status, missing) {
138
+ const note = afterWriteNote(status);
148
139
  const setup = setupStillMissingNote(missing);
149
140
  if (!setup)
150
141
  return [note];
@@ -209,6 +200,7 @@ export function parseSkillRegistry(body) {
209
200
  ...(asString(raw.replacement) ? { replacement: asString(raw.replacement) } : {}),
210
201
  requiresCredentials: raw.requires_credentials === true,
211
202
  credentialKeys: [...(primary ? [primary] : []), ...stringList(raw.additional_credential_keys)],
203
+ suggestedConnectors: [...new Set(stringList(raw.suggested_connectors).filter(slug => CONNECTOR_SLUG.test(slug)))],
212
204
  });
213
205
  }
214
206
  const channels = new Map();
@@ -295,7 +287,7 @@ export function planSkillChanges(input, registry, addDependencies) {
295
287
  const skill = registry.skills.get(name);
296
288
  if (!skill) {
297
289
  const suggestions = suggestSkills(name, registry);
298
- errors.add(`Unknown skill "${name}".${suggestions.length ? ` Did you mean ${suggestions.map(label).join(', ')}?` : ''} Use list_agent_skills for the full list.`);
290
+ errors.add(`Unknown skill "${name}".${suggestions.length ? ` Did you mean ${suggestions.map(label).join(', ')}?` : ''} Use list_agent_skills for the full list. An outside service is a Connector, not a skill: list_agent_connectors lists them and connect_agent_connector connects one.`);
299
291
  continue;
300
292
  }
301
293
  if (enabled && skill.deprecated) {
@@ -324,7 +316,7 @@ export function planSkillChanges(input, registry, addDependencies) {
324
316
  }
325
317
  return { requested, addedDependencies: added, errors: [...errors] };
326
318
  }
327
- /** Only real changes are sent, since a skill change restarts a running agent. */
319
+ /** Only real changes are sent, since a skill change reaches a running agent, live or with a restart. */
328
320
  export function diffSkills(requested, enabledNow) {
329
321
  const current = new Set(enabledNow);
330
322
  const diff = { changes: {}, enable: [], disable: [], alreadySet: [] };
@@ -393,14 +385,11 @@ export function credentialsUsedBySkills(skills, registry) {
393
385
  return used;
394
386
  }
395
387
  /**
396
- * Why connect_agent_oauth connect refuses a service on this agent, or null when
397
- * it connects: one of the agent's active skills uses it, or one of its custom
398
- * skills or scheduled tasks requires it (a skill's scheduled task only when it
399
- * can use that credential now). Wiro keeps such an entry off until the
400
- * credential is connected, and connecting turns it on, so the entry counts
401
- * whatever its enabled says. A template agent's setup also waits for the
402
- * credentials its template requires, whichever skills are on, so those stay
403
- * connectable.
388
+ * Null when the agent uses this credential: one of its active skills reads it, or
389
+ * one of its custom skills or scheduled tasks requires it (a skill's scheduled
390
+ * task only when it can use that credential now). A template agent's setup also
391
+ * waits for the credentials its template requires, whichever skills are on. Else
392
+ * the skills that would use it, to turn on first.
404
393
  */
405
394
  export function unusedCredential(row, credential, registry) {
406
395
  const used = credentialsUsedBySkills(enabledSkillNames(row), registry);
@@ -412,41 +401,11 @@ export function unusedCredential(row, credential, registry) {
412
401
  if (used.has(credential) || (!isCustomBuild(row) && credentialGroup(row, credential)?.optional === false))
413
402
  return null;
414
403
  return {
415
- services: [...used].flatMap(key => {
416
- const schema = credentialGroup(row, key)?._schema;
417
- return isPlainObject(schema) && isPlainObject(schema.oauth_provider)
418
- ? [`${asString(schema.title) ?? wordsFromKey(key)} (\`${key}\`)`]
419
- : [];
420
- }),
421
404
  skills: [...registry.skills.values()]
422
405
  .filter(skill => !skill.deprecated && skill.requiresCredentials && skill.credentialKeys[0] === credential)
423
406
  .map(skill => skillLabel(skill.name, registryTitles(registry))),
424
407
  };
425
408
  }
426
- export function turnOnSkillText(title, credential, skills) {
427
- return skills.length > 0
428
- ? `To use ${title}, first turn on ${skills.join(' or ')} with apply_agent_skills; list_agent_skills with name "${credential}" shows how it connects.`
429
- : '';
430
- }
431
- /**
432
- * The same rule for the answers that offer connect (status, and describing or
433
- * saving a credential), as a note to show instead of that offer. Null when the
434
- * service connects, and when the skills cannot be read: connect checks again.
435
- */
436
- export async function unusedCredentialNote(client, row, credential, title, signal) {
437
- try {
438
- const unused = unusedCredential(row, credential, await loadSkillRegistry(client, signal));
439
- if (!unused)
440
- return null;
441
- return [
442
- `${title} is not used by any of this agent's active skills, custom skills or scheduled tasks, so connect_agent_oauth refuses it for now.`,
443
- turnOnSkillText(title, credential, unused.skills),
444
- ].filter(Boolean).join(' ');
445
- }
446
- catch {
447
- return null;
448
- }
449
- }
450
409
  // A key minted by this package: mcp-<random>-<change digest>. Keys from earlier versions also carry a price fingerprint at the end.
451
410
  const IDEMPOTENCY_KEY_RE = /^mcp-[0-9a-f]{16}-([0-9a-f]{10})(?:-[0-9a-f]{8})?$/;
452
411
  /** Fingerprint of one logical skill change, independent of the agent's current state. */
@@ -476,6 +435,11 @@ export function idempotencyKeyMismatch(key, digest) {
476
435
  return parsed !== null && parsed.digest !== digest;
477
436
  }
478
437
  const DAY_SECONDS = 86400;
438
+ /** An amount Wiro answers in hundredths of a dollar, in USD; null stays null. */
439
+ function hundredthsToUsd(value) {
440
+ const cents = toNumber(value);
441
+ return cents === null ? null : centsToUsd(cents);
442
+ }
479
443
  /** The plan change of a pricing answer, or null when the agent has no active plan or Wiro sent none. */
480
444
  export function readPlanChange(value) {
481
445
  if (!isPlainObject(value))
@@ -484,12 +448,12 @@ export function readPlanChange(value) {
484
448
  wallet: asString(value.provider) === 'prepaid',
485
449
  periodEnd: toNumber(value.periodEnd),
486
450
  secondsLeft: toNumber(value.secondsLeft),
487
- creditsNow: toNumber(value.creditsNow),
488
- creditsThisPeriod: toNumber(value.creditsThisPeriod),
489
- creditsFromRenewal: toNumber(value.creditsFromRenewal),
451
+ // Wiro answers the included usage in hundredths of a dollar.
452
+ includedNowUsd: hundredthsToUsd(value.creditsNow),
453
+ includedThisPeriodUsd: hundredthsToUsd(value.creditsThisPeriod),
454
+ includedFromRenewalUsd: hundredthsToUsd(value.creditsFromRenewal),
490
455
  chargeNowUsd: toNumber(value.chargeNowUsd),
491
- creditNowUsd: toNumber(value.creditNowUsd),
492
- usedCreditsUsd: toNumber(value.usedCreditsUsd),
456
+ refusal: asString(value.refusal)?.trim() || null,
493
457
  };
494
458
  }
495
459
  /** Whether a rise now pays the one-day minimum: under a day is left of the period. */
@@ -587,41 +551,25 @@ export function describeSkillsApplyError(error, titles) {
587
551
  }
588
552
  return { ...base, guidance: workspaceHint(message) ?? '' };
589
553
  }
590
- /**
591
- * One refusal covers an agent that does not exist and an agent this project may
592
- * not connect, and the fix for each is different. The agent's own read tells
593
- * them apart.
594
- */
595
- export async function connectionRefusalText(client, agentGuid, message, done, signal) {
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: `
597
- + 'connect this server with such a project, by its API key or a browser sign-in.';
598
- try {
599
- await readUserAgent(client, agentGuid, signal);
600
- }
601
- catch (error) {
602
- if (isAgentNotFound(error))
603
- return AGENT_NOT_FOUND_TEXT;
604
- return `${message}\n\nCheck the guid with list_my_agents. If the agent is listed, integrations ${rule}`;
605
- }
606
- return `${message}\n\nIntegrations ${rule}`;
607
- }
608
- /** Wiro's answer when it could not clear a saved connection. Nothing says the connection is gone, and a repeat is safe. */
609
- export const CONNECTION_NOT_CLEARED = 'The saved connection could not be cleared. Please try again.';
610
554
  export const WORKSPACE_HINT = 'Connect with a project in the workspace (personal or team) that owns this agent, by its API key or a browser sign-in.';
611
555
  /** The API names a dashboard concept ("team context"); here the workspace is the connected project's. */
612
556
  export function workspaceHint(message) {
613
557
  return /switch to the (team|personal)|different team|personal workspace/i.test(message) ? WORKSPACE_HINT : undefined;
614
558
  }
615
- // A field's setup help is shown whole: its last steps, such as sharing a
616
- // calendar with the service account, are part of the setup.
559
+ // A field's setup help is shown whole: its last steps are part of the setup.
617
560
  export const FIELD_HELP_MAX = 4_000;
618
561
  // The Wiro project field. On the dashboard it is a project picker, and the help
619
- // it comes with describes that picker, so this line is shown instead.
562
+ // it comes with describes that picker, so this line is shown instead. The
563
+ // credential is the project the agent's video and voice skills run models
564
+ // with. The wiro connector, the agent's own model tools, always runs with the
565
+ // same project: connecting it binds its project to this credential.
620
566
  export const WIRO_PROJECT_NOTE = 'Connect a Wiro project with bind_agent_project: it takes the project of this connection or '
621
567
  + 'one from list_projects, and no key passes through this chat. The user can also pick the project on the agent\'s page in '
622
568
  + 'the Wiro dashboard. Saving a project API key with set_agent_credentials stays possible when the user gives one for this, '
623
- + 'and Wiro adds the project\'s secret by itself. Model runs the agent starts are billed to the wallet of the workspace '
624
- + 'that owns the project.';
569
+ + 'and Wiro adds the project\'s secret by itself. The agent\'s video and voice skills run models with this project, '
570
+ + 'billed to the wallet of the workspace that owns it. The agent\'s own model tools (wiro__*) come from the wiro '
571
+ + 'connector, which always runs with this same project: connecting it with connect_agent_connector (project_id, or '
572
+ + 'the project of this connection) binds that project here too, and its model runs count as the agent\'s own.';
625
573
  export function isWiroProjectField(raw) {
626
574
  return /^(custom:)?wiro-project-picker$/.test(asString(raw.type) ?? '');
627
575
  }
@@ -671,11 +619,7 @@ export function parseCredentialField(raw) {
671
619
  type: asString(raw.type) ?? 'text',
672
620
  required: raw.required === true,
673
621
  encrypted: raw.encrypted === true,
674
- oauthManaged: raw.oauth_managed === true,
675
- autoFilled: raw.auto_filled_by_oauth === true,
676
- serverManaged: raw.server_managed === true,
677
622
  platformManaged: raw.platform_managed === true,
678
- onlyInModes: Array.isArray(raw.only_in_modes) ? stringList(raw.only_in_modes) : null,
679
623
  ...(asString(raw.pattern) ? { pattern: asString(raw.pattern) } : {}),
680
624
  ...(toNumber(raw.minlength) !== null ? { minLength: toNumber(raw.minlength) } : {}),
681
625
  ...(toNumber(raw.maxlength) !== null ? { maxLength: toNumber(raw.maxlength) } : {}),
@@ -688,95 +632,24 @@ export function parseCredentialField(raw) {
688
632
  ...(asString(raw.placeholder) ? { placeholder: asString(raw.placeholder) } : {}),
689
633
  };
690
634
  }
691
- function parsePicker(raw) {
692
- if (!isPlainObject(raw) || raw.enabled === false)
693
- return null;
694
- const valueField = asString(raw.item_value_field);
695
- if (!valueField)
696
- return null;
697
- const urlItemFields = {};
698
- if (isPlainObject(raw.url_item_fields)) {
699
- for (const [saved, source] of Object.entries(raw.url_item_fields)) {
700
- if (asString(source))
701
- urlItemFields[saved] = asString(source);
702
- }
703
- }
704
- const nextRaw = isPlainObject(raw.next) && raw.next.enabled !== false ? raw.next : null;
705
- const maxParents = nextRaw ? toNumber(nextRaw.max_parents) : null;
706
- const next = nextRaw && asString(nextRaw.key) && asString(nextRaw.item_value_field)
707
- ? {
708
- key: asString(nextRaw.key),
709
- label: asString(nextRaw.modal_title)?.replace(/^select\s+/i, '') ?? asString(nextRaw.key),
710
- optional: nextRaw.optional === true,
711
- parentValueField: asString(nextRaw.parent_value_field) ?? valueField,
712
- parentLabelField: asString(nextRaw.parent_label_field) ?? asString(raw.item_label_field) ?? valueField,
713
- itemValueField: asString(nextRaw.item_value_field),
714
- itemLabelField: asString(nextRaw.item_label_field) ?? asString(nextRaw.item_value_field),
715
- persistField: asString(nextRaw.persist_field) ?? '',
716
- ...(maxParents !== null && Number.isInteger(maxParents) && maxParents > 0 ? { maxParents } : {}),
717
- }
718
- : null;
719
- return {
720
- multiSelect: raw.multi_select === true,
721
- valueField,
722
- ...(asString(raw.item_label_field) ? { labelField: asString(raw.item_label_field) } : {}),
723
- fieldsToSave: stringList(raw.item_fields_to_save).length > 0 ? stringList(raw.item_fields_to_save) : [valueField],
724
- urlItemFields,
725
- pendingCache: isPlainObject(raw.pending_cache),
726
- next,
727
- };
728
- }
729
635
  export function parseCredentialMeta(raw) {
730
636
  const key = asString(raw.key) ?? '';
731
637
  const fields = (Array.isArray(raw.credential_schema) ? raw.credential_schema : [])
732
638
  .filter(isPlainObject)
733
639
  .map(parseCredentialField)
734
640
  .filter(field => field.key);
735
- const provider = isPlainObject(raw.oauth_provider) ? raw.oauth_provider : null;
736
- let oauth = null;
737
- if (provider) {
738
- const flow = isPlainObject(provider.oauth_flow) ? provider.oauth_flow : {};
739
- const probe = isPlainObject(provider.direct_probe) ? provider.direct_probe : null;
740
- const tokenField = probe ? asString(probe.token_field) : undefined;
741
- oauth = {
742
- ...(asString(flow.callback_path) ? { callbackPath: asString(flow.callback_path) } : {}),
743
- stateFields: stringList(flow.state_fields),
744
- connectRequirements: (Array.isArray(flow.connect_requirements) ? flow.connect_requirements : [])
745
- .filter(isPlainObject)
746
- .map(requirement => asString(requirement.message) ?? '')
747
- .filter(Boolean),
748
- directProbe: probe
749
- ? {
750
- mode: asString(probe.mode) ?? 'api_key',
751
- ...(asString(probe.mode_label) ? { label: asString(probe.mode_label) } : {}),
752
- requiredFields: stringList(probe.required_fields).length > 0
753
- ? stringList(probe.required_fields)
754
- : (tokenField ? [tokenField] : []),
755
- }
756
- : null,
757
- picker: parsePicker(provider.account_picker),
758
- };
759
- }
760
641
  const channel = isPlainObject(raw.channel)
761
642
  ? { id: asString(raw.channel.id) ?? key, requiredFields: stringList(raw.channel.required_fields) }
762
643
  : null;
763
644
  return {
764
645
  key,
765
646
  title: asString(raw.title) ?? key,
766
- connectionModes: stringList(raw.connection_modes),
767
- ...(asString(raw.default_connection_mode) ? { defaultConnectionMode: asString(raw.default_connection_mode) } : {}),
768
- wiroPending: raw.wiro_connect_pending === true,
769
647
  fields,
770
648
  channel,
771
- oauth,
772
649
  platformOnly: raw.credential_mode === 'rule_only'
773
- || (!provider && fields.length > 0 && fields.every(field => field.platformManaged)),
650
+ || (fields.length > 0 && fields.every(field => field.platformManaged)),
774
651
  };
775
652
  }
776
- /** The modes a connection can use now: wiro is left out while the registry marks it pending. */
777
- export function usableConnectionModes(meta) {
778
- return meta.connectionModes.filter(mode => mode !== 'wiro' || !meta.wiroPending);
779
- }
780
653
  /** Returns null when the registry has no credential with that key. */
781
654
  export async function loadCredentialMeta(client, key, signal) {
782
655
  try {
@@ -795,12 +668,7 @@ export async function loadCredentialMeta(client, key, signal) {
795
668
  }
796
669
  }
797
670
  const OBJECT_LIST_TYPES = new Set([
798
- 'custom:apps-list-ios',
799
- 'custom:apps-list-android',
800
- 'custom:apps-list-adjust',
801
671
  'custom:urls-list',
802
- 'custom:firebase-accounts-list',
803
- 'custom:drive-folder-picker',
804
672
  ]);
805
673
  /** Mirrors how the API stores a field: lists of rows, lists of strings, files or one value. */
806
674
  export function credentialFieldShape(field) {
@@ -818,8 +686,6 @@ export function credentialFieldShape(field) {
818
686
  }
819
687
  if (type === 'fileinput')
820
688
  return 'file';
821
- if (type === 'fileinput-base64')
822
- return 'base64-file';
823
689
  if (type === 'boolean')
824
690
  return 'boolean';
825
691
  if (type === 'number')
@@ -828,55 +694,9 @@ export function credentialFieldShape(field) {
828
694
  return 'select';
829
695
  return 'text';
830
696
  }
831
- /** Fields the connection flow or Wiro fills; customers cannot write them. */
697
+ /** Fields Wiro fills; customers cannot write them. */
832
698
  export function isWritableField(field) {
833
- return !field.autoFilled && !field.serverManaged && !field.platformManaged && field.type !== 'computed';
834
- }
835
- // Token state the connection flow owns.
836
- const CONNECTION_STATE_FIELDS = new Set([
837
- 'accesstoken',
838
- 'refreshtoken',
839
- 'connectedat',
840
- 'tokenexpiresat',
841
- 'refreshtokenexpiresat',
842
- ]);
843
- /**
844
- * Base64 file fields hold the file's bytes as base64. Callers often have the
845
- * file's text instead (a service account JSON, a .p8 key), so anything that is
846
- * not already base64 is encoded here.
847
- */
848
- export function normalizeBase64FileValue(value) {
849
- const dataUrl = /^data:[^,]*;base64,(.*)$/s.exec(value.trim());
850
- if (dataUrl)
851
- return (dataUrl[1] ?? '').replace(/\s+/g, '');
852
- const compact = value.replace(/\s+/g, '');
853
- if (compact && compact.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(compact))
854
- return compact;
855
- return Buffer.from(value, 'utf8').toString('base64');
856
- }
857
- function isJsonObjectText(text) {
858
- try {
859
- return isPlainObject(JSON.parse(text));
860
- }
861
- catch {
862
- return false;
863
- }
864
- }
865
- /** A key file field's value as Wiro stores it, or why it is refused. The value itself is never repeated. */
866
- function keyFileValue(field, value, label) {
867
- if (typeof value !== 'string')
868
- return { error: `${label} takes the file's content as text or base64.` };
869
- // Key files take the file's text; refuse a link before anything is saved.
870
- if (/^\s*https?:\/\//i.test(value)) {
871
- return { error: `${label} takes the file's content as text or base64, not a link. The user can paste the file's text or upload the file on the agent's page in the Wiro dashboard.` };
872
- }
873
- const stored = normalizeBase64FileValue(value);
874
- // A JSON key, such as a service account file, must hold a JSON object, so a
875
- // path, a share link or an id is refused before anything is saved.
876
- if (field.fileTypes?.includes('application/json') && !isJsonObjectText(Buffer.from(stored, 'base64').toString('utf8'))) {
877
- return { error: `${label} takes the text of the JSON key file. This value is not JSON. The user can paste the file's text or upload the file on the agent's page in the Wiro dashboard.` };
878
- }
879
- return { value: stored };
699
+ return !field.platformManaged && field.type !== 'computed';
880
700
  }
881
701
  function isEmptyValue(value) {
882
702
  if (value === null || value === undefined)
@@ -903,8 +723,11 @@ export function holdsSecretMask(value) {
903
723
  }
904
724
  /** What a value that holds the mask holds, for the sentence that refuses it. */
905
725
  export const SECRET_MASK_TEXT = 'the dots Wiro shows in place of a saved secret, not the secret itself';
906
- // Short values (select options, flags) are not secrets and would garble messages.
907
- function collectStrings(value, into) {
726
+ /**
727
+ * Every string of 8 or more characters in a value, at any depth of its lists and objects, for the redaction of
728
+ * error texts. Short values (select options, flags) are not secrets and would garble messages.
729
+ */
730
+ export function collectStrings(value, into) {
908
731
  if (typeof value === 'string') {
909
732
  if (value.trim().length >= 8)
910
733
  into.push(value.trim());
@@ -992,8 +815,8 @@ function isListField(field) {
992
815
  /**
993
816
  * The rows of a list of objects, checked the way Wiro checks them: only the
994
817
  * keys the item schema declares, each value by its own rules, and a list inside
995
- * a row (such as the apps of one Firebase account) by its own shape. Errors
996
- * name the row the way Wiro does: "App ID in Apps #2 in Firebase Accounts #1".
818
+ * a row (such as the channels of one Discord server) by its own shape. Errors
819
+ * name the row the way Wiro does: "Server ID in Allowed Discord Servers #2".
997
820
  */
998
821
  function rowsValue(field, value, rowLabel) {
999
822
  const allowed = new Set(field.itemSchema.map(item => item.key));
@@ -1027,9 +850,6 @@ function rowFieldValue(field, value, label) {
1027
850
  if (!isFilledValue(value))
1028
851
  return field.required ? { error: `${label} is required.` } : { value };
1029
852
  const shape = credentialFieldShape(field);
1030
- // Key files inside a row, such as each Firebase account's service account JSON, are stored like top-level ones.
1031
- if (shape === 'base64-file')
1032
- return keyFileValue(field, value, label);
1033
853
  if (typeof value === 'object')
1034
854
  return { error: `${label} takes a single text value.` };
1035
855
  const text = String(value);
@@ -1040,7 +860,7 @@ function rowFieldValue(field, value, label) {
1040
860
  return problem ? { error: problem } : { value };
1041
861
  }
1042
862
  /**
1043
- * A list inside one entry of a list, such as the apps of one Firebase account,
863
+ * A list inside one entry of a list, such as the channels of one Discord server,
1044
864
  * in a whole write of the outer list or on its own with parent_field: rows
1045
865
  * checked against its item schema, or text items.
1046
866
  */
@@ -1060,11 +880,17 @@ function nestedListValue(field, value, entryLabel) {
1060
880
  ? { error: `${label} is required.` }
1061
881
  : checked;
1062
882
  }
883
+ /** What an unknown credential key gets: the credentials there are, and where an outside service goes. */
884
+ export const UNKNOWN_CREDENTIAL_HINT = 'Credentials are chat channels (such as "telegram"), Twilio Voice, settings and the Wiro '
885
+ + 'project; get_my_agent lists the agent\'s. An outside service is a Connector: list_agent_connectors lists them and '
886
+ + 'connect_agent_connector connects one.';
1063
887
  /**
1064
888
  * Checks every requested field against the credential registry and builds the
1065
889
  * API payload. Nothing is written when any field is refused.
1066
890
  */
1067
- export function prepareCredentialWrite(inputs, metas) {
891
+ export function prepareCredentialWrite(inputs, metas,
892
+ /** Unknown keys that name a connector, with its title: they get the connector tools' names. */
893
+ connectors = new Map()) {
1068
894
  const prepared = { apiFields: [], files: [], errors: [], secrets: [] };
1069
895
  const reportedUnknown = new Set();
1070
896
  for (const input of inputs) {
@@ -1074,7 +900,10 @@ export function prepareCredentialWrite(inputs, metas) {
1074
900
  const meta = metas.get(credential) ?? null;
1075
901
  if (!meta) {
1076
902
  if (!reportedUnknown.has(credential)) {
1077
- prepared.errors.push(`Unknown credential "${credential}". The credential keys a skill uses are listed by list_agent_skills and get_my_agent.`);
903
+ const connector = connectors.get(credential);
904
+ prepared.errors.push(connector
905
+ ? `${connector} is a Connector, not a credential: connect it with connect_agent_connector (list_agent_connectors with name "${credential}" shows what it needs).`
906
+ : `Unknown credential "${credential}". ${UNKNOWN_CREDENTIAL_HINT}`);
1078
907
  reportedUnknown.add(credential);
1079
908
  }
1080
909
  continue;
@@ -1091,27 +920,10 @@ export function prepareCredentialWrite(inputs, metas) {
1091
920
  prepared.errors.push(`${meta.title}: "${fieldName}" is a reserved name.`);
1092
921
  continue;
1093
922
  }
1094
- if (CONNECTION_STATE_FIELDS.has(fieldName)) {
1095
- prepared.errors.push(`${meta.title}: "${fieldName}" is filled by the connection itself. Use connect_agent_oauth.`);
1096
- continue;
1097
- }
1098
923
  if (holdsSecretMask(input.value)) {
1099
924
  prepared.errors.push(`${meta.title}: "${fieldName}" holds ${SECRET_MASK_TEXT}. Leave it out to keep the saved value, or send the new value.`);
1100
925
  continue;
1101
926
  }
1102
- if (fieldName === 'authmethod') {
1103
- const usable = usableConnectionModes(meta);
1104
- if (input.parent_field || usable.length === 0) {
1105
- prepared.errors.push(`${meta.title} has no connection modes, so "authmethod" does not apply.`);
1106
- }
1107
- else if (typeof input.value !== 'string' || !usable.includes(input.value)) {
1108
- prepared.errors.push(`${meta.title}: authmethod must be one of ${usable.join(', ')}.`);
1109
- }
1110
- else {
1111
- prepared.apiFields.push({ credentialkey: credential, fieldname: 'authmethod', fieldvalue: input.value });
1112
- }
1113
- continue;
1114
- }
1115
927
  if (input.parent_field) {
1116
928
  const root = input.parent_field.split(/[.[\]]/)[0]?.trim() ?? '';
1117
929
  const parent = meta.fields.find(field => field.key === root);
@@ -1127,7 +939,7 @@ export function prepareCredentialWrite(inputs, metas) {
1127
939
  continue;
1128
940
  }
1129
941
  if (!isWritableField(parent)) {
1130
- prepared.errors.push(`${parent.label} is filled by the connection or by Wiro and cannot be set.`);
942
+ prepared.errors.push(`${parent.label} is filled by Wiro and cannot be set.`);
1131
943
  continue;
1132
944
  }
1133
945
  const item = parent.itemSchema.find(candidate => candidate.key === fieldName);
@@ -1173,7 +985,7 @@ export function prepareCredentialWrite(inputs, metas) {
1173
985
  continue;
1174
986
  }
1175
987
  if (!isWritableField(field)) {
1176
- prepared.errors.push(`${field.label} is filled when the account is connected with connect_agent_oauth and cannot be set directly.`);
988
+ prepared.errors.push(`${field.label} is filled by Wiro and cannot be set directly.`);
1177
989
  continue;
1178
990
  }
1179
991
  const shape = credentialFieldShape(field);
@@ -1205,15 +1017,6 @@ export function prepareCredentialWrite(inputs, metas) {
1205
1017
  });
1206
1018
  continue;
1207
1019
  }
1208
- if (shape === 'base64-file') {
1209
- const checked = keyFileValue(field, input.value, field.label);
1210
- if (checked.error) {
1211
- prepared.errors.push(checked.error);
1212
- continue;
1213
- }
1214
- prepared.apiFields.push({ credentialkey: credential, fieldname: fieldName, fieldvalue: checked.value });
1215
- continue;
1216
- }
1217
1020
  const checked = shape === 'string-array' || shape === 'object-array'
1218
1021
  ? listValue(field, input.value, field.label)
1219
1022
  : scalarValue(field, input.value, field.label);
@@ -1316,16 +1119,12 @@ export function credentialGroup(row, key) {
1316
1119
  const group = groups ? groups[key] : undefined;
1317
1120
  return isPlainObject(group) ? group : null;
1318
1121
  }
1319
- /**
1320
- * Whether the agent can use a credential now. An OAuth credential is ready only once connected: a saved shop
1321
- * domain or own-app key alone does not let the agent sign in.
1322
- */
1122
+ /** Whether the agent can use a credential now: it is connected, or every required field holds a value. */
1323
1123
  export function credentialReady(row, key) {
1324
1124
  const group = credentialGroup(row, key);
1325
1125
  if (!group)
1326
1126
  return false;
1327
- const oauth = isPlainObject(group._schema) && isPlainObject(group._schema.oauth_provider);
1328
- return group._connected === true || (!oauth && group._filled === true);
1127
+ return group._connected === true || group._filled === true;
1329
1128
  }
1330
1129
  export function credentialStatus(row, key, meta) {
1331
1130
  const group = credentialGroup(row, key);
@@ -1333,9 +1132,8 @@ export function credentialStatus(row, key, meta) {
1333
1132
  return null;
1334
1133
  const schema = isPlainObject(group._schema) ? group._schema : {};
1335
1134
  const connected = group._connected === true;
1336
- // A sign-in credential's required fields depend on its mode; connected is the signal there. Filled says every
1337
- // required field holds a value, a template's own value that is not shown included.
1338
- const missingFields = connected || !meta || meta.oauth || group._filled === true
1135
+ // Filled says every required field holds a value, a template's own value that is not shown included.
1136
+ const missingFields = connected || !meta || group._filled === true
1339
1137
  ? []
1340
1138
  : meta.fields
1341
1139
  .filter(field => field.required && isWritableField(field) && !isCredentialFieldFilled(field, group[field.key]))
@@ -1370,434 +1168,6 @@ export function channelStatuses(row) {
1370
1168
  };
1371
1169
  });
1372
1170
  }
1373
- // ---------------------------------------------------------------------------
1374
- // Sign-in connections (connect_agent_oauth)
1375
- // ---------------------------------------------------------------------------
1376
- /**
1377
- * Wiro sends the browser to this address after sign-in with the connected
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.
1381
- */
1382
- export function isAllowedRedirectUrl(url, agentGuid, apiBase = DEFAULT_BASE_URL) {
1383
- let parsed;
1384
- try {
1385
- parsed = new URL(url.trim());
1386
- }
1387
- catch {
1388
- return false;
1389
- }
1390
- if (parsed.username || parsed.password)
1391
- return false;
1392
- if (parsed.protocol === 'http:')
1393
- return parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
1394
- const dashboard = new URL(dashboardAgentUrl(agentGuid, apiBase));
1395
- return parsed.protocol === 'https:'
1396
- && parsed.host === dashboard.host
1397
- && parsed.pathname.replace(/\/+$/, '') === dashboard.pathname
1398
- && (parsed.search === '' || parsed.search === dashboard.search)
1399
- && parsed.hash === '';
1400
- }
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);
1428
- }
1429
- /** Goes with a list of missing fields that holds app keys, which may be saved already. */
1430
- export function writeOnlyNote(mode) {
1431
- return `App keys are not shown once saved. If they are saved already, connect with mode ${mode}.`;
1432
- }
1433
- /** The same note before a mode is chosen: it names each usable mode that takes app keys. */
1434
- export function writeOnlyModesNote(requirements) {
1435
- const modes = requirements
1436
- .filter(requirement => requirement.available && requirement.fields.some(field => field.writeOnly))
1437
- .map(requirement => requirement.mode);
1438
- return modes.length > 0 ? writeOnlyNote(modes.join(' or ')) : null;
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
- }
1457
- function fieldsForMode(meta, mode) {
1458
- if (mode === 'wiro')
1459
- return [];
1460
- const byKey = new Map(meta.fields.map(field => [field.key, field]));
1461
- const keys = [];
1462
- if (mode === meta.oauth?.directProbe?.mode) {
1463
- keys.push(...meta.oauth.directProbe.requiredFields);
1464
- }
1465
- else {
1466
- for (const field of meta.fields) {
1467
- if (isWritableField(field) && field.onlyInModes?.includes(mode))
1468
- keys.push(field.key);
1469
- }
1470
- if (mode === 'own')
1471
- keys.push(...(meta.oauth?.stateFields ?? []));
1472
- }
1473
- return [...new Set(keys)]
1474
- .map(key => byKey.get(key) ?? { ...parseCredentialField({ key }), required: true })
1475
- .filter(field => isWritableField(field));
1476
- }
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 = {}) {
1492
- const modes = meta.connectionModes.length > 0 ? meta.connectionModes : ['wiro'];
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;
1499
- const fields = fieldsForMode(meta, mode).map(field => {
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);
1503
- return {
1504
- field: field.key,
1505
- label: field.label,
1506
- isSet,
1507
- ...(field.oauthManaged && !isSet && !statusSays ? { writeOnly: true } : {}),
1508
- };
1509
- });
1510
- if (mode === 'wiro') {
1511
- return {
1512
- mode,
1513
- available: !meta.wiroPending,
1514
- needsBrowser: true,
1515
- fields,
1516
- note: meta.wiroPending
1517
- ? `Use another mode for ${meta.title}.`
1518
- : `Sign in through Wiro's own ${meta.title} app. Nothing to set up first.`,
1519
- };
1520
- }
1521
- if (mode === meta.oauth?.directProbe?.mode) {
1522
- return {
1523
- mode,
1524
- available: true,
1525
- needsBrowser: false,
1526
- fields,
1527
- note: `Save ${meta.oauth.directProbe.label ? `the ${meta.oauth.directProbe.label}` : 'these fields'} with set_agent_credentials, then connect with mode ${mode}. Wiro checks it and lists the accounts it can use. No browser needed.`,
1528
- };
1529
- }
1530
- if (mode === 'api_key') {
1531
- return {
1532
- mode,
1533
- available: true,
1534
- needsBrowser: false,
1535
- fields,
1536
- note: `Save these fields with set_agent_credentials together with authmethod ${mode}. There is no sign-in or connect step for this mode.`,
1537
- };
1538
- }
1539
- if (mode === 'own') {
1540
- const redirect = ownAppRedirectUri(meta, context.redirectUri, context.apiBase);
1541
- const requirements = meta.oauth?.connectRequirements ?? [];
1542
- return {
1543
- mode,
1544
- available: true,
1545
- needsBrowser: true,
1546
- fields,
1547
- note: `Use your own ${meta.title} app: save its keys with set_agent_credentials${redirect ? ` and allow ${redirect} as a redirect URI in the app` : ''}, then connect with mode own and sign in.${requirements.length > 0 ? ` ${requirements.join(' ')}` : ''}`,
1548
- };
1549
- }
1550
- return { mode, available: true, needsBrowser: true, fields, note: `Connect with mode ${mode}.` };
1551
- });
1552
- }
1553
- /**
1554
- * The mode to use when the caller did not name one: Wiro's own app when it is
1555
- * available, the only remaining mode, or the first mode whose fields are
1556
- * already saved (the registry's default first).
1557
- */
1558
- export function chooseConnectionMode(meta, requirements) {
1559
- const usable = requirements.filter(requirement => requirement.available);
1560
- const wiro = usable.find(requirement => requirement.mode === 'wiro');
1561
- if (wiro)
1562
- return 'wiro';
1563
- if (usable.length === 1)
1564
- return usable[0]?.mode ?? null;
1565
- const ordered = [...usable].sort((left, right) => {
1566
- const preferred = meta.defaultConnectionMode;
1567
- return Number(right.mode === preferred) - Number(left.mode === preferred);
1568
- });
1569
- return ordered.find(requirement => requirement.fields.every(field => field.isSet))?.mode ?? null;
1570
- }
1571
- /**
1572
- * An account in a line of this server's text. The outside service sets its name,
1573
- * and a service without an account choice gives that name as the id too, so both
1574
- * are quoted and a repeat is left out.
1575
- */
1576
- export function accountLabel(account) {
1577
- const name = oneLine(account.name);
1578
- const id = quotedSpan(account.id);
1579
- return name && name !== oneLine(account.id) ? `${quotedSpan(name)} (${id})` : id;
1580
- }
1581
- /** Candidate or saved accounts in one shape, whatever the provider calls the fields. */
1582
- export function toAccountRefs(list, picker) {
1583
- if (!Array.isArray(list))
1584
- return [];
1585
- return list.filter(isPlainObject).map(item => {
1586
- const id = asString(item.id) ?? (picker ? asString(item[picker.valueField]) : undefined) ?? '';
1587
- const name = asString(item.name)
1588
- ?? asString(item.title)
1589
- ?? asString(item.displayName)
1590
- ?? (picker?.labelField ? asString(item[picker.labelField]) : undefined)
1591
- ?? '';
1592
- return { id, name };
1593
- }).filter(account => account.id);
1594
- }
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) {
1600
- if (accounts.length === 0)
1601
- return { error: 'Pass at least one account.' };
1602
- if (!picker.multiSelect && accounts.length !== 1)
1603
- return { error: 'This connection uses exactly one account.' };
1604
- const ids = [];
1605
- for (const account of accounts) {
1606
- const id = (asString(account.id) ?? asString(account[picker.valueField]) ?? '').trim();
1607
- if (!id)
1608
- return { error: 'Every account needs an id.' };
1609
- if (ids.includes(id))
1610
- return { error: `Account ${id} is listed twice.` };
1611
- ids.push(id);
1612
- }
1613
- return { ids };
1614
- }
1615
- export function parseDiscoveredGroups(next, groups) {
1616
- if (!Array.isArray(groups))
1617
- return [];
1618
- return groups.filter(isPlainObject).map(group => {
1619
- const parent = isPlainObject(group.parent) ? group.parent : {};
1620
- const items = Array.isArray(group.items) ? group.items.filter(isPlainObject) : [];
1621
- return {
1622
- parent: {
1623
- id: asString(parent[next.parentValueField]) ?? '',
1624
- name: asString(parent[next.parentLabelField]) ?? '',
1625
- },
1626
- items: items
1627
- .map(item => ({
1628
- id: asString(item[next.itemValueField]) ?? '',
1629
- name: asString(item[next.itemLabelField]) ?? '',
1630
- }))
1631
- .filter(item => item.id),
1632
- ...(asString(group.errorcode) ? { errorCode: asString(group.errorcode) } : {}),
1633
- };
1634
- });
1635
- }
1636
- function sameId(left, right) {
1637
- if (left.trim() === right.trim())
1638
- return true;
1639
- const digits = (value) => value.replace(/\D+/g, '');
1640
- return digits(left) !== '' && digits(left) === digits(right);
1641
- }
1642
- /**
1643
- * Builds the chained-step payload from a fresh discovery. The API wants every
1644
- * readable parent exactly once and each item with its discovered label, so
1645
- * parents the caller left out are sent with no items.
1646
- */
1647
- export function buildChainedSelections(next, groups, selections) {
1648
- const chosen = new Map();
1649
- for (const selection of selections) {
1650
- const group = groups.find(candidate => sameId(candidate.parent.id, selection.parent));
1651
- if (!group) {
1652
- return {
1653
- skippedParents: [],
1654
- error: `Account "${selection.parent}" is not among the accounts this step lists (${groups.map(candidate => candidate.parent.id).join(', ') || 'none'}).`,
1655
- };
1656
- }
1657
- if (group.errorCode) {
1658
- return {
1659
- skippedParents: [],
1660
- error: `${accountLabel(group.parent)} could not be read (${group.errorCode}), so nothing can be chosen for it. Leave it out.`,
1661
- };
1662
- }
1663
- const ids = chosen.get(group.parent.id) ?? [];
1664
- for (const itemId of selection.items) {
1665
- const item = group.items.find(candidate => sameId(candidate.id, itemId));
1666
- if (!item) {
1667
- return {
1668
- skippedParents: [],
1669
- error: `"${itemId}" is not available under ${accountLabel(group.parent)}. Available: ${group.items.map(accountLabel).join(', ') || 'none'}.`,
1670
- };
1671
- }
1672
- if (!ids.includes(item.id))
1673
- ids.push(item.id);
1674
- }
1675
- chosen.set(group.parent.id, ids);
1676
- }
1677
- const skippedParents = [];
1678
- const payload = groups.filter(group => !group.errorCode).map(group => {
1679
- const ids = chosen.get(group.parent.id);
1680
- if (!ids)
1681
- skippedParents.push(group.parent);
1682
- return {
1683
- parentvalue: group.parent.id,
1684
- items: group.items
1685
- .filter(item => ids?.includes(item.id))
1686
- .map(item => ({ [next.itemValueField]: item.id, [next.itemLabelField]: item.name })),
1687
- };
1688
- });
1689
- return { selections: payload, skippedParents };
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
- }
1713
- export function parseOAuthStatus(body, picker) {
1714
- let childStep = null;
1715
- const next = picker?.next;
1716
- const steps = isPlainObject(body.pickersteps) ? body.pickersteps : null;
1717
- const step = next && steps && isPlainObject(steps[next.key]) ? steps[next.key] : null;
1718
- if (next && step) {
1719
- childStep = {
1720
- picker: next.key,
1721
- optional: step.optional === true,
1722
- configured: step.configured === true,
1723
- groups: parseDiscoveredGroups(next, step.groups).map(group => ({ parent: group.parent, items: group.items })),
1724
- };
1725
- }
1726
- const redirectUri = asString(body.redirecturi)?.trim();
1727
- return {
1728
- connected: body.connected === true,
1729
- accounts: toAccountRefs(body.accounts, picker),
1730
- connectedAt: asString(body.connectedat) ?? '',
1731
- tokenExpiresAt: asString(body.tokenexpiresat) ?? '',
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 } : {}),
1741
- };
1742
- }
1743
- export async function readOAuthStatus(client, agentGuid, credential, picker, signal) {
1744
- const body = requireApiSuccess(await client.post('/UserAgentOAuth/OAuthStatus', {
1745
- useragentguid: agentGuid,
1746
- credentialkey: credential,
1747
- }, signal), 'Could not read the connection status.');
1748
- return parseOAuthStatus(body, picker);
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
- }
1775
- /**
1776
- * Wiro reports a picker credential as not connected until an account is
1777
- * saved, so a fresh connectedat with no accounts means "signed in, accounts
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.
1780
- */
1781
- export function connectionState(status, options) {
1782
- const fromFlow = ownFlowState(status);
1783
- if (fromFlow)
1784
- return fromFlow;
1785
- if (options.since !== undefined && status.connectedAt === options.since)
1786
- return 'waiting_for_user';
1787
- if (status.connected) {
1788
- return status.childStep && !status.childStep.optional && !status.childStep.configured
1789
- ? 'pick_child_items'
1790
- : 'connected';
1791
- }
1792
- const expiresAt = Date.parse(status.tokenExpiresAt);
1793
- if (Number.isFinite(expiresAt) && expiresAt <= (options.nowMs ?? Date.now())
1794
- && (status.accounts.length > 0 || status.connectedAt)) {
1795
- return 'token_expired';
1796
- }
1797
- if (options.hasPicker && status.connectedAt && status.accounts.length === 0)
1798
- return 'pick_accounts';
1799
- return 'not_connected';
1800
- }
1801
1171
  /** The entry that holds what an agent posts, sends or changes by itself until the user says yes. */
1802
1172
  export const APPROVAL_POLICY_KEY = 'cs-approval-policy';
1803
1173
  const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -1909,9 +1279,25 @@ export function looksLikeCron(expression) {
1909
1279
  return false;
1910
1280
  return parts.every(part => /^[0-9A-Za-z*,/?#-]+$/.test(part));
1911
1281
  }
1912
- /** The runtime always runs a template's scheduled task with the template's own prompt. */
1282
+ /**
1283
+ * Wiro's answer to a change of the text of a scheduled task the agent's template owns: one the template wrote a text
1284
+ * for. The agent runs the template's text whatever its own copy says, so the text stays the template's; its switch and
1285
+ * its schedule are the agent's own.
1286
+ */
1287
+ export const TEMPLATE_TASK_TEXT_REFUSAL = 'This scheduled task comes with the agent\'s template, so its instructions '
1288
+ + 'cannot be changed. You can still turn it on or off and change its schedule.';
1289
+ const TEMPLATE_TASK_TEXT_PATTERN = /comes with the agent's template, so its instructions cannot be changed/i;
1290
+ /** What to do instead of changing a template task's text. */
1291
+ const TEMPLATE_TASK_TEXT_HELP = 'enabled turns it on or off and interval changes its schedule. To change what it does, '
1292
+ + 'edit the related custom skill (a cs- key without cron), or create a scheduled task of your own.';
1293
+ /** The refusal of a text change to a scheduled task the template owns, with the task's key and what to do instead. */
1913
1294
  export function templateTaskTextError(key) {
1914
- return `The text of ${key} comes from the agent's template and cannot be changed; only its schedule (interval) and on/off state (enabled) can. To change what it does, edit the related custom skill (a cs- key without cron), or create your own scheduled task.`;
1295
+ return `${key}: ${TEMPLATE_TASK_TEXT_REFUSAL} ${TEMPLATE_TASK_TEXT_HELP}`;
1296
+ }
1297
+ /** Whether a sent text is the one a task shows, line endings and surrounding blanks aside, as Wiro compares them. */
1298
+ export function sameTaskText(sent, shown) {
1299
+ const plain = (text) => text.replace(/\r\n/g, '\n').trim();
1300
+ return plain(sent) === plain(shown);
1915
1301
  }
1916
1302
  /**
1917
1303
  * Checks deploy_agent's custom_skills the way manage_agent_custom_skill
@@ -1960,11 +1346,13 @@ export function resolveDeployCustomSkills(entries, template) {
1960
1346
  }
1961
1347
  const fromTemplate = known.has(key);
1962
1348
  const templateTask = fromTemplate && kind === 'scheduled_task';
1349
+ // A scheduled task the template wrote a text for runs that text: the agent's own copy never runs.
1350
+ const templateText = templateTask && Boolean(known.get(key)?.instructions?.trim());
1963
1351
  if (entry.value !== undefined && !entry.value.trim()) {
1964
1352
  errors.push(`${key}: value cannot be empty.${fromTemplate ? ' Leave it out to keep the template\'s text.' : ''}`);
1965
1353
  continue;
1966
1354
  }
1967
- if (templateTask && entry.value !== undefined) {
1355
+ if (templateText && entry.value !== undefined) {
1968
1356
  errors.push(templateTaskTextError(key));
1969
1357
  continue;
1970
1358
  }
@@ -2000,6 +1388,19 @@ export function humanizeCustomSkillKey(key) {
2000
1388
  function skillGroupsByKey(value) {
2001
1389
  return Object.fromEntries(Object.entries(value).filter(([, groups]) => Array.isArray(groups)).map(([key, groups]) => [key, toSkillGroups(groups)]));
2002
1390
  }
1391
+ /** A task's connector slugs, as a list or as the JSON text Wiro stores. */
1392
+ function connectorList(value) {
1393
+ let list = value;
1394
+ if (typeof value === 'string') {
1395
+ try {
1396
+ list = JSON.parse(value);
1397
+ }
1398
+ catch {
1399
+ return [];
1400
+ }
1401
+ }
1402
+ return [...new Set(stringList(list).filter(slug => CONNECTOR_SLUG.test(slug)))];
1403
+ }
2003
1404
  export function customSkillEntries(row) {
2004
1405
  const rows = [
2005
1406
  ...(Array.isArray(row.customskills) ? row.customskills : []),
@@ -2018,7 +1419,9 @@ export function customSkillEntries(row) {
2018
1419
  source,
2019
1420
  userCreated: source === 'user-created' || entry._user_created === true,
2020
1421
  requiresCredentials: stringList(entry.requires_credentials),
1422
+ requiresConnectors: connectorList(entry.requires_connectors),
2021
1423
  notWritten: key === STARTER_TASK_KEY && entry._edited === false,
1424
+ ...(customSkillKindOf(key) === 'scheduled_task' && entry._editable === false ? { templateText: true } : {}),
2022
1425
  ownerSkills: stringList(entry._owner_skills),
2023
1426
  skillOff: entry._skill_off === true,
2024
1427
  offSkills: toSkillGroups(entry._off_skills),
@@ -2027,62 +1430,20 @@ export function customSkillEntries(row) {
2027
1430
  };
2028
1431
  }).filter(entry => entry.key);
2029
1432
  }
2030
- /**
2031
- * What connecting a credential does to the entries that need it. Saving it turns on an entry that is off only
2032
- * when the entry's own list names it. For a skill's scheduled task Wiro says what it would still wait for once
2033
- * that credential is connected: such a task turns on and runs (on), or turns on and stays paused while those
2034
- * skills are off (paused). A scheduled task that is on already starts running when only this connection held
2035
- * it back (starts), or stays paused while those skills are off (waiting).
2036
- */
2037
- export function entriesTurnedOnBy(row, credential) {
2038
- const on = [];
2039
- const paused = [];
2040
- const starts = [];
2041
- const waiting = [];
2042
- for (const entry of customSkillEntries(row)) {
2043
- const groups = entry.ifConnected?.[credential];
2044
- if (entry.enabled) {
2045
- if (groups && groups.length > 0)
2046
- waiting.push({ key: entry.key, groups });
2047
- else if (startsOnConnect(row, entry, credential))
2048
- starts.push(entry);
2049
- continue;
2050
- }
2051
- if (!entry.requiresCredentials.includes(credential))
2052
- continue;
2053
- if (!entry.ifConnected || (groups !== undefined && groups.length === 0))
2054
- on.push(entry);
2055
- else if (groups !== undefined)
2056
- paused.push({ key: entry.key, groups });
2057
- }
2058
- return { on, paused, starts, waiting };
2059
- }
2060
- /**
2061
- * Whether a scheduled task that is on runs once this credential is connected, and not before. A skill's task
2062
- * runs then when Wiro says it needs nothing more ([]), and does not run now while it is paused for skills or
2063
- * none of the connections it can use is ready. A task with no skill gate runs while any credential its list
2064
- * names is ready. The starter task does not run until its text is written.
2065
- */
2066
- function startsOnConnect(row, entry, credential) {
2067
- if (entry.kind !== 'scheduled_task' || entry.notWritten)
2068
- return false;
2069
- if (entry.ifConnected) {
2070
- const usable = entry.usableCredentials ?? [];
2071
- return entry.ifConnected[credential]?.length === 0
2072
- && (entry.skillOff === true || (usable.length > 0 && !usable.some(key => credentialReady(row, key))));
2073
- }
2074
- return entry.requiresCredentials.includes(credential) && !entry.requiresCredentials.some(key => credentialReady(row, key));
2075
- }
2076
1433
  /**
2077
1434
  * The connection a scheduled task needs, as a sentence: the credentials it can use (a skill's task) or the
2078
- * ones its row lists (a task of the user's own), by title where the agent's credential cards have one.
1435
+ * ones its row lists (a task of the user's own), by title where the agent's credential cards have one, and
1436
+ * the connectors it needs.
2079
1437
  */
2080
1438
  export function connectionNeededText(row, entry) {
2081
1439
  const keys = entry.usableCredentials ?? entry.requiresCredentials;
2082
- if (keys.length === 0)
2083
- return '';
2084
- const labels = keys.map(key => credentialLabel(row, key));
2085
- return `It only runs while ${labels.length > 1 ? 'one of ' : ''}${nameList(labels, 'or')} is connected.`;
1440
+ const credentials = keys.length > 0
1441
+ ? `It only runs while ${keys.length > 1 ? 'one of ' : ''}${nameList(keys.map(key => credentialLabel(row, key)), 'or')} is connected.`
1442
+ : '';
1443
+ const connectors = entry.requiresConnectors.length > 0
1444
+ ? `It needs ${entry.requiresConnectors.length > 1 ? 'one of the connectors ' : 'the connector '}${nameList(entry.requiresConnectors.map(slug => `\`${slug}\``), 'or')} connected to run.`
1445
+ : '';
1446
+ return [credentials, connectors].filter(Boolean).join(' ');
2086
1447
  }
2087
1448
  /**
2088
1449
  * A credential as people see it, with its key: Google Ads (`google-ads`). Its title comes from the agent's card
@@ -2107,6 +1468,8 @@ export function customSkillErrorMessage(message) {
2107
1468
  if (/invalid-cron-expression|invalid cron/i.test(message)) {
2108
1469
  return 'The schedule is not a valid cron expression. Use five fields: minute hour day-of-month month day-of-week, for example "0 9 * * 1-5".';
2109
1470
  }
1471
+ if (TEMPLATE_TASK_TEXT_PATTERN.test(message))
1472
+ return `${message} ${TEMPLATE_TASK_TEXT_HELP}`;
2110
1473
  if (/customskill-preset-description-not-editable/.test(message)) {
2111
1474
  return 'This entry comes with the agent, so its description cannot be changed. Its text and on/off state can.';
2112
1475
  }