@k2b/cloud 0.6.0-rc.0 → 0.7.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 (315) hide show
  1. package/README.md +2 -2
  2. package/package.json +30 -17
  3. package/scripts/browser-performance.ts +14 -0
  4. package/scripts/build-pdf-renderer.ts +39 -0
  5. package/scripts/build.ts +15 -35
  6. package/scripts/preload.ts +9 -12
  7. package/scripts/sync-recovery-smoke.ts +2 -1
  8. package/src/_internal/app-presentation.ts +14 -2
  9. package/src/_internal/capabilities.ts +108 -7
  10. package/src/_internal/capability-streams.ts +81 -0
  11. package/src/_internal/define-app.ts +62 -36
  12. package/src/_internal/heartbeat.ts +4 -0
  13. package/src/_internal/help-catalog.ts +27 -172
  14. package/src/_internal/help.ts +13 -76
  15. package/src/_internal/page-responses.ts +2 -0
  16. package/src/_internal/postgres-application-name.ts +30 -0
  17. package/src/_internal/process-identity.ts +15 -0
  18. package/src/_internal/process-sync.ts +1 -1
  19. package/src/_internal/registry-validation.ts +29 -25
  20. package/src/_internal/registry.ts +2 -53
  21. package/src/_internal/runtime-context.ts +5 -16
  22. package/src/_internal/server-timing.ts +13 -0
  23. package/src/_internal/status-preserving-ssr.ts +18 -6
  24. package/src/_internal/web-vitals-asset.ts +10 -0
  25. package/src/access/PermissionEditor.tsx +14 -153
  26. package/src/access/PrincipalPicker.tsx +104 -0
  27. package/src/access/ui.ts +2 -0
  28. package/src/ai/admin.ts +14 -13
  29. package/src/ai/assistant-models.ts +12 -1
  30. package/src/ai/audio-format.ts +34 -0
  31. package/src/ai/audio-tool.ts +90 -0
  32. package/src/ai/browser-code-contracts.ts +79 -0
  33. package/src/ai/browser.ts +2 -0
  34. package/src/ai/capabilities.ts +55 -36
  35. package/src/ai/capability-execution.ts +47 -12
  36. package/src/ai/chat/blocks.tsx +157 -95
  37. package/src/ai/chat/capability-result.ts +15 -0
  38. package/src/ai/chat/capability-table.tsx +2 -10
  39. package/src/ai/chat/composer-adapter.ts +48 -3
  40. package/src/ai/chat/message-actions.tsx +8 -7
  41. package/src/ai/chat/message-utils.ts +12 -1
  42. package/src/ai/chat/messages.ts +2 -0
  43. package/src/ai/chat/presentation.tsx +19 -48
  44. package/src/ai/chat/primitives.tsx +43 -1
  45. package/src/ai/chat/tool-disclosure.tsx +17 -2
  46. package/src/ai/chat/tool-groups.ts +52 -0
  47. package/src/ai/chat-quotas.ts +25 -0
  48. package/src/ai/chat-task-contracts.ts +9 -1
  49. package/src/ai/chat-tasks.ts +276 -43
  50. package/src/ai/client/controller.ts +110 -33
  51. package/src/ai/client/file-source.ts +12 -6
  52. package/src/ai/client/live-connection.ts +1 -0
  53. package/src/ai/client/projection.ts +22 -11
  54. package/src/ai/client/transport.ts +4 -0
  55. package/src/ai/code-capability-routes.ts +110 -0
  56. package/src/ai/code-capability-transport.ts +38 -0
  57. package/src/ai/code-mode-skill.ts +114 -0
  58. package/src/ai/code-runtime-tools.ts +166 -0
  59. package/src/ai/code-source-contracts.ts +202 -0
  60. package/src/ai/code-source-tools.ts +145 -0
  61. package/src/ai/compaction.ts +27 -6
  62. package/src/ai/data-analysis-skill.ts +10 -0
  63. package/src/ai/default-tools.ts +25 -2
  64. package/src/ai/dictation-runtime.ts +171 -0
  65. package/src/ai/dictations.ts +188 -0
  66. package/src/ai/draft-content.ts +34 -0
  67. package/src/ai/enrich.ts +6 -0
  68. package/src/ai/executor.ts +191 -31
  69. package/src/ai/file-content-version.ts +22 -0
  70. package/src/ai/file-context.ts +2 -1
  71. package/src/ai/file-media-type.ts +12 -0
  72. package/src/ai/file-reference-contracts.ts +15 -0
  73. package/src/ai/file-tools.ts +2 -1
  74. package/src/ai/files-store.ts +174 -71
  75. package/src/ai/fixtures/vision-encrypted.pdf +0 -0
  76. package/src/ai/grids-skill.ts +40 -10
  77. package/src/ai/http.ts +15 -8
  78. package/src/ai/index.ts +26 -2
  79. package/src/ai/inference-calls.ts +198 -0
  80. package/src/ai/live-events.ts +5 -1
  81. package/src/ai/memory-learning.ts +60 -28
  82. package/src/ai/message-queue.ts +167 -0
  83. package/src/ai/migrate.ts +187 -11
  84. package/src/ai/model-pricing.ts +43 -0
  85. package/src/ai/pdf-render-worker.ts +74 -0
  86. package/src/ai/pdf-render.fixture.ts +28 -0
  87. package/src/ai/pdf-render.ts +77 -0
  88. package/src/ai/projects-routes.ts +3 -3
  89. package/src/ai/projects.ts +20 -6
  90. package/src/ai/protocol.ts +3 -0
  91. package/src/ai/provider.ts +1 -8
  92. package/src/ai/quota-provider.ts +191 -0
  93. package/src/ai/quota-report.ts +152 -0
  94. package/src/ai/quotas-migrate.ts +45 -0
  95. package/src/ai/quotas.ts +168 -0
  96. package/src/ai/routes.ts +215 -11
  97. package/src/ai/run-timeout.ts +10 -0
  98. package/src/ai/runtime-tools.ts +3 -0
  99. package/src/ai/runtime.ts +55 -16
  100. package/src/ai/settings.ts +36 -8
  101. package/src/ai/short-id.ts +2 -2
  102. package/src/ai/skill-catalog.ts +0 -10
  103. package/src/ai/skill-search.ts +47 -0
  104. package/src/ai/skill-seeds.ts +105 -20
  105. package/src/ai/skill-tool.ts +16 -5
  106. package/src/ai/skills-routes.ts +32 -4
  107. package/src/ai/skills.ts +324 -155
  108. package/src/ai/store.ts +373 -191
  109. package/src/ai/stream.ts +5 -0
  110. package/src/ai/structured-runs.ts +4 -3
  111. package/src/ai/structured.ts +8 -1
  112. package/src/ai/system-prompt.ts +12 -2
  113. package/src/ai/timeline.ts +2 -5
  114. package/src/ai/todo-contracts.ts +20 -0
  115. package/src/ai/todo-tool.ts +16 -0
  116. package/src/ai/tool-audit.ts +30 -40
  117. package/src/ai/tools.ts +6 -0
  118. package/src/ai/transcription.ts +202 -0
  119. package/src/ai/turn-timing.ts +114 -0
  120. package/src/ai/types.ts +58 -10
  121. package/src/ai/ui.tsx +2 -0
  122. package/src/ai/usage.ts +118 -118
  123. package/src/ai/vision-tool.ts +39 -10
  124. package/src/api/admin-ai-projects.ts +2 -2
  125. package/src/api/admin-ai-quotas.ts +74 -0
  126. package/src/api/admin-ai-skills.ts +48 -5
  127. package/src/api/admin-ai-usage.ts +2 -2
  128. package/src/api/admin-core-settings.ts +25 -0
  129. package/src/api/admin-identity.ts +91 -51
  130. package/src/api/admin-rail.ts +58 -0
  131. package/src/api/announcements.ts +14 -0
  132. package/src/api/capabilities.ts +292 -43
  133. package/src/api/capability-streams.ts +262 -0
  134. package/src/api/help.ts +8 -44
  135. package/src/api/index.ts +6 -0
  136. package/src/api/mcp.ts +44 -26
  137. package/src/api/me-web-vitals.ts +35 -0
  138. package/src/api/me.ts +2 -0
  139. package/src/api/search/schemas.ts +26 -15
  140. package/src/api/search.bench.ts +1 -1
  141. package/src/api/search.ts +54 -17
  142. package/src/browser/CloudResourceSearch.tsx +640 -702
  143. package/src/browser/app-approval-vault.ts +19 -7
  144. package/src/browser/command-bridge.ts +109 -0
  145. package/src/browser/command-shortcuts.ts +76 -0
  146. package/src/browser/commands.ts +66 -0
  147. package/src/browser/navigation-search.ts +48 -0
  148. package/src/browser/notifications.ts +1 -1
  149. package/src/browser/resource-picker.tsx +5 -18
  150. package/src/browser/resource-search-dialog.ts +9 -0
  151. package/src/browser/resource-search-input.ts +46 -0
  152. package/src/browser/resource-search-messages.ts +76 -40
  153. package/src/browser/resource-search.ts +7 -0
  154. package/src/browser/search-bridge.ts +102 -0
  155. package/src/browser/search-commands.ts +59 -0
  156. package/src/browser/search.ts +13 -0
  157. package/src/browser/spotlight-position.ts +208 -0
  158. package/src/browser/testing.ts +5 -0
  159. package/src/browser/web-vitals.ts +25 -0
  160. package/src/capabilities/claims.ts +179 -0
  161. package/src/capabilities/client.ts +34 -0
  162. package/src/capabilities/command-link.ts +16 -0
  163. package/src/capabilities/executions.ts +298 -0
  164. package/src/capabilities/migrate.ts +81 -0
  165. package/src/capabilities/server.ts +114 -34
  166. package/src/capabilities/stream-body.ts +16 -0
  167. package/src/capabilities/streams.ts +28 -0
  168. package/src/cli/admin/ai-quotas.ts +161 -0
  169. package/src/cli/admin/ai-skills.ts +64 -0
  170. package/src/cli/admin/ai-usage.ts +53 -30
  171. package/src/cli/admin/app-credentials.ts +79 -0
  172. package/src/cli/admin/data.ts +17 -0
  173. package/src/cli/admin/index.ts +9 -0
  174. package/src/cli/capabilities.ts +29 -0
  175. package/src/cli/capability-streams.ts +25 -0
  176. package/src/cli/index.ts +3 -2
  177. package/src/config/env.ts +11 -8
  178. package/src/contracts/app.ts +23 -3
  179. package/src/contracts/capabilities.ts +68 -5
  180. package/src/contracts/capability-streams.ts +46 -0
  181. package/src/contracts/commands.ts +49 -0
  182. package/src/contracts/index.ts +6 -1
  183. package/src/contracts/rail-admin.ts +38 -0
  184. package/src/contracts/rail-preferences.ts +16 -0
  185. package/src/contracts/registry.ts +3 -27
  186. package/src/contracts/settings-types.ts +1 -1
  187. package/src/contracts/shared.ts +9 -5
  188. package/src/contracts/web-vitals.ts +27 -0
  189. package/src/desktop/solid.tsx +3 -3
  190. package/src/index.ts +0 -4
  191. package/src/server/index.ts +3 -0
  192. package/src/server/middleware/auth.ts +3 -2
  193. package/src/server/middleware/route-template.ts +9 -3
  194. package/src/server/middleware/runtime.ts +2 -1
  195. package/src/server/middleware/settings.ts +17 -11
  196. package/src/server/services/access-revision.ts +10 -0
  197. package/src/server/services/access.ts +1 -1
  198. package/src/server/services/index.ts +1 -0
  199. package/src/services/account-category-policy.ts +9 -0
  200. package/src/services/account-lifecycle/audit.ts +1 -1
  201. package/src/services/accounts/app.ts +12 -2
  202. package/src/services/accounts/email-write.ts +23 -0
  203. package/src/services/accounts/groups.ts +15 -4
  204. package/src/services/accounts/identities.ts +249 -0
  205. package/src/services/accounts/identity-reconciliation.ts +87 -0
  206. package/src/services/accounts/ipa-data.ts +2 -2
  207. package/src/services/accounts/local-groups.ts +2 -2
  208. package/src/services/accounts/posix.ts +45 -29
  209. package/src/services/accounts/users.ts +2 -2
  210. package/src/services/announcements/index.ts +69 -8
  211. package/src/services/audit/index.ts +1 -1
  212. package/src/services/cache-fill.ts +35 -0
  213. package/src/services/help/index.ts +109 -0
  214. package/src/services/help/maintenance.ts +25 -0
  215. package/src/services/help/store.ts +180 -0
  216. package/src/services/help/types.ts +46 -0
  217. package/src/services/identity/invocation-actor.ts +2 -2
  218. package/src/services/identity/key-config.ts +2 -1
  219. package/src/services/identity/key-ring.ts +1 -1
  220. package/src/services/index.ts +15 -0
  221. package/src/services/ipa/users.ts +268 -221
  222. package/src/services/legal-consent.ts +1 -1
  223. package/src/services/logging/index.ts +15 -13
  224. package/src/services/logging/trace.ts +2 -1
  225. package/src/services/logging/web-vitals.ts +81 -0
  226. package/src/services/mandates/index.ts +18 -4
  227. package/src/services/mandates/policy.ts +65 -2
  228. package/src/services/notifications/batches.ts +124 -57
  229. package/src/services/notifications/browser.ts +12 -0
  230. package/src/services/notifications/index.ts +0 -2
  231. package/src/services/notifications/platform.ts +0 -4
  232. package/src/services/oauth-tokens.ts +3 -3
  233. package/src/services/pdf/gotenberg.ts +107 -84
  234. package/src/services/pdf/index.ts +3 -0
  235. package/src/services/providers/local/users.ts +25 -16
  236. package/src/services/public-http.ts +101 -0
  237. package/src/services/rail-shortcuts.ts +95 -0
  238. package/src/services/rail-snapshot.ts +53 -0
  239. package/src/services/request-cache-redis.ts +28 -0
  240. package/src/services/session/index.ts +15 -2
  241. package/src/services/session/user.ts +62 -37
  242. package/src/services/settings/core-settings.ts +21 -28
  243. package/src/services/settings/defaults.ts +5 -0
  244. package/src/services/settings/store.ts +58 -84
  245. package/src/shared/ai-costs.ts +42 -0
  246. package/src/shared/ai-platform-prompt.ts +1 -1
  247. package/src/shared/ai-quotas.ts +136 -0
  248. package/src/shared/ai-usage.ts +6 -16
  249. package/src/shared/app-presentation.ts +21 -15
  250. package/src/shared/capability-messages.ts +14 -0
  251. package/src/shared/help.ts +6 -42
  252. package/src/shared/index.ts +6 -0
  253. package/src/ssr/AdminLayout.tsx +7 -5
  254. package/src/ssr/AdminSidebar.tsx +29 -15
  255. package/src/ssr/AppLaunchpad.island.tsx +24 -137
  256. package/src/ssr/AppLaunchpadPanel.tsx +181 -0
  257. package/src/ssr/BrowserPushRegistration.island.tsx +12 -0
  258. package/src/ssr/GlobalSearchDialog.tsx +167 -20
  259. package/src/ssr/GlobalSearchTrigger.island.tsx +33 -22
  260. package/src/ssr/Layout.tsx +17 -6
  261. package/src/ssr/LayoutBreadcrumbs.island.tsx +3 -5
  262. package/src/ssr/LayoutFooter.tsx +1 -1
  263. package/src/ssr/LayoutHeader.tsx +46 -14
  264. package/src/ssr/LayoutHelp.tsx +23 -22
  265. package/src/ssr/{HotkeysHelpRail.island.tsx → LayoutHelpTrigger.island.tsx} +18 -12
  266. package/src/ssr/LayoutRail.tsx +17 -9
  267. package/src/ssr/MobileNavigation.tsx +71 -0
  268. package/src/ssr/MobileProfileActions.tsx +49 -0
  269. package/src/ssr/ProfilePreferences.island.tsx +3 -36
  270. package/src/ssr/RailApps.island.tsx +2 -2
  271. package/src/ssr/RailEditor.tsx +17 -2
  272. package/src/ssr/WorkspaceNavigation.island.tsx +7 -0
  273. package/src/ssr/WorkspaceNavigationProvider.tsx +16 -0
  274. package/src/ssr/admin-navigation.ts +7 -1
  275. package/src/ssr/help.ts +29 -0
  276. package/src/ssr/islands/SearchBar.tsx +67 -0
  277. package/src/ssr/islands/index.ts +3 -1
  278. package/src/ssr/layout-context.ts +2 -2
  279. package/src/ssr/layout-help-search.ts +15 -0
  280. package/src/ssr/mobile-menu-history.ts +70 -0
  281. package/src/ssr/platform-messages.ts +16 -8
  282. package/src/ssr/profile-actions.ts +42 -0
  283. package/src/ssr/rail-context.ts +8 -4
  284. package/src/ssr/rail-messages.ts +2 -0
  285. package/src/ssr/rail-navigation.ts +3 -3
  286. package/src/ssr/workspace-navigation.ts +75 -0
  287. package/src/styles/effects.css +6 -6
  288. package/src/styles/global.css +54 -0
  289. package/src/styles/input.css +43 -41
  290. package/src/styles/resource-search.css +505 -0
  291. package/src/styles/utilities-feedback.css +13 -0
  292. package/src/styles/utilities-layout.css +1 -5
  293. package/src/styles/utilities-navigation.css +3 -39
  294. package/src/types/ambient.d.ts +5 -0
  295. package/src/workflows/ai/runtime.ts +5 -1
  296. package/src/workflows/ai/store.ts +2 -0
  297. package/src/workflows/ai-actions.ts +16 -13
  298. package/src/workflows/definition.ts +10 -5
  299. package/src/workflows/store/actions.ts +44 -20
  300. package/src/workflows/store/index.ts +2 -0
  301. package/src/workflows/store/runs.ts +36 -0
  302. package/src/workflows/store/worker-pool.ts +55 -0
  303. package/src/workflows/store/worker-runtime.ts +90 -0
  304. package/scripts/app-favicon.test.ts +0 -49
  305. package/src/ai/chat/blocks.render.test.tsx +0 -1108
  306. package/src/ai/kit-skill.ts +0 -22
  307. package/src/ai/usage-migrate.ts +0 -81
  308. package/src/browser/CloudResourceSearch.behavior.test.tsx +0 -74
  309. package/src/browser/notification-target.ts +0 -27
  310. package/src/contracts/notification-live.ts +0 -66
  311. package/src/services/notifications/live.ts +0 -50
  312. package/src/ssr/BrowserNotifications.island.tsx +0 -135
  313. package/src/ssr/GlobalSearchDialog.behavior.test.tsx +0 -96
  314. package/src/ssr/Layout.render.test.tsx +0 -148
  315. package/src/ssr/islands/SearchBar.island.tsx +0 -80
