@k2b/cloud 0.23.0 → 0.24.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 (45) hide show
  1. package/package.json +2 -2
  2. package/src/_internal/capabilities.ts +230 -75
  3. package/src/_internal/define-app.ts +12 -3
  4. package/src/_internal/fixtures/filesv2-manifest-cloud-v0.29.0.json +887 -0
  5. package/src/_internal/page-responses.ts +1 -1
  6. package/src/_internal/registry.ts +78 -3
  7. package/src/ai/chat/blocks.tsx +2 -1
  8. package/src/ai/chat/messages.ts +6 -0
  9. package/src/ai/client/controller.ts +65 -20
  10. package/src/ai/client/transport.ts +5 -5
  11. package/src/ai/code-mode-skill.ts +2 -2
  12. package/src/ai/index.ts +0 -7
  13. package/src/ai/live-events.ts +1 -262
  14. package/src/ai/live.ts +31 -2
  15. package/src/ai/migrate.ts +35 -16
  16. package/src/ai/runtime.ts +1 -6
  17. package/src/ai/solid.ts +0 -5
  18. package/src/api/help.ts +2 -2
  19. package/src/api/pwa-phone.ts +10 -3
  20. package/src/api/search/schemas.ts +34 -0
  21. package/src/api/search.ts +118 -50
  22. package/src/browser/CloudResourceSearch.browser-harness.tsx +11 -0
  23. package/src/browser/CloudResourceSearch.tsx +208 -80
  24. package/src/browser/resource-search-messages.ts +15 -2
  25. package/src/browser/search-stream.ts +151 -0
  26. package/src/contracts/capabilities.ts +89 -24
  27. package/src/contracts/capability-compatibility.ts +28 -14
  28. package/src/contracts/file-provider.ts +158 -0
  29. package/src/contracts/index.ts +1 -0
  30. package/src/events/live-engine.ts +11 -7
  31. package/src/events/live.ts +32 -32
  32. package/src/server/help.ts +3 -3
  33. package/src/services/index.ts +1 -1
  34. package/src/services/outbox.ts +29 -115
  35. package/src/services/pdf/markdown.ts +22 -2
  36. package/src/services/pwa-devices.ts +74 -8
  37. package/src/shared/markdown/formula.ts +122 -26
  38. package/src/shared/markdown/index.ts +27 -14
  39. package/src/ssr/PwaLayout.tsx +2 -1
  40. package/src/styles/resource-search.css +19 -0
  41. package/src/ai/client/live-connection.ts +0 -141
  42. package/src/ai/live-messages.ts +0 -45
  43. package/src/ai/live-outbox.ts +0 -102
  44. package/src/ai/live-routes.ts +0 -412
  45. package/src/shared/markdown/extensions/info-blocks.ts +0 -79
package/src/api/search.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Hono, type MiddlewareHandler } from "hono";
2
- import { describeRoute } from "hono-openapi";
2
+ import { describeRoute, resolver } from "hono-openapi";
3
3
  import { readBoundedJson } from "../_internal/bounded-json";
4
4
  import { resolveCapabilityManifestPresentation } from "../_internal/capabilities";
5
5
  import { listCapabilities } from "../_internal/registry";
@@ -18,14 +18,24 @@ import { searchInvocationOperation } from "../services/identity/invocation-opera
18
18
  import { normalizeInvocationRequestId, signInvocationToken } from "../services/identity/invocation-token";
19
19
  import { withActiveIdentitySigner } from "../services/identity/key-ring";
20
20
  import { LOCALE_HEADER } from "../shared/locale";
21
- import { type SearchItem, SearchItemSchema, SearchQuerySchema, SearchResponseSchema } from "./search/schemas";
21
+ import {
22
+ SEARCH_STREAM_CONTENT_TYPE,
23
+ type SearchItem,
24
+ SearchItemSchema,
25
+ type SearchProviderStatus,
26
+ SearchQuerySchema,
27
+ type SearchResponse,
28
+ SearchResponseSchema,
29
+ type SearchStreamLine,
30
+ SearchStreamLineSchema,
31
+ } from "./search/schemas";
22
32
 
