@lobu/runtime-device 21.2.1 → 23.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 (233) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +91 -83
  3. package/npm-shrinkwrap.json +492 -438
  4. package/package.json +12 -2
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +1 -1
  6. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +5 -6
  7. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +1 -0
  8. package/vendor/cli/dist/commands/_lib/apply/client.js +26 -7
  9. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +9 -1
  10. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +1 -0
  11. package/vendor/cli/dist/commands/_lib/apply/diff.js +46 -4
  12. package/vendor/cli/dist/commands/_lib/apply/map-config.js +18 -38
  13. package/vendor/cli/dist/commands/_lib/init-from-org/bootstrap.js +5 -17
  14. package/vendor/cli/dist/commands/init.d.ts +0 -2
  15. package/vendor/cli/dist/commands/init.js +0 -27
  16. package/vendor/cli/dist/commands/login.d.ts +17 -0
  17. package/vendor/cli/dist/commands/login.js +43 -17
  18. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +0 -8
  19. package/vendor/cli/dist/commands/memory/_lib/errors.js +0 -12
  20. package/vendor/cli/dist/commands/memory/_lib/mcp.js +6 -6
  21. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +4 -10
  22. package/vendor/cli/dist/config/define.d.ts +21 -15
  23. package/vendor/cli/dist/config/define.js +2 -2
  24. package/vendor/cli/dist/connectors/README.md +21 -6
  25. package/vendor/cli/dist/connectors/_google/actions.ts +270 -0
  26. package/vendor/cli/dist/connectors/_google/discovery/calendar_v3.json +1 -0
  27. package/vendor/cli/dist/connectors/_google/discovery/chat_v1.json +1 -0
  28. package/vendor/cli/dist/connectors/_google/discovery/docs_v1.json +1 -0
  29. package/vendor/cli/dist/connectors/_google/discovery/drive_v3.json +1 -0
  30. package/vendor/cli/dist/connectors/_google/discovery/gmail_v1.json +1 -0
  31. package/vendor/cli/dist/connectors/_google/discovery/people_v1.json +1 -0
  32. package/vendor/cli/dist/connectors/_google/discovery/sheets_v4.json +1 -0
  33. package/vendor/cli/dist/connectors/_google/discovery/tasks_v1.json +1 -0
  34. package/vendor/cli/dist/connectors/_google/discovery/youtube_v3.json +1 -0
  35. package/vendor/cli/dist/connectors/_google/discovery.ts +442 -0
  36. package/vendor/cli/dist/connectors/_google/errors.ts +91 -0
  37. package/vendor/cli/dist/connectors/_google/list-feed.ts +223 -0
  38. package/vendor/cli/dist/connectors/_google/policies.ts +127 -0
  39. package/vendor/cli/dist/connectors/agentid.ts +43 -0
  40. package/vendor/cli/dist/connectors/chat-user-identity.ts +2 -1
  41. package/vendor/cli/dist/connectors/github-automation-events.ts +9 -0
  42. package/vendor/cli/dist/connectors/github-identity.ts +28 -3
  43. package/vendor/cli/dist/connectors/github.ts +101 -59
  44. package/vendor/cli/dist/connectors/google_calendar.ts +207 -719
  45. package/vendor/cli/dist/connectors/google_drive.ts +16 -2
  46. package/vendor/cli/dist/connectors/google_gmail.ts +52 -33
  47. package/vendor/cli/dist/connectors/herdr.ts +406 -0
  48. package/vendor/cli/dist/connectors/jira-helpers.ts +313 -0
  49. package/vendor/cli/dist/connectors/jira.ts +35 -227
  50. package/vendor/cli/dist/connectors/linear.ts +7 -4
  51. package/vendor/cli/dist/connectors/linkedin-browser-script.ts +13 -0
  52. package/vendor/cli/dist/connectors/linkedin-draft-page.js +104 -0
  53. package/vendor/cli/dist/connectors/linkedin-drafts.ts +73 -0
  54. package/vendor/cli/dist/connectors/linkedin-identity.ts +32 -0
  55. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +1185 -0
  56. package/vendor/cli/dist/connectors/linkedin-inbox.ts +156 -0
  57. package/vendor/cli/dist/connectors/linkedin-like.ts +114 -0
  58. package/vendor/cli/dist/connectors/linkedin-takeout.ts +577 -0
  59. package/vendor/cli/dist/connectors/linkedin.ts +3998 -0
  60. package/vendor/cli/dist/connectors/postgres.ts +27 -2
  61. package/vendor/cli/dist/connectors/takeout-utils.ts +240 -0
  62. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +230 -0
  63. package/vendor/cli/dist/connectors/tiktok-web-page.js +217 -0
  64. package/vendor/cli/dist/connectors/tiktok_web.ts +319 -0
  65. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +285 -567
  66. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +74 -455
  67. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +135 -0
  68. package/vendor/cli/dist/connectors/whatsapp_web.ts +159 -618
  69. package/vendor/cli/dist/connectors/x-dm-adapter.js +556 -0
  70. package/vendor/cli/dist/connectors/x-identity.ts +31 -2
  71. package/vendor/cli/dist/connectors/x.ts +539 -253
  72. package/vendor/cli/dist/index.js +1 -37
  73. package/vendor/cli/dist/internal/context.d.ts +10 -0
  74. package/vendor/cli/dist/internal/context.js +26 -16
  75. package/vendor/cli/dist/internal/node-version.d.ts +1 -1
  76. package/vendor/cli/dist/internal/node-version.js +1 -1
  77. package/vendor/cli/dist/internal/oauth.d.ts +3 -1
  78. package/vendor/cli/dist/internal/oauth.js +4 -3
  79. package/vendor/cli/dist/internal/runtime-components.d.ts +9 -0
  80. package/vendor/cli/dist/internal/runtime-components.js +67 -2
  81. package/vendor/cli/dist/mac-auth.js +17 -1
  82. package/vendor/cli/dist/providers.json +1 -1
  83. package/vendor/cli/dist/runtime-components.json +4 -4
  84. package/vendor/cli/dist/templates/AGENTS.md.tmpl +12 -5
  85. package/vendor/cli/dist/templates/README.md.tmpl +1 -1
  86. package/vendor/cli/dist/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  87. package/vendor/cli/dist/vendor/ora/index.d.ts +332 -0
  88. package/vendor/cli/dist/vendor/ora/index.js +424 -0
  89. package/vendor/cli/dist/vendor/ora/license +9 -0
  90. package/vendor/cli/dist/vendor/ora/package.json +64 -0
  91. package/vendor/cli/dist/vendor/ora/readme.md +329 -0
  92. package/vendor/cli/package.json +2 -2
  93. package/vendor/connector-sdk/dist/browser-handoff-banner.d.ts +39 -0
  94. package/vendor/connector-sdk/dist/browser-handoff-banner.js +175 -0
  95. package/vendor/connector-sdk/dist/browser-requirement.d.ts +36 -0
  96. package/vendor/connector-sdk/dist/browser-requirement.js +60 -0
  97. package/vendor/connector-sdk/dist/browser-source-read.d.ts +52 -0
  98. package/vendor/connector-sdk/dist/browser-source-read.js +107 -0
  99. package/vendor/connector-sdk/dist/connector-runtime.d.ts +3 -1
  100. package/vendor/connector-sdk/dist/connector-runtime.js +10 -0
  101. package/vendor/connector-sdk/dist/connector-types.d.ts +169 -45
  102. package/vendor/connector-sdk/dist/define-connector.d.ts +4 -2
  103. package/vendor/connector-sdk/dist/define-connector.js +3 -0
  104. package/vendor/connector-sdk/dist/index.d.ts +8 -2
  105. package/vendor/connector-sdk/dist/index.js +3 -0
  106. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +16 -21
  107. package/vendor/connector-sdk/dist/reaction-client-types.typecheck.d.ts +5 -0
  108. package/vendor/connector-sdk/package.json +13 -1
  109. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +43 -30
  110. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +416 -330
  111. package/vendor/connector-worker/dist/agent-turn/memory.d.ts +3 -2
  112. package/vendor/connector-worker/dist/agent-turn/memory.js +3 -20
  113. package/vendor/connector-worker/dist/agent-turn/types.d.ts +3 -15
  114. package/vendor/connector-worker/dist/agent-turn/workspace.d.ts +2 -2
  115. package/vendor/connector-worker/dist/agent-turn/workspace.js +2 -4
  116. package/vendor/connector-worker/dist/daemon/action-monitor.d.ts +12 -0
  117. package/vendor/connector-worker/dist/daemon/action-monitor.js +25 -0
  118. package/vendor/connector-worker/dist/daemon/agent-turn.js +0 -9
  119. package/vendor/connector-worker/dist/daemon/automation.d.ts +4 -11
  120. package/vendor/connector-worker/dist/daemon/automation.js +6 -6
  121. package/vendor/connector-worker/dist/daemon/builtins/index.d.ts +12 -0
  122. package/vendor/connector-worker/dist/daemon/builtins/index.js +61 -1
  123. package/vendor/connector-worker/dist/daemon/builtins/os-shell.d.ts +2 -1
  124. package/vendor/connector-worker/dist/daemon/builtins/os-shell.js +40 -27
  125. package/vendor/connector-worker/dist/daemon/client.d.ts +6 -4
  126. package/vendor/connector-worker/dist/daemon/client.js +3 -3
  127. package/vendor/connector-worker/dist/daemon/device-concurrency.d.ts +8 -0
  128. package/vendor/connector-worker/dist/daemon/device-concurrency.js +13 -0
  129. package/vendor/connector-worker/dist/daemon/executor.d.ts +1 -1
  130. package/vendor/connector-worker/dist/daemon/executor.js +48 -120
  131. package/vendor/connector-worker/dist/daemon/log.d.ts +2 -0
  132. package/vendor/connector-worker/dist/daemon/log.js +23 -2
  133. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +23 -6
  134. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +57 -23
  135. package/vendor/connector-worker/dist/daemon/native-bridge/client.d.ts +6 -0
  136. package/vendor/connector-worker/dist/daemon/native-bridge/client.js +15 -0
  137. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +29 -25
  138. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.d.ts +1 -1
  139. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.js +1 -0
  140. package/vendor/connector-worker/dist/daemon/poll-loop.d.ts +3 -0
  141. package/vendor/connector-worker/dist/daemon/poll-loop.js +5 -1
  142. package/vendor/connector-worker/dist/daemon/start.d.ts +1 -0
  143. package/vendor/connector-worker/dist/daemon/start.js +15 -20
  144. package/vendor/connector-worker/dist/daemon/terminal-failure.js +0 -11
  145. package/vendor/connector-worker/dist/daemon/worker-id.d.ts +17 -0
  146. package/vendor/connector-worker/dist/daemon/worker-id.js +22 -0
  147. package/vendor/connector-worker/dist/executor/interface.d.ts +34 -2
  148. package/vendor/connector-worker/dist/executor/isolate.js +66 -15
  149. package/vendor/connector-worker/dist/executor/redact.d.ts +1 -0
  150. package/vendor/connector-worker/dist/executor/redact.js +97 -26
  151. package/vendor/connector-worker/dist/executor/runtime.d.ts +7 -0
  152. package/vendor/connector-worker/dist/executor/runtime.js +26 -0
  153. package/vendor/connector-worker/dist/isolate/bridge.js +3 -1
  154. package/vendor/connector-worker/dist/mac-device-daemon.js +24 -29
  155. package/vendor/connector-worker/package.json +2 -2
  156. package/vendor/core/dist/agent-policy.js +1 -1
  157. package/vendor/core/dist/agent-store.d.ts +2 -0
  158. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  159. package/vendor/core/dist/agent-tooling.js +1 -1
  160. package/vendor/core/dist/capabilities.d.ts +1 -1
  161. package/vendor/core/dist/capabilities.js +2 -1
  162. package/vendor/core/dist/connector-query-errors.d.ts +32 -0
  163. package/vendor/core/dist/connector-query-errors.js +41 -1
  164. package/vendor/core/dist/contracts/agent-settings.d.ts +0 -11
  165. package/vendor/core/dist/contracts/agent-settings.js +1 -7
  166. package/vendor/core/dist/contracts/tools/collection-presentation.d.ts +93 -0
  167. package/vendor/core/dist/contracts/tools/collection-presentation.js +88 -0
  168. package/vendor/core/dist/contracts/tools/collection-selection.d.ts +47 -0
  169. package/vendor/core/dist/contracts/tools/collection-selection.js +74 -0
  170. package/vendor/core/dist/contracts/tools/manage-agents.d.ts +10 -4
  171. package/vendor/core/dist/contracts/tools/manage-auth-profiles.d.ts +1 -1
  172. package/vendor/core/dist/contracts/tools/manage-auth-profiles.js +5 -1
  173. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +19 -4
  174. package/vendor/core/dist/contracts/tools/manage-automations.js +25 -8
  175. package/vendor/core/dist/contracts/tools/manage-connections.d.ts +1 -0
  176. package/vendor/core/dist/contracts/tools/manage-connections.js +3 -0
  177. package/vendor/core/dist/contracts/tools/manage-conversations.js +2 -2
  178. package/vendor/core/dist/contracts/tools/manage-entity-schema.d.ts +11 -0
  179. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +42 -3
  180. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +181 -152
  181. package/vendor/core/dist/contracts/tools/manage-entity.js +118 -162
  182. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +14 -0
  183. package/vendor/core/dist/contracts/tools/manage-feeds.js +17 -0
  184. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +41 -3
  185. package/vendor/core/dist/contracts/tools/manage-operations.js +40 -2
  186. package/vendor/core/dist/contracts/tools/manage-views.d.ts +182 -7
  187. package/vendor/core/dist/contracts/tools/manage-views.js +49 -13
  188. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +11 -2
  189. package/vendor/core/dist/contracts/tools/read-knowledge.js +23 -3
  190. package/vendor/core/dist/contracts/tools/save-memory.d.ts +3 -6
  191. package/vendor/core/dist/contracts/tools/save-memory.js +2 -6
  192. package/vendor/core/dist/contracts/tools/view-attach.d.ts +2 -1
  193. package/vendor/core/dist/contracts/tools/view-attach.js +7 -2
  194. package/vendor/core/dist/contracts/worker/protocol.d.ts +130 -159
  195. package/vendor/core/dist/contracts/worker/protocol.js +88 -76
  196. package/vendor/core/dist/device-pin-tombstones.d.ts +44 -0
  197. package/vendor/core/dist/device-pin-tombstones.js +57 -0
  198. package/vendor/core/dist/index.d.ts +5 -5
  199. package/vendor/core/dist/index.js +4 -6
  200. package/vendor/core/dist/json-template.d.ts +6 -10
  201. package/vendor/core/dist/json-template.js +5 -9
  202. package/vendor/core/dist/logger.js +17 -26
  203. package/vendor/core/dist/shell-safety.d.ts +9 -0
  204. package/vendor/core/dist/shell-safety.js +154 -0
  205. package/vendor/core/dist/suggestions.d.ts +1 -1
  206. package/vendor/core/dist/suggestions.js +1 -1
  207. package/vendor/core/dist/tool-trace-summary.d.ts +1 -1
  208. package/vendor/core/dist/tool-trace-summary.js +1 -1
  209. package/vendor/core/dist/types.d.ts +1 -3
  210. package/vendor/core/dist/utils/diagnostic-scrubber.d.ts +7 -0
  211. package/vendor/core/dist/utils/diagnostic-scrubber.js +437 -0
  212. package/vendor/core/dist/worker/auth.d.ts +44 -6
  213. package/vendor/core/dist/worker/auth.js +44 -11
  214. package/vendor/core/dist/worker/wire.d.ts +0 -10
  215. package/vendor/core/package.json +20 -11
  216. package/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  217. package/vendor/ora/index.d.ts +332 -0
  218. package/vendor/ora/index.js +424 -0
  219. package/vendor/ora/license +9 -0
  220. package/vendor/ora/package.json +53 -0
  221. package/vendor/ora/readme.md +329 -0
  222. package/vendor/cli/dist/commands/telemetry.d.ts +0 -10
  223. package/vendor/cli/dist/commands/telemetry.js +0 -66
  224. package/vendor/connector-worker/dist/daemon/device-chat.d.ts +0 -9
  225. package/vendor/connector-worker/dist/daemon/device-chat.js +0 -61
  226. package/vendor/core/dist/contracts/worker/device-chat.d.ts +0 -4
  227. package/vendor/core/dist/contracts/worker/device-chat.js +0 -26
  228. package/vendor/core/dist/sentry.d.ts +0 -26
  229. package/vendor/core/dist/sentry.js +0 -133
  230. package/vendor/core/dist/tool-policy.d.ts +0 -74
  231. package/vendor/core/dist/tool-policy.js +0 -305
  232. package/vendor/core/dist/utils/sentry-scrubber.d.ts +0 -29
  233. package/vendor/core/dist/utils/sentry-scrubber.js +0 -228