@@ -0,0 +1,202 @@
1
+ import { AiFileLocation, AiFileReference } from "./file-reference-contracts";
2
+ import { z } from "zod";
3
+ import { CodeResourceId } from "./browser-code-contracts";
4
+ import { PrincipalSchema } from "../contracts/shared";
5
+
6
+ // Flat Assistant tool inputs. The owning service also validates its domain contracts.
7
+ const Id = z.object({ id: CodeResourceId }).strict();
8
+ const Page = z.number().int().min(1).max(100000).default(1);
9
+ const ArtifactPath = z
10
+ .string()
11
+ .min(1)
12
+ .max(180)
13
+ .regex(/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/)
14
+ .refine((path) => path.split("/").every((part) => part !== "." && part !== ".."));
15
+ const ArtifactFile = z
16
+ .object({
17
+ path: ArtifactPath,
18
+ content: z
19
+ .string()
20
+ .max(1024 * 1024)
21
+ .describe("Complete source file content; read existing content before replacing it."),
22
+ })
23
+ .strict();
24
+ const Icon = z
25
+ .string()
26
+ .regex(/^ti ti-[a-z0-9-]+$/)
27
+ .max(80);
28
+ const ArtifactMetadata = z
29
+ .object({
30
+ title: z.string().trim().min(1).max(120).optional(),
31
+ description: z.string().trim().max(500).optional(),
32
+ icon: Icon.optional(),
33
+ })
34
+ .strict();
35
+ const ArtifactCreate = ArtifactMetadata.required({ title: true });
36
+ const PublicationNote = z.string().trim().min(1).max(1000);
37
+ const DatabaseSql = z.object({
38
+ sql: z.string().trim().min(1).max(16000).describe("Read-only SELECT; no writes, CTEs or comments. Use LIMIT."),
39
+ params: z.array(z.json()).max(1000).default([]),
40
+ });
41
+
42
+ const CodeWriteInput = Id.extend({
43
+ expectedRevision: z.number().int().positive(),
44
+ entry: ArtifactPath.optional(),
45
+ files: z.array(z.union([ArtifactFile, z.object({ path: ArtifactPath, fromFile: AiFileReference }).strict()])).min(1).max(64),
46
+ });
47
+
48
+ export const CODE_SOURCE_TOOLS = {
49
+ code_files: {
50
+ description: "List authorized files in one explicit chat, Project or App shared store. Returns locations, metadata and nextAfter. Use code_file_stat to obtain the opaque version before copying; does not load bytes into model context.",
51
+ input: AiFileLocation.omit({ path: true }).extend({ after: z.string().max(500).default(""), limit: z.number().int().min(1).max(1000).default(100) }),
52
+ },
53
+ code_file_stat: {
54
+ description: "Inspect one authorized file location. Returns exists plus its exact versioned reference, size and mediaType, never its bytes. App files require Use, Project files Read, chats ownership.",
55
+ input: z.object({ file: AiFileLocation }).strict(),
56
+ },
57
+ code_file_copy: {
58
+ description: "Copy one exact file version between chat, Project and App shared stores with fresh review. Source bytes never enter tool output. App destination requires Use, Project destination Write, chat destination ownership. Set expectedVersion null only for a new destination; otherwise use its version from code_file_stat. Source/version, target rights, overwrite and byte limits are rechecked. This grants no access to other files.",
59
+ review: true,
60
+ input: z.object({ source: AiFileReference, destination: AiFileLocation, expectedVersion: z.string().min(1).max(128).nullable() }).strict(),
61
+ },
62
+ code_database_export: {
63
+ description: "Export an App database backup into the current chat as a file. Manage required. Returns the actual path/version; no backup bytes enter tool output. Never overwrites an existing file. The chat file-size/storage limits apply. This is a Studio backup operation, not access to vendor APIs.",
64
+ input: Id.extend({ path: z.string().startsWith("/").max(240).default("/database.sqlite").describe("New chat filename; an existing path is rejected. Choose another name after a conflict.") }),
65
+ },
66
+ code_manage_read: {
67
+ description: "Read an App management snapshot before deletion: title, source revision, publication, file/JSON counts, database connection and managementRevision. Manage required. Does not expose another user's credentials or database server internals.", input: Id,
68
+ },
69
+ code_delete: {
70
+ description: "Permanently delete an App, all source history, publications, grants and server data with fresh review. Read code_manage_read first. Database physical cleanup is queued, not claimed finished. Cannot delete an App that changed since review.", review: true,
71
+ input: Id.extend({ expectedManagementRevision: z.string().regex(/^[a-f0-9]{64}$/) }),
72
+ },
73
+ code_database_read: {
74
+ description: "Read App database connection status, generation, dataRevision and aggregate overview. Manage required; does not create a database. These are Studio contracts, not access to the backing service API.",
75
+ input: Id,
76
+ },
77
+ code_database_clear: {
78
+ description: "Permanently clear all table rows with fresh review while preserving schema, source, files and JSON storage. Manage required. Read code_database_read first. Returns completed and clearedTables; partial failure is explicit and cannot be blindly retried.",
79
+ review: true,
80
+ input: Id.extend({ expectedGeneration: z.string().regex(/^[a-f0-9]{64}$/), expectedDataRevision: z.uuid() }),
81
+ },
82
+ code_database_reset: {
83
+ description: "Disconnect and permanently discard an App database, including schema, with fresh review. Preserves source, publications and files/JSON storage. Next explicit connection creates an empty database; physical deletion is queued. Read code_database_read first. Never use as a routine query fix.",
84
+ review: true,
85
+ input: Id.extend({ expectedGeneration: z.string().regex(/^[a-f0-9]{64}$/).nullable(), expectedDataRevision: z.uuid().nullable() }),
86
+ },
87
+ code_storage_list: {
88
+ description: "Inspect an App's shared files or JSON keys for administration. Manage required. Returns storageRevision, counts and a page of key/bytes/mediaType/version metadata; no file contents. Follow nextAfter.",
89
+ input: Id.extend({ area: z.enum(["files", "kv"]), after: z.string().max(240).default(""), limit: z.number().int().min(1).max(1000).default(100) }),
90
+ },
91
+ code_storage_delete: {
92
+ description: "Delete one shared file/JSON key, or clear an explicit storage area, with fresh user review. Manage required. Source, publications and database are preserved. Read code_storage_list first.",
93
+ review: true,
94
+ input: Id.extend({ area: z.enum(["files", "kv", "all"]), key: z.string().min(1).max(240).optional().describe("Delete this exact key; omit to clear the entire area. Not valid with area all."), expectedStorageRevision: z.number().int().positive().describe("storageRevision from code_storage_list; concurrent writes invalidate the review.") }).refine(input => input.area !== "all" || input.key === undefined, "all clears both areas and cannot select a key"),
95
+ },
96
+ code_access_read: {
97
+ description: "Read an App's current grants and accessRevision before changing access. Manage required. App Use is read; Manage is admin. Skill access is separate.",
98
+ input: Id,
99
+ },
100
+ code_access_change: {
101
+ description: "Grant, change or revoke one App permission with fresh user review. Read code_access_read first. Sharing a referenced Skill is a separate operation.",
102
+ review: true,
103
+ input: Id.extend({
104
+ expectedAccessRevision: z.string().regex(/^[a-f0-9]{64}$/).describe("Exact accessRevision returned by code_access_read."),
105
+ principal: PrincipalSchema.refine(principal => principal.type !== "service_account", "Studio Apps support user, group, authenticated or public grants.").optional().describe("New user or group from core.entities.search, authenticated, or public (read/run only, no server data). Service accounts are unsupported. Supply principal OR accessId."),
106
+ accessId: z.uuid().optional().describe("Existing grant ID from code_access_read; supply accessId OR principal."),
107
+ permission: z.enum(["read", "admin"]).nullable().describe("read means Use, admin means Manage; null removes an existing accessId."),
108
+ }).refine(input => Number(input.principal !== undefined) + Number(input.accessId !== undefined) === 1
109
+ && (input.principal === undefined || input.permission !== null), "Supply principal with permission OR accessId with permission (null removes)")
110
+ .refine(input => input.principal?.type !== "public" || input.permission === "read", "Public Apps only support read/run access"),
111
+ },
112
+ code_actions: {
113
+ description: "Discover a visible App's currently published actions and their complete input/output JSON Schemas without running code. Returns publishedVersion for code_action. Requires Use; no draft source or management tools are loaded.",
114
+ input: Id.extend({ draft: z.boolean().default(false).describe("Inspect current draft actions instead of the publication; Manage required.") }),
115
+ },
116
+ code_sql: {
117
+ description:
118
+ "Run a read-only SELECT directly against an App database without writing code. Supply its id and parameterized SQL. Does not create or connect a database. Requires current resource access; Project access applies only in that Project chat. Narrow columns and add LIMIT for large results.",
119
+ input: Id.extend(DatabaseSql.shape),
120
+ },
121
+ code_versions: {
122
+ description: "List numbered published versions with notes, author and date. Admin only. Separate from automatic file-save history.",
123
+ input: Id.extend({ page: Page }),
124
+ },
125
+ code_list: {
126
+ description:
127
+ "Find accessible Apps, including published Project Apps in the current authorized Project chat. Reuse the intended resource instead of creating duplicates.",
128
+ input: z
129
+ .object({
130
+ page: Page,
131
+ q: z.string().max(120).optional().describe("Find by title or description; matches only metadata you may access."),
132
+ })
133
+ .strict(),
134
+ },
135
+ code_read: {
136
+ description:
137
+ "Read the current file, or omit path for the directory. Follow nextOffset for long files. revision is optional and only needed to inspect history.",
138
+ input: Id.extend({
139
+ path: ArtifactPath.optional().describe("Exact relative file path. Omit to list files."),
140
+ offset: z.number().int().min(0).default(0).describe("UTF-16 offset; follow nextOffset for the remaining content."),
141
+ revision: z.number().int().positive().optional().describe("Historical revision from code_history. Omit for current files."),
142
+ }),
143
+ },
144
+ code_history: {
145
+ description: "List previous saved versions. Use code_read with a returned revision only when historical source is needed.",
146
+ input: Id.extend({ page: Page }),
147
+ },
148
+ code_fork: {
149
+ description:
150
+ "Create a private editable copy of an accessible publication. Source is copied; shared data, database and Project associations are not. Project-only access does not permit forks.",
151
+ input: Id,
152
+ },
153
+ code_publish: {
154
+ description:
155
+ "Publish tested working source as the next numbered version. A concise change note is required. Never changes sharing. Read current revision first; a concurrent edit causes a conflict.",
156
+ input: Id.extend({
157
+ expectedRevision: z
158
+ .number()
159
+ .int()
160
+ .positive()
161
+ .describe("Current working revision from code_read; prevents conflicting publication or restore."),
162
+ note: PublicationNote,
163
+ }),
164
+ },
165
+ code_unpublish: {
166
+ description: "Withdraw the current App publication with fresh review. Use code_manage_read first. Preserves source, publication history and data; ordinary Use-level callers can no longer start this App or its actions.",
167
+ review: true,
168
+ input: Id.extend({ expectedPublishedVersion: z.number().int().positive() }),
169
+ },
170
+ code_restore: {
171
+ description:
172
+ "Restore a published version including title, description and icon as the working source and a new latest publication, atomically. Automatically records Restore version X. Preserves publication history and user data; do not call code_publish again.",
173
+ input: Id.extend({
174
+ version: z.number().int().positive().describe("Publication number returned by code_versions."),
175
+ expectedRevision: z
176
+ .number()
177
+ .int()
178
+ .positive()
179
+ .describe("Current working revision from code_read; prevents conflicting publication or restore."),
180
+ }),
181
+ },
182
+ code_update: {
183
+ description: "Change working title, description or Tabler icon. Does not publish. Use e.g. ti ti-calculator or ti ti-chart-bar.",
184
+ input: Id.extend(ArtifactMetadata.shape),
185
+ },
186
+ code_create: {
187
+ description:
188
+ "Create a private reusable App with an optional UI, published actions and optional persistence. For one-off analysis, use code_run with code instead. Returns id and entry path; write source with code_write. Optional icon uses the complete class, e.g. ti ti-chart-bar; omit it when unsure. Does not run or share anything.",
189
+ input: ArtifactCreate.pick({ title: true, description: true, icon: true }),
190
+ },
191
+ code_write: {
192
+ description: "Atomically save complete source files against expectedRevision from code_read/create. Other files stay unchanged. Returns revision and compiler diagnostics; never runs. fromFile imports one exact chat/Project/App file reference as UTF-8 source without printing bytes. File imports receive fresh review because source may be shared or published. Use code_file_stat first; source file and bundle byte limits apply.",
193
+ review: (input: unknown) => CodeWriteInput.parse(input).files.some(file => "fromFile" in file),
194
+ input: CodeWriteInput,
195
+ },
196
+ code_remove: {
197
+ description:
198
+ "Remove one source file, saving immediately. Source history is retained for recovery; does not delete the app. Removing an absent file is harmless. Returns diagnostics for any broken imports.",
199
+ input: Id.extend({ path: ArtifactPath.describe("Exact relative path of the file to remove.") }),
200
+ },
201
+ } as const;
202
+ export type CodeSourceToolName = keyof typeof CODE_SOURCE_TOOLS;
@@ -0,0 +1,145 @@
1
+ import { z } from "zod";
2
+ import {
3
+ capabilityIdempotencyKeyHash,
4
+ capabilityRequestHash,
5
+ claimCapabilityIdempotency,
6
+ completeCapabilityClaim,
7
+ markCapabilityClaimUncertain,
8
+ } from "../capabilities/claims";
9
+ import { getApp } from "../_internal/registry";
10
+ import { readBoundedJson } from "../_internal/bounded-json";
11
+ import { withActiveIdentitySigner } from "../services/identity/key-ring";
12
+ import { signInvocationToken } from "../services/identity/invocation-token";
13
+ import { LOCALE_HEADER } from "../shared/locale";
14
+ import { CODE_SOURCE_TOOLS, type CodeSourceToolName } from "./code-source-contracts";
15
+ import { resolveAiCapabilityActor } from "./capability-execution";
16
+ import { aiConversations } from "./store";
17
+ import { defineAiTool } from "./tools";
18
+
19
+ const WRITE_TOOLS = new Set(["code_create", "code_write", "code_remove", "code_update", "code_fork", "code_publish", "code_restore", "code_database_export", ...Object.entries(CODE_SOURCE_TOOLS).filter(([, definition]) => "review" in definition && definition.review).map(([name]) => name)]);
20
+
21
+ const Reply = z.discriminatedUnion("ok", [
22
+ z.object({ ok: z.literal(true), data: z.unknown() }),
23
+ z.object({ ok: z.literal(false), error: z.object({ code: z.string(), message: z.string() }) }),
24
+ ]);
25
+
26
+ /** Direct server tools: discovery exposes code_*; Assistant owns the resource services. */
27
+ export function createCodeSourceTool(name: CodeSourceToolName) {
28
+ const definition = CODE_SOURCE_TOOLS[name];
29
+ return defineAiTool({
30
+ name,
31
+ description:
32
+ definition.description +
33
+ (WRITE_TOOLS.has(name) ? " If a write has an unknown outcome, inspect current state before attempting another write." : ""),
34
+ inputSchema: definition.input,
35
+ outputSchema: z.unknown(),
36
+ approval: "never",
37
+ }).server(async (input, context) => {
38
+ if (!context.conversationId) throw new Error("Code tools require an Assistant conversation.");
39
+ const { actor } = await resolveAiCapabilityActor({
40
+ conversationId: context.conversationId,
41
+ persistedActor: context.actor,
42
+ store: aiConversations,
43
+ });
44
+ const app = await getApp("assistant");
45
+ if (!app) throw new Error("Assistant is unavailable.");
46
+ const signal = context.signal;
47
+ const send = async (review = false) => {
48
+ const signed = await withActiveIdentitySigner(
49
+ "invocation",
50
+ (signer) =>
51
+ signInvocationToken({
52
+ targetAppId: "assistant",
53
+ callingAppId: "core",
54
+ operation: `tool:${name}`,
55
+ schemaHash: null,
56
+ authority: {
57
+ sub: actor.user.id,
58
+ principal_type: "user",
59
+ access_subject_type: "user",
60
+ access_subject_id: actor.user.id,
61
+ credential_kind: "session",
62
+ scopes: [],
63
+ },
64
+ signer,
65
+ issuer: signer.issuer,
66
+ }),
67
+ { signal, timeoutMs: 5000 },
68
+ );
69
+ const headers = new Headers({ authorization: `Bearer ${signed.token}`, "content-type": "application/json" });
70
+ if (context.locale) headers.set(LOCALE_HEADER, context.locale);
71
+ const response = await fetch(new URL(`/_internal/assistant/tools/${name}`, app.baseUrl), {
72
+ method: "POST",
73
+ headers,
74
+ redirect: "manual",
75
+ signal,
76
+ body: JSON.stringify({ input, conversationId: context.conversationId, ...(review ? { review: true } : {}) }),
77
+ });
78
+ const parsed = await readBoundedJson(response, 256 * 1024);
79
+ if (!parsed.ok) throw new Error("Invalid Assistant tool response. A write may have completed; inspect its state before retrying.");
80
+ const reply = Reply.safeParse(parsed.data);
81
+ if (!reply.success) throw new Error("Assistant tool request failed. Inspect resource state before retrying a write.");
82
+ if (!reply.data.ok) throw new Error(`${reply.data.error.code}: ${reply.data.error.message}`);
83
+ if (!response.ok) throw new Error("Assistant tool request failed.");
84
+ return { data: reply.data.data, status: response.status };
85
+ };
86
+ if ("review" in definition && (typeof definition.review === "function" ? definition.review(input) : definition.review)) {
87
+ const preview = z.object({ data: z.object({ message: z.string().min(1) }) }).parse((await send(true)).data).data;
88
+ if (!await context.requestApproval(preview.message)) throw new Error("The user declined this change. No mutation was sent.");
89
+ }
90
+ // Reuse the platform replay guard; these tools are not registered capabilities.
91
+ const claim = WRITE_TOOLS.has(name)
92
+ ? {
93
+ appId: "assistant",
94
+ capability: `tool:${name}`,
95
+ principal: `user:${actor.user.id}`,
96
+ keyHash: capabilityIdempotencyKeyHash(`${context.conversationId}:${context.callId}`),
97
+ }
98
+ : null;
99
+ if (claim) {
100
+ if (!context.callId) throw new Error("A write requires a tool call ID.");
101
+ const state = await claimCapabilityIdempotency(claim, capabilityRequestHash(input));
102
+ if (state.state === "replay")
103
+ throw new Error("This write already completed. Use code_list or code_read to inspect current state; do not repeat the write.");
104
+ if (state.state !== "claimed")
105
+ throw new Error(`Write outcome ${state.state}; inspect current state before attempting another write.`);
106
+ }
107
+ try {
108
+ const response = await send();
109
+ if (claim) await completeCapabilityClaim(claim, response.status, response.data);
110
+ return response.data;
111
+ } catch (error) {
112
+ if (claim) await markCapabilityClaimUncertain(claim);
113
+ throw error;
114
+ }
115
+ });
116
+ }
117
+
118
+ export const createCodeSourceTools = () => [
119
+ createCodeSourceTool("code_files"),
120
+ createCodeSourceTool("code_file_stat"),
121
+ createCodeSourceTool("code_file_copy"),
122
+ createCodeSourceTool("code_database_export"),
123
+ createCodeSourceTool("code_manage_read"),
124
+ createCodeSourceTool("code_delete"),
125
+ createCodeSourceTool("code_database_read"),
126
+ createCodeSourceTool("code_database_clear"),
127
+ createCodeSourceTool("code_database_reset"),
128
+ createCodeSourceTool("code_storage_list"),
129
+ createCodeSourceTool("code_storage_delete"),
130
+ createCodeSourceTool("code_access_read"),
131
+ createCodeSourceTool("code_access_change"),
132
+ createCodeSourceTool("code_actions"),
133
+ createCodeSourceTool("code_sql"),
134
+ createCodeSourceTool("code_versions"),
135
+ createCodeSourceTool("code_list"),
136
+ createCodeSourceTool("code_read"),
137
+ createCodeSourceTool("code_history"),
138
+ createCodeSourceTool("code_fork"),
139
+ createCodeSourceTool("code_publish"),
140
+ createCodeSourceTool("code_restore"),
141
+ createCodeSourceTool("code_update"),
142
+ createCodeSourceTool("code_create"),
143
+ createCodeSourceTool("code_write"),
144
+ createCodeSourceTool("code_remove"),
145
+ ];
@@ -89,6 +89,23 @@ const findLoopSplitIndex = (entries: StoreEntry[], keepLoops: number): number =>
89
89
  return -1;