23
33
  const log = logger("search");
24
34
  const SearchProviderResultSchema = capabilityResultSchema(UniversalSearchDataSchema);
25
35
 
26
36
  /**
27
- * Maximum items returned to the client after merging across providers.
28
- * The frontend has no further limit — this caps the rendered list.
37
+ * Maximum items of the merged JSON response. A streamed search has no merged
38
+ * list: each app's line carries at most that app's provider limit.
29
39
  */
30
40
  const GLOBAL_RESULT_LIMIT = 30;
31
41
  const PROVIDER_CONCURRENCY = 8;
@@ -122,8 +132,25 @@ const startBounded = <T, R>(
122
132
  return deferred.map((entry) => entry.promise);
123
133
  };
124
134
 
125
- const settleBounded = async <T, R>(items: readonly T[], concurrency: number, run: (item: T, index: number) => Promise<R>) =>
126
- Promise.all(startBounded(items, concurrency, run));
135
+ /** Highest app-provided priority first, then by title. */
136
+ const rankItems = (items: SearchItem[]) => items.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.title.localeCompare(b.title));
137
+
138
+ /** The browser asks for a stream explicitly; every other client keeps the merged JSON response. */
139
+ const acceptsStream = (accept: string | undefined) =>
140
+ accept?.split(",").some((type) => type.split(";")[0]?.trim().toLowerCase() === SEARCH_STREAM_CONTENT_TYPE) ?? false;
141
+
142
+ const streamHeaders = {
143
+ "content-type": `${SEARCH_STREAM_CONTENT_TYPE}; charset=utf-8`,
144
+ // Each line must reach the browser when it is written: no cache, no transformation, no proxy buffering.
145
+ "cache-control": "no-store, no-transform",
146
+ "x-accel-buffering": "no",
147
+ } as const;
148
+
149
+ const encoder = new TextEncoder();
150
+ const lineText = (line: SearchStreamLine) => `${JSON.stringify(line)}\n`;
151
+ const encodeLine = (line: SearchStreamLine) => encoder.encode(lineText(line));
152
+
153
+ type AppOutcome = { appId: string; status: SearchProviderStatus; items: SearchItem[]; ms: number };
127
154
 
128
155
  const waitWithin = <T>(value: Promise<T>, signal: AbortSignal): Promise<T> =>