@@ -0,0 +1,442 @@
1
+ /**
2
+ * Google Discovery documents, read directly.
3
+ *
4
+ * Every Google REST API publishes a Discovery document: each method's HTTP
5
+ * verb, path template, parameters, request/response schemas and the OAuth
6
+ * scopes that may authorize it. The connectors pin a trimmed copy of each
7
+ * document (see `scripts/pin-google-discovery.ts`) and compile actions and
8
+ * feed requests from it, so URL building, parameter encoding and scope lists
9
+ * come from Google's own description instead of being retyped per action.
10
+ */
11
+ import { fileInputSchema, MAX_CONNECTOR_FILE_BYTES } from '@lobu/connector-sdk';
12
+
13
+ export interface DiscoverySchema {
14
+ id?: string;
15
+ type?: string;
16
+ $ref?: string;
17
+ description?: string;
18
+ properties?: Record<string, DiscoverySchema>;
19
+ items?: DiscoverySchema;
20
+ additionalProperties?: DiscoverySchema;
21
+ enum?: string[];
22
+ format?: string;
23
+ readOnly?: boolean;
24
+ default?: string;
25
+ required?: boolean;
26
+ repeated?: boolean;
27
+ location?: 'path' | 'query';
28
+ minimum?: string;
29
+ maximum?: string;
30
+ deprecated?: boolean;
31
+ }
32
+
33
+ export interface DiscoveryMethod {
34
+ id: string;
35
+ path: string;
36
+ httpMethod: string;
37
+ description?: string;
38
+ parameters?: Record<string, DiscoverySchema>;
39
+ parameterOrder?: string[];
40
+ request?: { $ref: string };
41
+ response?: { $ref: string };
42
+ scopes?: string[];
43
+ supportsMediaDownload?: boolean;
44
+ useMediaDownloadService?: boolean;
45
+ supportsMediaUpload?: boolean;
46
+ mediaUpload?: {
47
+ accept?: string[];
48
+ maxSize?: string;
49
+ protocols?: { simple?: { multipart?: boolean; path: string } };
50
+ };
51
+ deprecated?: boolean;
52
+ }
53
+
54
+ interface DiscoveryResource {
55
+ methods?: Record<string, DiscoveryMethod>;
56
+ resources?: Record<string, DiscoveryResource>;
57
+ }
58
+
59
+ export interface DiscoveryDocument extends DiscoveryResource {
60
+ name: string;
61
+ version: string;
62
+ title?: string;
63
+ revision?: string;
64
+ rootUrl: string;
65
+ servicePath: string;
66
+ batchPath?: string;
67
+ auth?: { oauth2?: { scopes?: Record<string, { description?: string }> } };
68
+ schemas?: Record<string, DiscoverySchema>;
69
+ }
70
+
71
+ export function discoveryMethods(doc: DiscoveryResource): DiscoveryMethod[] {
72
+ const out = Object.values(doc.methods ?? {});
73
+ for (const resource of Object.values(doc.resources ?? {})) {
74
+ out.push(...discoveryMethods(resource));
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * A method's own parameters. Discovery declares the transport plumbing every
81
+ * method shares (`key`, `access_token`, `alt`, `fields`, …) once at document
82
+ * level; the pin script drops it, so it never reaches an action's input. Of
83
+ * those, only `fields` is a caller's choice, and `methodInputSchema` adds it.
84
+ */
85
+ export function methodParameters(method: DiscoveryMethod): Array<[string, DiscoverySchema]> {
86
+ return Object.entries(method.parameters ?? {});
87
+ }
88
+
89
+ /** Lookup by Discovery method id, e.g. `calendar.events.list`. */
90
+ export function findMethod(doc: DiscoveryDocument, id: string): DiscoveryMethod {
91
+ const method = discoveryMethods(doc).find((m) => m.id === id);
92
+ if (!method) throw new Error(`${doc.name}/${doc.version} has no method ${id}`);
93
+ return method;
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // Request building
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export interface GoogleRequest {
101
+ method: string;
102
+ url: string;
103
+ body?: string | Uint8Array;
104
+ headers: Record<string, string>;
105
+ }
106
+
107
+ /**
108
+ * RFC 6570 expansion as Discovery uses it. `{name}` is a single path segment
109
+ * and is fully encoded (`team@example.com` → `team%40example.com`). `{+name}`
110
+ * is reserved expansion: the value is a resource NAME such as
111
+ * `spaces/AAA/messages/BBB` whose slashes are structure, so only each segment
112
+ * is encoded. Encoding the whole value would send `spaces%2FAAA…`, which
113
+ * Google answers with 404.
114
+ */
115
+ function expandPath(template: string, values: Record<string, unknown>, methodId: string): string {
116
+ return template.replace(/\{(\+?)([^}]+)\}/g, (_, reserved: string, name: string) => {
117
+ const value = values[name];
118
+ if (value === undefined || value === null || value === '') {
119
+ throw new Error(`${methodId} requires path parameter "${name}".`);
120
+ }
121
+ const text = String(value);
122
+ return reserved ? text.split('/').map(encodeURIComponent).join('/') : encodeURIComponent(text);
123
+ });
124
+ }
125
+
126
+ /** File bytes for a media upload, already resolved from a Lobu file input. */
127
+ export interface UploadMedia {
128
+ bytes: Uint8Array;
129
+ contentType: string;
130
+ }
131
+
132
+ export function buildGoogleRequest(
133
+ doc: DiscoveryDocument,
134
+ method: DiscoveryMethod,
135
+ input: Record<string, unknown>,
136
+ options: { media?: 'download'; upload?: UploadMedia } = {}
137
+ ): GoogleRequest {
138
+ const uploadPath = options.upload ? uploadProtocol(method)?.path : undefined;
139
+ if (options.upload && !uploadPath) throw new Error(`${method.id} does not accept a file upload.`);
140
+ // Concatenated, not `new URL(path, base)`: a relative path whose first
141
+ // segment holds a colon (`spaces:search`) would parse as a URL scheme. An
142
+ // upload path is absolute from the API host (`/upload/drive/v3/files`).
143
+ const url = new URL(
144
+ uploadPath
145
+ ? `${doc.rootUrl.replace(/\/$/, '')}${expandPath(uploadPath, input, method.id)}`
146
+ : `${doc.rootUrl}${doc.servicePath}${expandPath(method.path, input, method.id)}`
147
+ );
148
+ for (const [name, schema] of methodParameters(method)) {
149
+ if (schema.location !== 'query') continue;
150
+ const value = input[name];
151
+ if (value === undefined || value === null) continue;
152
+ for (const item of Array.isArray(value) ? value : [value]) {
153
+ url.searchParams.append(name, String(item));
154
+ }
155
+ }
156
+ if (typeof input.fields === 'string' && input.fields) url.searchParams.set('fields', input.fields);
157
+ if (options.media === 'download') url.searchParams.set('alt', 'media');
158
+
159
+ const request: GoogleRequest = { method: method.httpMethod, url: url.toString(), headers: {} };
160
+ if (options.upload) {
161
+ // Multipart carries the request object beside the bytes; a method with no
162
+ // request object (YouTube `thumbnails.set`) takes the bytes alone.
163
+ const upload = method.request
164
+ ? multipartRelated(JSON.stringify(input.body ?? {}), options.upload)
165
+ : { body: options.upload.bytes, contentType: options.upload.contentType };
166
+ url.searchParams.set('uploadType', method.request ? 'multipart' : 'media');
167
+ request.url = url.toString();
168
+ request.body = upload.body;
169
+ request.headers['Content-Type'] = upload.contentType;
170
+ } else if (input.body !== undefined && method.request) {
171
+ request.body = JSON.stringify(input.body);
172
+ request.headers['Content-Type'] = 'application/json';
173
+ }
174
+ return request;
175
+ }
176
+
177
+ /** Google's simple upload protocol, when the method offers its multipart form. */
178
+ function uploadProtocol(method: DiscoveryMethod): { path: string } | undefined {
179
+ const simple = method.supportsMediaUpload ? method.mediaUpload?.protocols?.simple : undefined;
180
+ return simple?.multipart ? simple : undefined;
181
+ }
182
+
183
+ /** `multipart/related`: the JSON request object, then the file's bytes verbatim. */
184
+ function multipartRelated(metadata: string, media: UploadMedia): { body: Uint8Array; contentType: string } {
185
+ const boundary = `lobu_${crypto.randomUUID().replace(/-/g, '')}`;
186
+ const encoder = new TextEncoder();
187
+ const head = encoder.encode(
188
+ `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${metadata}\r\n` +
189
+ `--${boundary}\r\nContent-Type: ${media.contentType}\r\n\r\n`
190
+ );
191
+ const tail = encoder.encode(`\r\n--${boundary}--\r\n`);
192
+ const body = new Uint8Array(head.length + media.bytes.length + tail.length);
193
+ body.set(head, 0);
194
+ body.set(media.bytes, head.length);
195
+ body.set(tail, head.length + media.bytes.length);
196
+ return { body, contentType: `multipart/related; boundary=${boundary}` };
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // JSON Schema
201
+ // ---------------------------------------------------------------------------
202
+
203
+ type JsonSchema = Record<string, unknown>;
204
+
205
+ /**
206
+ * Formats handed to the operation validator (ajv-formats): only those whose
207
+ * AJV rule is no stricter than Google's. Dropped, and left to Google to
208
+ * validate: Google-only formats (`google-fieldmask`, `uint64`, …) AJV does not
209
+ * know; `byte`, because Gmail sends base64url, which AJV's base64 rejects; and
210
+ * `date-time`/`google-datetime`, because Google accepts an offset-free time
211
+ * beside a `timeZone` (Calendar `EventDateTime`), which RFC 3339 does not.
212
+ */
213
+ const FORMAT_ALIASES: Record<string, string> = {
214
+ date: 'date',
215
+ int32: 'int32',
216
+ int64: 'int64',
217
+ float: 'float',
218
+ double: 'double',
219
+ };
220
+
221
+ function scalarSchema(schema: DiscoverySchema, describe = true): JsonSchema {
222
+ const out: JsonSchema = {};
223
+ if (schema.type && schema.type !== 'any') out.type = schema.type;
224
+ if (describe && schema.description) out.description = schema.description;
225
+ if (schema.enum) out.enum = schema.enum;
226
+ const format = schema.format ? FORMAT_ALIASES[schema.format] : undefined;
227
+ if (format) out.format = format;
228
+ if (schema.default !== undefined) out.default = coerceDefault(schema);
229
+ if (schema.minimum !== undefined) out.minimum = Number(schema.minimum);
230
+ if (schema.maximum !== undefined) out.maximum = Number(schema.maximum);
231
+ return out;
232
+ }
233
+
234
+ /** Discovery spells every default as a string, even `"true"` and `"250"`. */
235
+ function coerceDefault(schema: DiscoverySchema): unknown {
236
+ if (schema.type === 'boolean') return schema.default === 'true';
237
+ if (schema.type === 'integer' || schema.type === 'number') return Number(schema.default);
238
+ return schema.default;
239
+ }
240
+
241
+ function parameterSchema(schema: DiscoverySchema): JsonSchema {
242
+ if (!schema.repeated) return scalarSchema(schema);
243
+ const { description, ...item } = scalarSchema(schema);
244
+ return { type: 'array', items: item, ...(description ? { description } : {}) };
245
+ }
246
+
247
+ /**
248
+ * Convert a Discovery schema, collecting every referenced schema into `defs`.
249
+ * Refs stay refs (`#/$defs/Event`): Discovery schemas can be recursive, so
250
+ * inlining may not terminate. `readOnly` properties are dropped from request
251
+ * bodies: they are server-assigned (`etag`, `htmlLink`) and Google rejects or
252
+ * ignores them.
253
+ *
254
+ * Descriptions are kept only on the request object's own fields (`describe`).
255
+ * Google's nested field prose is what makes `events.insert` 35 KB and Sheets
256
+ * `batchUpdate` 175 KB of schema; the structure alone is a fraction of that.
257
+ */
258
+ function bodySchema(
259
+ doc: DiscoveryDocument,
260
+ schema: DiscoverySchema,
261
+ defs: Record<string, JsonSchema>,
262
+ describe: boolean
263
+ ): JsonSchema {
264
+ if (schema.$ref) {
265
+ addDef(doc, schema.$ref, defs, false);
266
+ return { $ref: `#/$defs/${schema.$ref}`, ...(describe && schema.description ? { description: schema.description } : {}) };
267
+ }
268
+ const out = scalarSchema(schema, describe);
269
+ if (schema.properties) {
270
+ out.properties = Object.fromEntries(
271
+ Object.entries(schema.properties)
272
+ .filter(([, property]) => !property.readOnly)
273
+ .map(([name, property]) => [name, bodySchema(doc, property, defs, describe)])
274
+ );
275
+ }
276
+ if (schema.items) out.items = bodySchema(doc, schema.items, defs, false);
277
+ if (schema.additionalProperties) {
278
+ out.additionalProperties = bodySchema(doc, schema.additionalProperties, defs, false);
279
+ }
280
+ return out;
281
+ }
282
+
283
+ function addDef(
284
+ doc: DiscoveryDocument,
285
+ name: string,
286
+ defs: Record<string, JsonSchema>,
287
+ describe: boolean
288
+ ): void {
289
+ if (defs[name]) return;
290
+ const schema = doc.schemas?.[name];
291
+ if (!schema) throw new Error(`${doc.name}/${doc.version} references unknown schema ${name}`);
292
+ defs[name] = {}; // placeholder first: a self-reference must not recurse forever
293
+ defs[name] = bodySchema(doc, schema, defs, describe);
294
+ }
295
+
296
+ /**
297
+ * Google's partial-response selector, valid on every method. Drive needs it
298
+ * most: without it `files.get` answers with four fields.
299
+ */
300
+ const FIELDS_PARAMETER: JsonSchema = {
301
+ type: 'string',
302
+ description:
303
+ 'Partial-response field selector, e.g. `nextPageToken,files(id,name,modifiedTime)`. `*` returns every field; some APIs (Drive) return only a few unless asked.',
304
+ };
305
+
306
+ /**
307
+ * The file a media-upload method sends beside its request object. Lobu's file
308
+ * input contract carries it, so bytes never pass through the model; the cap is
309
+ * the platform's per-operation limit or Google's, whichever is lower.
310
+ */
311
+ function mediaSchema(method: DiscoveryMethod): JsonSchema {
312
+ const googleMax = Number(method.mediaUpload?.maxSize);
313
+ const maxBytes = Math.min(MAX_CONNECTOR_FILE_BYTES, Number.isFinite(googleMax) && googleMax > 0 ? googleMax : Infinity);
314
+ const accept = method.mediaUpload?.accept?.join(', ');
315
+ return {
316
+ ...fileInputSchema({ maxBytes }),
317
+ description:
318
+ `File content to upload with this request (at most ${maxBytes} bytes${accept ? `; ${accept}` : ''}). ` +
319
+ 'The request object still goes in `body`. Pass a file from run_sdk ctx.files or a Lobu file reference, never inline bytes copied through the model.',
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Flat action input: every path/query parameter at the top level, plus `body`
325
+ * for methods that take a request object. Flat because that is how every
326
+ * Google client library and Google's own reference page present a call.
327
+ */
328
+ export function methodInputSchema(
329
+ doc: DiscoveryDocument,
330
+ method: DiscoveryMethod,
331
+ defaults: Record<string, unknown> = {}
332
+ ): JsonSchema {
333
+ const properties: Record<string, JsonSchema> = {};
334
+ const required: string[] = [];
335
+ for (const [name, schema] of methodParameters(method)) {
336
+ if (name === 'body' || name === 'fields' || name === 'media') {
337
+ throw new Error(`${method.id} has a parameter named "${name}", which collides with a reserved input.`);
338
+ }
339
+ properties[name] = parameterSchema(schema);
340
+ if (name in defaults) properties[name].default = defaults[name];
341
+ else if (schema.required) required.push(name);
342
+ }
343
+ properties.fields = FIELDS_PARAMETER;
344
+ if (uploadProtocol(method)) properties.media = mediaSchema(method);
345
+ const schema: JsonSchema = { type: 'object', properties, ...(required.length ? { required } : {}) };
346
+ if (!method.request) return schema;
347
+ const defs: Record<string, JsonSchema> = {};
348
+ addDef(doc, method.request.$ref, defs, true);
349
+ properties.body = { $ref: `#/$defs/${method.request.$ref}`, description: 'Request body.' };
350
+ return fitToBudget({ ...schema, $defs: defs }, method.request.$ref);
351
+ }
352
+
353
+ /**
354
+ * Upper bound on one action's input schema, in serialized bytes.
355
+ *
356
+ * `operations.listAvailable` returns every input schema by default, so a
357
+ * connector's whole catalogue lands in an agent's context: Calendar's 32
358
+ * actions were 134 KB, Sheets `batchUpdate` alone 54 KB (203 nested types).
359
+ */
360
+ const SCHEMA_BUDGET_BYTES = 12 * 1024;
361
+
362
+ /**
363
+ * Shrink a body-carrying schema until it fits the budget, in order of what is
364
+ * lost: first the body's field prose is cut to its first sentence, then the
365
+ * deepest nested types collapse to opaque `{ type, title }` placeholders, one
366
+ * level at a time. Parameters are never touched. Collapsing only loosens
367
+ * validation — Google still validates the body — so what is lost is guidance,
368
+ * never correctness of what is sent. A request type whose own fields exceed the
369
+ * budget (Drive `File`) is returned at depth 0 rather than truncated further.
370
+ */
371
+ function fitToBudget(schema: JsonSchema, root: string): JsonSchema {
372
+ const size = (s: JsonSchema) => JSON.stringify(s).length;
373
+ if (size(schema) <= SCHEMA_BUDGET_BYTES) return schema;
374
+
375
+ const defs = mapDescriptions(schema.$defs, firstSentence) as Record<string, JsonSchema>;
376
+ let fitted: JsonSchema = { ...schema, $defs: defs };
377
+ if (size(fitted) <= SCHEMA_BUDGET_BYTES) return fitted;
378
+
379
+ const depths = new Map([[root, 0]]);
380
+ const queue = [root];
381
+ for (let name = queue.shift(); name !== undefined; name = queue.shift()) {
382
+ for (const ref of refsIn(defs[name])) {
383
+ if (depths.has(ref)) continue;
384
+ depths.set(ref, (depths.get(name) ?? 0) + 1);
385
+ queue.push(ref);
386
+ }
387
+ }
388
+ for (let depth = Math.max(...depths.values()) - 1; depth >= 0; depth--) {
389
+ const keep = new Set([...depths].filter(([, d]) => d <= depth).map(([name]) => name));
390
+ fitted = {
391
+ ...schema,
392
+ properties: collapseRefs(schema.properties, keep, defs),
393
+ $defs: Object.fromEntries([...keep].map((name) => [name, collapseRefs(defs[name], keep, defs)])),
394
+ };
395
+ if (size(fitted) <= SCHEMA_BUDGET_BYTES) break;
396
+ }
397
+ return fitted;
398
+ }
399
+
400
+ function firstSentence(text: string): string {
401
+ const sentence = (text.match(/^[\s\S]*?[.!?](?=\s+[A-Z]|$)/)?.[0] ?? text).trim();
402
+ return sentence.length > 200 ? `${sentence.slice(0, 199)}…` : sentence;
403
+ }
404
+
405
+ function mapDescriptions(node: unknown, map: (text: string) => string): unknown {
406
+ if (Array.isArray(node)) return node.map((child) => mapDescriptions(child, map));
407
+ if (!node || typeof node !== 'object') return node;
408
+ return Object.fromEntries(
409
+ Object.entries(node).map(([key, value]) => [
410
+ key,
411
+ key === 'description' && typeof value === 'string' ? map(value) : mapDescriptions(value, map),
412
+ ])
413
+ );
414
+ }
415
+
416
+ const DEF_PREFIX = '#/$defs/';
417
+
418
+ function refsIn(node: unknown, found = new Set<string>()): Set<string> {
419
+ if (Array.isArray(node)) for (const child of node) refsIn(child, found);
420
+ else if (node && typeof node === 'object') {
421
+ for (const [key, value] of Object.entries(node)) {
422
+ if (key === '$ref' && typeof value === 'string') found.add(value.slice(DEF_PREFIX.length));
423
+ else refsIn(value, found);
424
+ }
425
+ }
426
+ return found;
427
+ }
428
+
429
+ /** Replace refs to types outside `keep` with an opaque schema naming the Google type. */
430
+ function collapseRefs(node: unknown, keep: Set<string>, defs: Record<string, JsonSchema>): JsonSchema {
431
+ const walk = (value: unknown): unknown => {
432
+ if (Array.isArray(value)) return value.map(walk);
433
+ if (!value || typeof value !== 'object') return value;
434
+ const { $ref, ...rest } = value as JsonSchema;
435
+ if (typeof $ref === 'string') {
436
+ const name = $ref.slice(DEF_PREFIX.length);
437
+ if (!keep.has(name)) return { type: defs[name]?.type ?? 'object', title: name, ...rest };
438
+ }
439
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, walk(child)]));
440
+ };
441
+ return walk(node) as JsonSchema;
442
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Google API failures, classified from the structured error body.
3
+ *
4
+ * Google answers several unrelated conditions with the same HTTP status — a
5
+ * 403 is a quota hit, a missing OAuth scope, a disabled API in the client's
6
+ * GCP project, or a genuine permission denial — and each needs a different
7
+ * recovery (back off, ask for consent, fix the project, give up). The body
8
+ * carries typed reasons (`error.details[].reason`, legacy `error.errors[].reason`),
9
+ * so the distinction is read from those enums once, here, and passed on as a
10
+ * code; nothing downstream re-matches message text.
11
+ */
12
+
13
+ export type GoogleErrorCode =
14
+ | 'rate_limited'
15
+ | 'quota_exhausted'
16
+ | 'scope_insufficient'
17
+ | 'api_disabled'
18
+ | 'auth_expired'
19
+ | 'permission_denied'
20
+ | 'not_found'
21
+ | 'cursor_expired'
22
+ | 'invalid_request'
23
+ | 'server_error'
24
+ | 'unknown';
25
+
26
+ export interface GoogleError {
27
+ code: GoogleErrorCode;
28
+ status: number;
29
+ message: string;
30
+ retryable: boolean;
31
+ /** Reasons as Google sent them, for logs. */
32
+ reasons: string[];
33
+ }
34
+
35
+ interface GoogleErrorBody {
36
+ error?: {
37
+ message?: string;
38
+ status?: string;
39
+ errors?: Array<{ reason?: string }>;
40
+ details?: Array<{ reason?: string }>;
41
+ } | string;
42
+ error_description?: string;
43
+ }
44
+
45
+ const RATE_LIMIT_REASONS = new Set([
46
+ 'rateLimitExceeded',
47
+ 'userRateLimitExceeded',
48
+ 'RATE_LIMIT_EXCEEDED',
49
+ ]);
50
+ const QUOTA_REASONS = new Set(['quotaExceeded', 'dailyLimitExceeded']);
51
+ const SCOPE_REASONS = new Set(['ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'insufficientPermissions']);
52
+ const DISABLED_REASONS = new Set(['SERVICE_DISABLED', 'accessNotConfigured', 'API_DISABLED']);
53
+
54
+ export function classifyGoogleError(status: number, bodyText: string): GoogleError {
55
+ let body: GoogleErrorBody = {};
56
+ try {
57
+ body = (JSON.parse(bodyText) ?? {}) as GoogleErrorBody;
58
+ } catch {
59
+ // Not JSON (an HTML 502 page from a load balancer): status alone decides.
60
+ }
61
+ const error = typeof body.error === 'object' ? body.error : undefined;
62
+ const reasons = [
63
+ ...(error?.details ?? []).map((d) => d.reason),
64
+ ...(error?.errors ?? []).map((e) => e.reason),
65
+ typeof body.error === 'string' ? body.error : undefined,
66
+ ].filter((r): r is string => typeof r === 'string');
67
+ const message = error?.message ?? body.error_description ?? bodyText.slice(0, 500);
68
+ const has = (set: Set<string>) => reasons.some((r) => set.has(r));
69
+ const result = (code: GoogleErrorCode, retryable = false): GoogleError => ({
70
+ code,
71
+ status,
72
+ message,
73
+ retryable,
74
+ reasons,
75
+ });
76
+
77
+ // Order matters: a 403 can carry both a generic and a specific reason.
78
+ if (has(DISABLED_REASONS)) return result('api_disabled');
79
+ if (has(SCOPE_REASONS)) return result('scope_insufficient');
80
+ if (has(QUOTA_REASONS)) return result('quota_exhausted');
81
+ if (status === 429 || has(RATE_LIMIT_REASONS)) return result('rate_limited', true);
82
+ if (status === 401 || reasons.includes('invalid_grant') || reasons.includes('authError')) {
83
+ return result('auth_expired');
84
+ }
85
+ if (status === 410) return result('cursor_expired');
86
+ if (status === 404) return result('not_found');
87
+ if (status === 403) return result('permission_denied');
88
+ if (status === 400) return result('invalid_request');
89
+ if (status >= 500) return result('server_error', true);
90
+ return result('unknown');
91
+ }