90
90
  };
91
91
 
92
+ /** Preserve recent complete rounds, retaining one when the first loop has only two. */
93
+ const findRoundSplitIndex = (entries: StoreEntry[]): number => {
94
+ const rounds = entries.flatMap((entry, index) => entry.message.role === "assistant" && entry.kind === "message" ? [index] : []);
95
+ if (!rounds.length) return -1;
96
+ const candidate = rounds.length === 1 ? entries.length : rounds[rounds.length - (rounds.length > 2 ? 2 : 1)]!;
97
+ const pending = new Set<string>();
98
+ let safe = -1;
99
+ for (let index = 0; index < candidate; index++) {
100
+ const message = entries[index]!.message;
101
+ if (message.role === "assistant") {
102
+ for (const block of message.content) if (block.type === "tool_call") pending.add(block.id);
103
+ } else if (message.role === "tool_result") pending.delete(message.callId);
104
+ if (pending.size === 0) safe = index + 1;
105
+ }
106
+ return safe;
107
+ };
108
+
92
109
  const buildCompactionPrompt = (additionalInstructions: string, source: string) => ({
93
110
  systemPrompt: buildAiTaskPrompt({
94
111
  baseInstructions: DEFAULT_COMPACTION_PROMPT,
@@ -113,13 +130,16 @@ export const createCloudCompactFn = (input: {
113
130
  keepRecentLoops?: number;
114
131
  }): CompactFn => {
115
132
  return (ctx) => {
116
- if (!ctx.force && (typeof ctx.fillRatio !== "number" || ctx.fillRatio < COMPACTION_FILL_RATIO)) return null;
133
+ const window = ctx.provider.contextWindow;
134
+ const reserve = input.maxOutputTokens ?? 0;
135
+ const fillRatio = typeof ctx.fillRatio === "number" && window && window > reserve
136
+ ? ctx.fillRatio * window / (window - reserve) : ctx.fillRatio;
137
+ if (!ctx.force && (typeof fillRatio !== "number" || fillRatio < COMPACTION_FILL_RATIO)) return null;
117
138
 
118
139
  const totalLoops = countConversationLoops(ctx.entries);
119
- const keepLoops = input.keepRecentLoops ?? keepLoopsForFillRatio(ctx.fillRatio, totalLoops);
120
- if (totalLoops <= keepLoops) return null;
121
-
122
- const splitIndex = findLoopSplitIndex(ctx.entries, keepLoops);
140
+ const keepLoops = input.keepRecentLoops ?? keepLoopsForFillRatio(fillRatio, totalLoops);
141
+ const loopSplit = totalLoops > keepLoops ? findLoopSplitIndex(ctx.entries, keepLoops) : -1;
142
+ const splitIndex = loopSplit > 0 ? loopSplit : findRoundSplitIndex(ctx.entries);
123
143
  if (splitIndex < 1) return null;
124
144
 
125
145
  const sourceEntries = ctx.entries.slice(0, splitIndex);
@@ -162,6 +182,7 @@ export const createCloudCompactFn = (input: {
162
182
 
163
183
  await aiConversations.compactMessages({
164
184
  conversationId: input.conversationId,
185
+ turnId: input.turnId,
165
186
  checkpointSeq: checkpoint.seq,
166
187
  modelProfileId: input.modelProfileId,
167
188
  summary: {
@@ -179,4 +200,4 @@ export const createCloudCompactFn = (input: {
179
200
  };
180
201
  };
181
202
 
182
- export const __compactionTest = { countConversationLoops, findLoopSplitIndex, keepLoopsForFillRatio };
203
+ export const __compactionTest = { countConversationLoops, findLoopSplitIndex, findRoundSplitIndex, keepLoopsForFillRatio };
@@ -0,0 +1,10 @@
1
+ // Generated by packages/assistant/scripts/generate-code-mode-skill.ts.
2
+ import type { AiSkillTemplate } from "./skills";
3
+ export const ASSISTANT_DATA_ANALYSIS_SKILL = {
4
+ "key": "assistant:data-analysis",
5
+ "version": 6,
6
+ "name": "assistant-data-analysis",
7
+ "description": "Analyze source data, explain metrics and comparisons, and build evidence-backed reports or interactive dashboards in Assistant Code Mode. Use for multi-step analysis, data exploration, and dashboards; a simple chart only needs the Code Mode charts reference.",
8
+ "instructions": "# Analyze data and deliver an inspectable result\n\nStart with the question the reader needs to answer. Choose a direct answer,\nan interactive visualization in this chat, an exported file, or a reusable Studio app accordingly.\nFor a one-time visual analysis, prefer a chat visualization; filters and buttons\ndo not by themselves require a Studio App.\nLoad `assistant-code-mode` for execution and read its `references/analytics.md`\nfor the built-in UI. Loading this skill does not install a library or grant access.\n\n## Keep a working plan\n\nFor work with several real steps, use `todo_write` to keep a short chat plan.\nReplace the full `todos` list each time; give each item a stable `id`, actionable\n`content`, and `status` (`pending`, `in_progress`, `completed`, or `cancelled`).\nAt most one step is active. Update as work changes, including user corrections;\nmark a step completed only after doing and checking it. Preserve exact commands\nwhen they matter. Skip this tool for a simple calculation or conversational reply.\n\nFor analysis, useful steps are reconcile source data, build the analysis, and\nverify totals, filters and conclusions. A rendered dashboard alone is not proof\nthat its numbers are correct. Keep blocked source work open and explain why.\n\n## Establish the data\n\nIdentify the actual source, unit of observation, time window, timezone, and\nlatest complete period. Read files or discover the relevant Cloud capabilities\nbefore selecting fields. External APIs use `http.fetch`; credentials are entered\nonly through the trusted `code_secret` dialog.\n\nInspect a bounded sample, missing values, duplicate keys, types, and coverage.\nReconcile totals and join cardinalities before drawing conclusions. Keep raw\nnumbers separate from display formatting. Distinguish zero from unavailable data;\nstate exclusions and denominator choices. Do not substitute fixture data for a\nblocked source unless the user requested a mockup.\n\nKeep the source query or transformation in the saved source or an accompanying\nfile so another run can reproduce the result. Preserve the source identity and\nretrieval timestamp, without credentials or credential-bearing URLs.\n\n## Build one consistent analysis\n\nDerive charts, metrics, and tables from the same reviewed data. Aggregate large\ninputs before crossing the UI bridge. Chart Explorer rows identify selectable\nentities with stable string keys; derived bins and groups need explicit mark\nmappings. Shared keys across charts mean the same entity, not equal values.\n\nChoose the simplest chart that answers the question. Use tables for exact\nrecords, bars for category comparisons, lines for ordered trends, and distributions\nfor spread. State units, comparison windows, and whether a percent is a fraction\nor an already scaled number. Do not imply causation from correlation.\n\nLead reports with the finding, then supporting evidence and limitations.\nLead dashboards with the important measurements, then trends and diagnostic\nbreakdowns. Use shared filters only when they affect all claimed views. Keep the\ninitial view useful without interaction. Avoid unrelated metrics added merely to\nfill a grid.\n\nAttach source context to Explorer data: `mode`, `asOf`, `sources`, and relevant\n`status`/`note`. A timestamp records when the data was retrieved; it does not prove\nthat the upstream source is complete. Label partial or fixture data visibly.\n\n## Validate before delivery\n\nRun the actual source with `code_run`. Inspect the result; use `code_interact`\nwith structured UI events to test filters, chart/table switching, selection,\nempty results, and recovery from a failed load. Reconcile displayed values with\nthe reviewed totals and check that filters describe the data actually displayed.\nA successful schema validation does not establish analytical correctness.\n\nValidate the actual presented source (the saved revision for Apps), rather than pasting its formulas into a\nsecond test script. Keep an independent expectation from the input data: row\ncounts, unmatched joins, totals and representative boundary cases. For targets,\nstate their grain (for example month × region) and aggregate each target once;\nmultiple selected regions must sum their distinct targets. Compare inspected raw\nKPI values and plotted series with independent expectations. A formatted value\nmatching after rounding does not validate the raw ratio. Never round fractions\nbefore passing them to percent-formatted controls. Preserve precision\nuntil display formatting. Test reset, one/multiple/all selections, empty results,\nand complete versus partial periods. A newly generated timestamp is not source\nfreshness: keep the real retrieval or file-snapshot timestamp stable.\n\nFor a Studio App data snapshot, export the validated dataset with `files.save` and\n`code_export`, then copy its exact path/version into the resource with\n`code_write({id,expectedRevision,files:[{path:\"data.json\",fromFile:reference}]})`.\nObtain the exact reference with `code_file_stat`; importing private files into\nApp source receives fresh review.\nImport that file in the app. Never rebuild a truncated dataset by copying tool\noutput. Keep transformations and source identity alongside the snapshot.\n\nHuman approval and uncertain HTTP outcomes follow the Code Mode HTTP contract.\nDo not replay an external mutation to refresh a chart. Separate local filtering\nfrom external loading; an Apply button can avoid a request for every slider move.\n\n## Save, share, and hand off\n\nFor chat visualizations, test `code_run` and relevant `code_interact` controls,\nthen deliver with `code_present({runId,title})`. A successful run alone is not\nvisible to the user. Retain source identity, reviewed input data and their real\nretrieval timestamp. Put writes and external reloads behind explicit buttons;\nopening an old result must not repeat earlier actions. The user can download the\ncurrent view as PDF/HTML or an individual chart as SVG.\n\nFor reusable Studio Apps, reuse one Cloud resource for later revisions of the same report or dashboard.\nSave its source, test that revision, and use the normal Code Mode publication\nworkflow when publication is requested. Publishing a version and granting reader\naccess are separate operations. Preserve existing access; a dashboard request\ndoes not authorize broadening it. Personal secrets are never copied to readers.\n\nA published source version is not automatically a frozen data snapshot. A frozen\nreport must retain the reviewed data explicitly in its authorized resource or\noutput file. A live app must implement its loader and display the retrieval time;\nloading once is not continuous monitoring. No background refresh exists unless\nimplemented through an appropriate supported workflow.\n\nPresent the chat visualization, resource link or exported file, the data timestamp, and material\ncoverage limitations. Say whether it is a snapshot or reloads from its sources.\nIf publication fails, retain the tested resource and report the failed stage;\ndo not claim success or create a different public destination. Sites-specific\nhosting, access policies, and editor storage are not part of this Cloud workflow.",
9
+ "extraFrontmatter": {}
10
+ } satisfies AiSkillTemplate;
@@ -1,3 +1,9 @@
1
+ import { createAiTodoTool } from "./todo-tool";
2
+ import { runManagedCodeTool } from "./code-runtime-tools";
3
+ import { CODE_SOURCE_TOOLS } from "./code-source-contracts";
4
+ import { createCodeSourceTools } from "./code-source-tools";
5
+ import { CODE_RUNTIME_TOOL_NAMES, CodeActionInput, CodeRunInput, CodeInspectInput, CodeInteractInput, CodeStopInput, CodeOpenInput, CodeExportInput, CodePresentInput, CodeSecretInput } from "./browser-code-contracts";
6
+ import { z } from "zod";
1
7
  import {
2
8
  CloudAiCardInputSchema,
3
9
  CloudAiCardOutputSchema,
@@ -20,6 +26,7 @@ import { createCloudAiWebExtractTool, createCloudAiWebSearchTool, isCloudAiFirec
20
26
  import { createCloudAiMarkdownToPdfTool } from "./markdown-pdf-tool";
21
27
  import { defineAiTool } from "./tools";
22
28
  import type { AiDataBoundary, AiRuntimeTool } from "./types";
29
+ import { createCloudAiTranscribeAudioTool } from "./audio-tool";
23
30
  import { createCloudAiViewImageTool } from "./vision-tool";
24
31
 
25
32
  export {
@@ -87,10 +94,24 @@ export const createCloudAiLocalBashTool = () =>
87
94
  "use local_bash only when work on the user's local CLI computer is necessary; every command requires local confirmation and its result must be checked.",
88
95
  }).client();
89
96
 
90
- export const createDefaultCloudAiTools = () => [createCloudAiSurveyTool(), createCloudAiTextEditorTool()];
97
+ export const createCloudAiCodeTools = () => [
98
+ defineAiTool({name:"code_secret",description:"Open a trusted Secret input dialog. The user enters the value directly into encrypted Assistant storage; only configured/name returns. Never ask for a credential in chat, survey, app controls or code_interact. Personal secrets are scoped to this chat or resource and bound to the exact HTTPS origin, header and prefix. Use secret(name,{prefix}) in http.fetch headers; load assistant-code-mode for HTTP details. Web UI required for secret entry; stored secrets also work from CLI.",inputSchema:CodeSecretInput,outputSchema:z.object({configured:z.boolean(),name:z.string()}),approval:"never"}).client(),
99
+ defineAiTool({ name: "code_action", description: "Call one published Studio App action using its exact discovered name, publication and input schema. Discover with code_actions first. Use permission is sufficient; draft and management access are not granted. Runtime effects and approvals are real. Never repeat an uncertain mutation blindly.", inputSchema: CodeActionInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_action")),
100
+ defineAiTool({ name: "code_run", promptHint: "For file analysis, data transformations or combining Cloud data, run a short one-off script with code_run. Load assistant-code-mode for its runtime APIs; no saved app is required.", description: "Run a saved resource id OR one-off code in the isolated worker. Optional resourceId binds one-off code to existing app data (Manage required), without editing its source. Includes capabilities.run(name,input) to chain Cloud capabilities in JavaScript; load assistant-code-mode for its runtime APIs. Scripts accept current chat inputPaths; app test runs use them only as explicit picker fixtures. Returns output, logs and UI state for agent inspection only; use code_present to show a one-off visualization to the user. Local test storage is temporary; shared data, database writes and capability effects are real and keep normal permissions and approvals.", inputSchema: CodeRunInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_run")),
101
+ defineAiTool({ name: "code_inspect", description: "Inspect a test run: errors, logs, output, controls and pending modal. Use nodeId to inspect table rows or list items; follow pagination only as needed.", inputSchema: CodeInspectInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_inspect")),
102
+ defineAiTool({ name: "code_interact", description: "Operate a control or answer a pending modal using its exact snapshot ID. Buttons need only id; controls use event:{type:change,value:...} or event:{type:select,key:...}. Use answer for modal replies, or answer:null to cancel. Copy an interactions example from code_inspect; never send JSON as a string. Use steps:[{id,event?},...] for up to three known sequential interactions; stops on errors, modals or background work. Returns one resulting state with completedSteps and nextStep.", inputSchema: CodeInteractInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_interact")),
103
+ defineAiTool({ name: "code_stop", description: "Stop and release an isolated test run.", inputSchema: CodeStopInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_stop")),
104
+ defineAiTool({ name: "code_open", description: "Show the app beside the chat without starting it. For one-off calculations, return the result instead of opening an app.", inputSchema: CodeOpenInput, outputSchema: z.json(), approval: "never" }).client(),
105
+ defineAiTool({ name: "code_present", description: "Present a successful one-off run as a persistent interactive visualization in this chat. Requires code_run with code, without resourceId or saved app id. Saves source, selected inputs and UI preview. Users can activate controls and download the current view. Test runs are not visible until this succeeds. For reusable apps use code_open instead.", inputSchema: CodePresentInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_present")),
106
+ defineAiTool({ name: "code_export", description: "Copy a captured output file from a test run into the chat. Returns a path for normal file tools and presentation.", inputSchema: CodeExportInput, outputSchema: z.json(), approval: "never" }).server(runManagedCodeTool("code_export")),
107
+ ];
108
+
109
+ export const createDefaultCloudAiTools = () => [createAiTodoTool(), createCloudAiSurveyTool(), createCloudAiTextEditorTool()];
91
110
 
92
111
  /** Built-ins advertised through discovery and loaded only when needed. */
93
- export const CLOUD_AI_DEFERRED_BUILTIN_TOOL_NAMES = new Set([
112
+ export const CLOUD_AI_DEFERRED_BUILTIN_TOOL_NAMES = new Set<string>([
113
+ ...CODE_RUNTIME_TOOL_NAMES,
114
+ ...Object.keys(CODE_SOURCE_TOOLS),
94
115
  "survey",
95
116
  "text_editor",
96
117
  "list_files",
@@ -108,6 +129,7 @@ export const createConfiguredDefaultCloudAiTools = async (config?: {
108
129
  }) => {
109
130
  const tools: AiRuntimeTool[] = [
110
131
  ...createDefaultCloudAiTools(),
132
+ ...createCodeSourceTools(),
111
133
  createCloudAiListFilesTool(),
112
134
  createCloudAiReadFileTool(),
113
135
  createCloudAiFetchFileTool(),
@@ -116,6 +138,7 @@ export const createConfiguredDefaultCloudAiTools = async (config?: {
116
138
  createCloudAiPresentTool(),
117
139
  createCloudAiCalculateTool(),
118
140
  createCloudAiViewImageTool(),
141
+ createCloudAiTranscribeAudioTool(),
119
142
  ];
120
143
  const firecrawlConfigured =
121
144
  config && "firecrawlApiKey" in config ? Boolean(config.firecrawlApiKey?.trim()) : await isCloudAiFirecrawlConfigured();