129
156
  new Promise<T>((resolve, reject) => {
@@ -160,7 +187,14 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
160
187
  description: "Searches across app providers discovered via the service registry with optional tag filters.",
161
188
  ...requiresAuth,
162
189
  responses: {
163
- 200: jsonResponse(SearchResponseSchema, "Merged search results"),
190
+ 200: {
191
+ description:
192
+ "Merged search results. With `Accept: application/x-ndjson`, one JSON line per app in the order the apps finish instead.",
193
+ content: {
194
+ "application/json": { schema: resolver(SearchResponseSchema) },
195
+ [SEARCH_STREAM_CONTENT_TYPE]: { schema: resolver(SearchStreamLineSchema) },
196
+ },
197
+ },
164
198
  400: jsonResponse(ErrorResponseSchema, "Invalid query"),
165
199
  401: jsonResponse(ErrorResponseSchema, "Authentication required"),
166
200
  403: jsonResponse(ErrorResponseSchema, "User-backed actor required"),
@@ -172,6 +206,7 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
172
206
  expectUserBackedActor(c);
173
207
 
174
208
  const query = c.req.valid("query");
209
+ const stream = acceptsStream(c.req.header("accept"));
175
210
  const requestId = normalizeInvocationRequestId(c.req.header("x-request-id"));
176
211
  const invocationAuthority = invocationAuthorityFromRequest(auth.getAuthority(c));
177
212
  let entries: CapabilityRegistryEntry[];
@@ -231,18 +266,24 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
231
266
  const active =
232
267
  query.tag.length === 0 ? appProviders : appProviders.filter((provider) => provider.tags.some((tag) => query.tag.includes(tag)));
233
268
 
269
+ // Answers without a provider call: the catalog alone, or only unsupported tags.
270
+ const answerWithoutProviders = (body: SearchResponse) =>
271
+ stream
272
+ ? new Response(
273
+ [
274
+ lineText({ type: "start", query: body.query, apps, providers: [], ...(body.unsupportedTags ? { unsupportedTags } : {}) }),
275
+ lineText({ type: "done", status: "complete", count: 0 }),
276
+ ].join(""),
277
+ { headers: streamHeaders },
278
+ )
279
+ : c.json(body);
280
+
234
281
  if (query.q.length === 0 && query.tag.length === 0 && !query.app && !scope) {
235
- return c.json({ query: "", count: 0, items: [], apps });
282
+ return answerWithoutProviders({ query: "", count: 0, items: [], apps });
236
283
  }
237
284
 
238
285
  if (query.tag.length > 0 && active.length === 0) {
239
- return c.json({
240
- query: query.q,
241
- count: 0,
242
- items: [],
243
- apps,
244
- unsupportedTags,
245
- });
286
+ return answerWithoutProviders({ query: query.q, count: 0, items: [], apps, unsupportedTags });
246
287
  }
247
288
 
248
289
  // Single-provider queries get a larger sample for better local
@@ -252,7 +293,9 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
252
293
  const effectiveProviderLimit = active.length === 1 ? Math.min(GLOBAL_RESULT_LIMIT, query.provider_limit * 3) : query.provider_limit;
253
294
  // The same request-wide budget covers signing and provider I/O.
254
295
  const providerDeadline = AbortSignal.timeout(PROVIDER_TIMEOUT_MS);
255
- const fanoutSignal = AbortSignal.any([c.req.raw.signal, providerDeadline]);
296
+ // A client that stops reading a stream, such as the browser on the next keystroke, ends the search too.
297
+ const streamCancelled = new AbortController();
298
+ const fanoutSignal = AbortSignal.any([c.req.raw.signal, providerDeadline, streamCancelled.signal]);
256
299
  // Guard the whole issuance batch once, then reuse the prepared signer for
257
300
  // every target. This is one Postgres check per outer search request, not
258
301
  // one check per provider.
@@ -298,7 +341,8 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
298
341
  // One request-wide budget keeps latency flat as the number of apps grows.
299
342
  // Workers that have not started when the deadline expires fail fast on
300
343
  // the already-aborted signal instead of opening a fresh timeout window.
301
- const settled = await settleBounded(active, PROVIDER_CONCURRENCY, async (provider, index) => {
344
+ const fanoutStarted = performance.now();
345
+ const settled = startBounded(active, PROVIDER_CONCURRENCY, async (provider, index) => {
302
346
  // Scope tags to those this provider declared. Apps no longer need
303
347
  // their own gate — the framework guarantees they only see tags
304
348
  // they understand.
@@ -395,47 +439,71 @@ export const createSearchRoutes = (dependencies: SearchRouteDependencies = {}) =
395
439
  return validItems;
396
440
  });
397
441
 
398
- const items = settled.flatMap((result, index) => {
399
- if (result.status === "fulfilled") return result.value;
400
-
401
- log.warn("Search provider failed", {
402
- appId: active[index]?.appId ?? "unknown",
403
- tags: query.tag,
404
- error: result.reason instanceof Error ? result.reason.message : String(result.reason),
405
- });
406
- return [];
442
+ // One outcome per app, when all of its Queries have finished. Multiple
443
+ // focused Queries from one app must not buy that app a larger share.
444
+ const appIds = [...new Set(active.map((provider) => provider.appId))];
445
+ const outcomes = appIds.map(async (appId): Promise<AppOutcome> => {
446
+ const results = await Promise.all(active.flatMap((provider, index) => (provider.appId === appId ? [settled[index]!] : [])));
447
+ const failed = results.filter((result) => result.status === "rejected");
448
+ for (const result of failed) {
449
+ log.warn("Search provider failed", {
450
+ appId,
451
+ tags: query.tag,
452
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason),
453
+ });
454
+ }
455
+ const items = rankItems(results.flatMap((result) => (result.status === "fulfilled" ? result.value : []))).slice(
456
+ 0,
457
+ effectiveProviderLimit,
458
+ );
459
+ const status = failed.length ? (providerDeadline.aborted ? "timeout" : "error") : items.length ? "ok" : "empty";
460
+ return { appId, status, items, ms: Math.round(performance.now() - fanoutStarted) };
407
461
  });
462
+ const failure = (outcome: AppOutcome) => outcome.status === "timeout" || outcome.status === "error";
408
463
 
409
- items.sort((a, b) => {
410
- const priorityDiff = (b.priority ?? 0) - (a.priority ?? 0);
411
- if (priorityDiff !== 0) return priorityDiff;
412
- return a.title.localeCompare(b.title);
413
- });
464
+ if (stream) {
465
+ let cancelled = false;
466
+ const body = new ReadableStream<Uint8Array>({
467
+ start(controller) {
468
+ const write = (line: SearchStreamLine) => {
469
+ if (!cancelled) controller.enqueue(encodeLine(line));
470
+ };
471
+ write({ type: "start", query: query.q, apps, providers: appIds, ...(unsupportedTags.length > 0 ? { unsupportedTags } : {}) });
472
+ let count = 0;
473
+ let partial = false;
474
+ // A slow app never holds back the others: each line is written when its app finishes.
475
+ void Promise.all(
476
+ outcomes.map((pending) =>
477
+ pending.then((outcome) => {
478
+ count += outcome.items.length;
479
+ partial ||= failure(outcome);
480
+ write({ type: "provider", provider: outcome.appId, status: outcome.status, results: outcome.items, ms: outcome.ms });
481
+ }),
482
+ ),
483
+ ).then(() => {
484
+ write({ type: "done", status: partial ? "partial" : "complete", count });
485
+ if (!cancelled) controller.close();
486
+ });
487
+ },
488
+ cancel() {
489
+ cancelled = true;
490
+ streamCancelled.abort();
491
+ },
492
+ });
493
+ return new Response(body, { headers: streamHeaders });
494
+ }
414
495
 
415
- // Multiple focused Queries from one app must not buy that app a larger
416
- // share of the merged result set.
417
- const appCounts = new Map<string, number>();
418
- const appBounded = items.filter((item) => {
419
- const count = appCounts.get(item.appId) ?? 0;
420
- if (count >= effectiveProviderLimit) return false;
421
- appCounts.set(item.appId, count + 1);
422
- return true;
423
- });
424
- const sliced = appBounded.slice(0, GLOBAL_RESULT_LIMIT);
496
+ const finished = await Promise.all(outcomes);
497
+ const items = rankItems(finished.flatMap((outcome) => outcome.items)).slice(0, GLOBAL_RESULT_LIMIT);
498
+ const failedApps = finished.filter(failure).map((outcome) => outcome.appId);
425
499
 
426
500
  return c.json({
427
501
  query: query.q,
428
- count: sliced.length,
429
- items: sliced,
502
+ count: items.length,
503
+ items,
430
504
  apps,
431
505
  ...(unsupportedTags.length > 0 ? { unsupportedTags } : {}),
432
- ...(settled.some((result) => result.status === "rejected")
433
- ? {
434
- failedApps: [
435
- ...new Set(active.filter((_, index) => settled[index]?.status === "rejected").map((provider) => provider.appId)),
436
- ],
437
- }
438
- : {}),
506
+ ...(failedApps.length > 0 ? { failedApps } : {}),
439
507
  });
440
508
  },
441
509
  );
@@ -0,0 +1,11 @@
1
+ import { createGlobalSearchHost } from "../ssr/GlobalSearchDialog";
2
+ import { openCloudResourcePicker } from "./resource-picker";
3
+
4
+ /**
5
+ * Opens the real global search, or with `?picker` the resource picker, for a browser test that answers
6
+ * `/api/search` with invented, line-by-line results. `?app=<id>` narrows either one to one app.
7
+ */
8
+ const params = new URLSearchParams(location.search);
9
+ const app = params.get("app") ?? undefined;
10
+ if (params.has("picker")) void openCloudResourcePicker({ initialAppId: app });
11
+ else createGlobalSearchHost(() => []).open(app ? { scope: { appId: app, label: params.get("label") ?? app } } : {});