@vibes.diy/vibe-runtime 14.3.374 → 14.3.375

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.
@@ -7,9 +7,9 @@ export { BACKEND_GITHUB_OP_URL, handleBackendGithubOp } from "./backend-worker-l
7
7
  export { BACKEND_CONNECTIONS_OP_URL, handleBackendConnectionsOp } from "./backend-worker-loader-executor.js";
8
8
  export { BACKEND_STRIPE_OP_URL, handleBackendStripeOp } from "./backend-worker-loader-executor.js";
9
9
  export { BACKEND_YOUTUBE_OP_URL, handleBackendYoutubeOp } from "./backend-worker-loader-executor.js";
10
- export { HANDLER_THREW_HEADER } from "./backend-worker-loader-executor.js";
10
+ export { HANDLER_THREW_HEADER, settleOrAbort } from "./backend-worker-loader-executor.js";
11
11
  export type BackendHandler = "fetch" | "scheduled" | "onChange";
12
- export type BackendInvokeLane = BackendHandler | "tool";
12
+ export type BackendInvokeLane = BackendHandler | "tool" | "hook";
13
13
  export interface BackendTrigger {
14
14
  readonly userHandle?: string | null;
15
15
  readonly sourceTag?: string;
@@ -327,6 +327,7 @@ export interface BackendInvokeInput {
327
327
  readonly stripe?: BackendStripeCallback;
328
328
  readonly youtube?: BackendYoutubeCallback;
329
329
  readonly dbFetcher?: unknown;
330
+ readonly signal?: AbortSignal;
330
331
  }
331
332
  export interface BackendExecutor {
332
333
  invoke(input: BackendInvokeInput): Promise<Response>;
@@ -7,7 +7,7 @@ export { BACKEND_GITHUB_OP_URL, handleBackendGithubOp } from "./backend-worker-l
7
7
  export { BACKEND_CONNECTIONS_OP_URL, handleBackendConnectionsOp } from "./backend-worker-loader-executor.js";
8
8
  export { BACKEND_STRIPE_OP_URL, handleBackendStripeOp } from "./backend-worker-loader-executor.js";
9
9
  export { BACKEND_YOUTUBE_OP_URL, handleBackendYoutubeOp } from "./backend-worker-loader-executor.js";
10
- export { HANDLER_THREW_HEADER } from "./backend-worker-loader-executor.js";
10
+ export { HANDLER_THREW_HEADER, settleOrAbort } from "./backend-worker-loader-executor.js";
11
11
  export function parseBackendJsMode(raw) {
12
12
  switch ((raw ?? "").trim().toLowerCase()) {
13
13
  case "loader":
@@ -1,5 +1,8 @@
1
1
  export declare const MAX_BACKEND_TOOLS = 8;
2
2
  export declare const MAX_TOOL_INPUT_FIELDS = 12;
3
+ export declare const MAX_TOOL_TITLE_LENGTH = 60;
4
+ export declare const MAX_TOOL_OUTPUT_FIELDS = 12;
5
+ export declare const MAX_TOOL_ERROR_MESSAGE_CHARS = 500;
3
6
  export declare const MAX_TOOL_DESCRIPTION_LENGTH = 280;
4
7
  export declare const TOOL_NAME_PATTERN: RegExp;
5
8
  export declare const TOOL_FIELD_NAME_PATTERN: RegExp;
@@ -32,10 +35,25 @@ export interface BackendToolDecl {
32
35
  readonly for: BackendToolAudience;
33
36
  readonly input: readonly BackendToolField[];
34
37
  readonly run: BackendToolRun;
38
+ readonly title?: string;
39
+ readonly annotations?: BackendToolAnnotations;
40
+ readonly output?: readonly BackendToolField[];
35
41
  readonly offer?: true;
36
42
  readonly textsLater?: true;
37
- readonly picturePrompt?: true;
38
43
  }
44
+ export interface BackendToolAnnotations {
45
+ readonly readOnly?: true;
46
+ readonly consequential?: true;
47
+ }
48
+ export type BackendHookName = "picturePrompt";
49
+ export declare const BACKEND_HOOK_NAMES: readonly BackendHookName[];
50
+ export interface BackendHookDecl {
51
+ readonly name: BackendHookName;
52
+ readonly input: readonly BackendToolField[];
53
+ readonly legacyTool?: string;
54
+ readonly for?: BackendToolAudience;
55
+ }
56
+ export declare const PICTURE_PROMPT_HOOK_INPUT: readonly BackendToolField[];
39
57
  export interface ToolInputJsonSchema {
40
58
  readonly type: "object";
41
59
  readonly properties: Record<string, {
@@ -47,6 +65,13 @@ export interface ToolInputJsonSchema {
47
65
  readonly additionalProperties: false;
48
66
  }
49
67
  export declare function toolInputJsonSchema(tool: Pick<BackendToolDecl, "input">): ToolInputJsonSchema;
68
+ export interface ToolOutputJsonSchema {
69
+ readonly type: "object";
70
+ readonly properties: ToolInputJsonSchema["properties"];
71
+ readonly required: string[];
72
+ }
73
+ export declare function toolOutputJsonSchema(tool: Pick<BackendToolDecl, "output">): ToolOutputJsonSchema | undefined;
74
+ export declare function toolErrorMessage(result: unknown): string | undefined;
50
75
  export type ToolInputCheck = {
51
76
  readonly ok: true;
52
77
  readonly value: Record<string, BackendToolLiteral>;
package/backend-tools.js CHANGED
@@ -1,5 +1,8 @@
1
1
  export const MAX_BACKEND_TOOLS = 8;
2
2
  export const MAX_TOOL_INPUT_FIELDS = 12;
3
+ export const MAX_TOOL_TITLE_LENGTH = 60;
4
+ export const MAX_TOOL_OUTPUT_FIELDS = 12;
5
+ export const MAX_TOOL_ERROR_MESSAGE_CHARS = 500;
3
6
  export const MAX_TOOL_DESCRIPTION_LENGTH = 280;
4
7
  export const TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
5
8
  export const TOOL_FIELD_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
@@ -8,22 +11,44 @@ export const MAX_TOOL_RESULT_CHARS = 8_000;
8
11
  export const MAX_TOOL_RESPONSE_BYTES = MAX_TOOL_RESULT_CHARS * 6 + 1_024;
9
12
  export const BACKEND_TOOL_AUDIENCES = ["anyone", "members", "owner"];
10
13
  export const BACKEND_TOOL_FIELD_TYPES = ["string", "number", "boolean"];
11
- export function toolInputJsonSchema(tool) {
14
+ export const BACKEND_HOOK_NAMES = ["picturePrompt"];
15
+ export const PICTURE_PROMPT_HOOK_INPUT = [{ name: "addition", type: "string", optional: true }];
16
+ function fieldProperties(fields) {
12
17
  const properties = {};
13
- for (const f of tool.input) {
18
+ for (const f of fields) {
14
19
  properties[f.name] = {
15
20
  type: f.type,
16
21
  ...(f.description === undefined ? {} : { description: f.description }),
17
22
  ...(f.enum === undefined ? {} : { enum: f.enum }),
18
23
  };
19
24
  }
25
+ return properties;
26
+ }
27
+ export function toolInputJsonSchema(tool) {
20
28
  return {
21
29
  type: "object",
22
- properties,
30
+ properties: fieldProperties(tool.input),
23
31
  required: tool.input.filter((f) => f.optional === false).map((f) => f.name),
24
32
  additionalProperties: false,
25
33
  };
26
34
  }
35
+ export function toolOutputJsonSchema(tool) {
36
+ if (tool.output === undefined)
37
+ return undefined;
38
+ return {
39
+ type: "object",
40
+ properties: fieldProperties(tool.output),
41
+ required: tool.output.filter((f) => f.optional === false).map((f) => f.name),
42
+ };
43
+ }
44
+ export function toolErrorMessage(result) {
45
+ if (typeof result !== "object" || result === null || Array.isArray(result))
46
+ return undefined;
47
+ const r = result;
48
+ if (typeof r.error !== "string" || r.error.trim() === "" || r.ok === true)
49
+ return undefined;
50
+ return r.error.trim().slice(0, MAX_TOOL_ERROR_MESSAGE_CHARS);
51
+ }
27
52
  export function validateToolInput(tool, input) {
28
53
  const raw = input === undefined || input === null ? {} : input;
29
54
  if (typeof raw !== "object" || Array.isArray(raw))
@@ -25,6 +25,9 @@ export declare function handleBackendGithubOp(request: Request): Promise<Respons
25
25
  export declare function handleBackendConnectionsOp(request: Request): Promise<Response>;
26
26
  export declare function handleBackendStripeOp(request: Request): Promise<Response>;
27
27
  export declare function handleBackendYoutubeOp(request: Request): Promise<Response>;
28
+ export declare const HOOK_READ_ONLY_MESSAGE = "a hook is read-only";
29
+ export declare const BACKEND_HOOK_GUARD_SHIM: string;
30
+ export declare const BACKEND_HOOK_CTX_SHIM: string;
28
31
  export declare function buildBackendWorkerCode(input: {
29
32
  module: string;
30
33
  policyVersion?: string;
@@ -33,7 +36,9 @@ export declare function buildBackendWorkerCode(input: {
33
36
  appSlug: string;
34
37
  };
35
38
  depsVersion?: string;
39
+ lane?: "hook";
36
40
  }): WorkerCode;
41
+ export declare function settleOrAbort<T>(call: Promise<T>, signal: AbortSignal): Promise<T>;
37
42
  export declare const HANDLER_THREW_HEADER = "x-vibe-handler-threw";
38
43
  export declare function normalizeHandlerThrewMarker(res: Response, throwMarker: string): Response;
39
44
  export declare class WorkerLoaderBackendExecutor implements BackendExecutor {
@@ -1,10 +1,11 @@
1
1
  import { TxtEnDecoderSingleton } from "@adviser/cement";
2
2
  import { transformBackendSource } from "./transform-backend-source.js";
3
3
  import { loadBackendIsolateDeps } from "./backend-isolate-deps.js";
4
- import { MAX_TOOL_RESULT_CHARS } from "./backend-tools.js";
4
+ import { MAX_TOOL_ERROR_MESSAGE_CHARS, MAX_TOOL_RESULT_CHARS } from "./backend-tools.js";
5
5
  import { isValidNotifyPath, NOTIFY_CONSENT_ERROR, NOTIFY_PATH_ERROR, NOTIFY_PICTURE_SHAPE_ERROR } from "./notify-path.js";
6
6
  const MAIN_MODULE = "main.js";
7
7
  const BACKEND_MODULE = "backend.js";
8
+ const HOOK_GUARD_MODULE = "hook-guard.js";
8
9
  const LOG_BODY_MAX_CHARS = 4096;
9
10
  const COMPATIBILITY_DATE = "2025-05-01";
10
11
  const BINDING_SCHEMA_VERSION = "v17";
@@ -354,13 +355,63 @@ export async function handleBackendYoutubeOp(request) {
354
355
  : { ok: false, error: "ctx.youtube is not available (no active call context)" };
355
356
  return new Response(JSON.stringify(result), { headers: { "content-type": "application/json" } });
356
357
  }
358
+ export const HOOK_READ_ONLY_MESSAGE = "a hook is read-only";
359
+ export const BACKEND_HOOK_GUARD_SHIM = [
360
+ `(function installHookGuard(g) {`,
361
+ ` const real = g.fetch;`,
362
+ ` const apply = Reflect.apply;`,
363
+ ` const PromiseCtor = Promise;`,
364
+ ` const ErrorCtor = Error;`,
365
+ ` const DB_OP = ${JSON.stringify(BACKEND_DB_OP_URL)};`,
366
+ ` const LOG_OP = ${JSON.stringify(BACKEND_LOG_OP_URL)};`,
367
+ ` const REFUSED = ${JSON.stringify(HOOK_READ_ONLY_MESSAGE + ": outbound fetch is not available in a hook")};`,
368
+ ` function guardedFetch(input, init) {`,
369
+ ` if (typeof input === "string" && input === DB_OP) return apply(real, g, [DB_OP, init]);`,
370
+ ` if (typeof input === "string" && input === LOG_OP) return apply(real, g, [LOG_OP, init]);`,
371
+ ` return new PromiseCtor(function (resolve, reject) { reject(new ErrorCtor(REFUSED)); });`,
372
+ ` }`,
373
+ ` const pinned = { value: guardedFetch, writable: false, configurable: false, enumerable: true };`,
374
+ ` for (let o = g; o; o = Object.getPrototypeOf(o)) {`,
375
+ ` if (Object.prototype.hasOwnProperty.call(o, "fetch")) { try { Object.defineProperty(o, "fetch", pinned); } catch (e) { /* a frozen holder: the own property below still shadows it */ } }`,
376
+ ` }`,
377
+ ` try { Object.defineProperty(g, "fetch", pinned); } catch (e) { /* already pinned above */ }`,
378
+ ` const gone = ["WebSocket", "EventSource"];`,
379
+ ` for (let i = 0; i < gone.length; i++) {`,
380
+ ` try { Object.defineProperty(g, gone[i], { value: undefined, writable: false, configurable: false }); } catch (e) { /* not present */ }`,
381
+ ` }`,
382
+ `})(globalThis);`,
383
+ ``,
384
+ ].join("\n");
385
+ export const BACKEND_HOOK_CTX_SHIM = [
386
+ `function makeHookCtx(full) {`,
387
+ ` function refuse(what) {`,
388
+ ` return function hookRefused() { throw new Error(${JSON.stringify(HOOK_READ_ONLY_MESSAGE + ": ")} + what + " is not available in a hook"); };`,
389
+ ` }`,
390
+ ` return {`,
391
+ ` appInfo: full.appInfo,`,
392
+ ` userInfo: full.userInfo,`,
393
+ ` db: { query: full.db.query, get: full.db.get, put: refuse("ctx.db.put"), delete: refuse("ctx.db.delete") },`,
394
+ ` fetch: refuse("ctx.fetch"),`,
395
+ ` callAI: refuse("ctx.callAI"),`,
396
+ ` notify: refuse("ctx.notify"),`,
397
+ ` log: full.log,`,
398
+ ` github: { fetch: refuse("ctx.github"), routes: refuse("ctx.github") },`,
399
+ ` connections: { fetch: refuse("ctx.connections"), status: refuse("ctx.connections") },`,
400
+ ` stripe: { fetch: refuse("ctx.stripe"), status: refuse("ctx.stripe") },`,
401
+ ` youtube: { fetch: refuse("ctx.youtube"), status: refuse("ctx.youtube") },`,
402
+ ` secrets: Object.freeze({}),`,
403
+ ` };`,
404
+ `}`,
405
+ ].join("\n");
357
406
  const BACKEND_REQUEST_URL = "https://vibe-backend.internal/";
358
407
  export function buildBackendWorkerCode(input) {
359
408
  const policyVersion = input.policyVersion ?? "v1";
360
409
  const depsVersion = input.depsVersion ?? "";
410
+ const hookLane = input.lane === "hook";
361
411
  const vibeLiteral = input.vibe ? JSON.stringify({ ownerHandle: input.vibe.ownerHandle, appSlug: input.vibe.appSlug }) : "null";
362
412
  const main = [
363
- `// backend-isolate policy=${policyVersion} bindings=${BINDING_SCHEMA_VERSION} deps=${depsVersion}`,
413
+ `// backend-isolate policy=${policyVersion} bindings=${BINDING_SCHEMA_VERSION} deps=${depsVersion}${hookLane ? " lane=hook" : ""}`,
414
+ ...(hookLane ? [`import "./${HOOK_GUARD_MODULE}";`] : []),
364
415
  `import * as handlers from "./${BACKEND_MODULE}";`,
365
416
  `const VIBE = ${vibeLiteral};`,
366
417
  `function makeDb(trigger, dbNonce) {`,
@@ -434,16 +485,19 @@ export function buildBackendWorkerCode(input) {
434
485
  BACKEND_CONNECTIONS_SHIM,
435
486
  BACKEND_STRIPE_SHIM,
436
487
  BACKEND_YOUTUBE_SHIM,
488
+ ...(hookLane ? [BACKEND_HOOK_CTX_SHIM] : []),
437
489
  `export default {`,
438
490
  ` async fetch(request, env) {`,
439
491
  ` const { handler, trigger, dbNonce, aiNonce, notifyNonce, logNonce, githubNonce, connectionsNonce, stripeNonce, youtubeNonce, throwMarker, secrets } = await request.json();`,
440
- ` const ALLOWED_HANDLERS = { fetch: true, scheduled: true, onChange: true, tool: true };`,
492
+ hookLane
493
+ ? ` const ALLOWED_HANDLERS = { hook: true };`
494
+ : ` const ALLOWED_HANDLERS = { fetch: true, scheduled: true, onChange: true, tool: true };`,
441
495
  ` if (!Object.prototype.hasOwnProperty.call(ALLOWED_HANDLERS, handler)) {`,
442
496
  ` return new Response("invalid backend handler: " + handler, { status: 400 });`,
443
497
  ` }`,
444
498
  ` const logPending = [];`,
445
499
  ` const logLane = makeLog(logNonce, logPending);`,
446
- ` const ctx = {`,
500
+ ` const ${hookLane ? "fullCtx" : "ctx"} = {`,
447
501
  ` appInfo: VIBE,`,
448
502
  ` userInfo: trigger && trigger.userHandle ? { userHandle: trigger.userHandle } : null,`,
449
503
  ` db: makeDb(trigger, dbNonce),`,
@@ -457,19 +511,33 @@ export function buildBackendWorkerCode(input) {
457
511
  ` youtube: makeYoutube(youtubeNonce),`,
458
512
  ` secrets: Object.freeze(secrets || {}),`,
459
513
  ` };`,
460
- ` const toolName = handler === "tool" && trigger && trigger.payload ? trigger.payload.name : undefined;`,
461
- ` const toolSet = handler === "tool" ? handlers.tools : undefined;`,
462
- ` const tool = toolSet && typeof toolSet === "object" && typeof toolName === "string" && Object.prototype.hasOwnProperty.call(toolSet, toolName) ? toolSet[toolName] : undefined;`,
463
- ` const fn = handler === "tool" ? (tool && typeof tool === "object" ? tool.handler : undefined) : handlers[handler];`,
514
+ ...(hookLane
515
+ ? [
516
+ ` const ctx = makeHookCtx(fullCtx);`,
517
+ ` const hookPayload = trigger && trigger.payload ? trigger.payload : {};`,
518
+ ` const legacyTool = typeof hookPayload.legacyTool === "string" ? hookPayload.legacyTool : undefined;`,
519
+ ` const toolSet = legacyTool !== undefined ? handlers.tools : handlers.hooks;`,
520
+ ` const toolName = legacyTool !== undefined ? legacyTool : hookPayload.name;`,
521
+ ` const tool = toolSet && typeof toolSet === "object" && typeof toolName === "string" && Object.prototype.hasOwnProperty.call(toolSet, toolName) ? toolSet[toolName] : undefined;`,
522
+ ` const fn = tool && typeof tool === "object" ? (legacyTool !== undefined ? tool.handler : tool.run) : undefined;`,
523
+ ]
524
+ : [
525
+ ` const toolName = handler === "tool" && trigger && trigger.payload ? trigger.payload.name : undefined;`,
526
+ ` const toolSet = handler === "tool" ? handlers.tools : undefined;`,
527
+ ` const tool = toolSet && typeof toolSet === "object" && typeof toolName === "string" && Object.prototype.hasOwnProperty.call(toolSet, toolName) ? toolSet[toolName] : undefined;`,
528
+ ` const fn = handler === "tool" ? (tool && typeof tool === "object" ? tool.handler : undefined) : handlers[handler];`,
529
+ ]),
464
530
  ` if (typeof fn !== "function") {`,
465
531
  ` return new Response("no backend handler: " + handler, { status: 404 });`,
466
532
  ` }`,
467
533
  ` try {`,
468
- ` if (handler === "tool") {`,
534
+ hookLane ? ` if (handler === "hook") {` : ` if (handler === "tool") {`,
469
535
  ` try {`,
470
536
  ` const out = await fn.call(tool, (trigger.payload && trigger.payload.input) || {}, ctx);`,
471
537
  ` const resultText = JSON.stringify(out === undefined ? null : out);`,
472
- ` const toolBody = typeof resultText !== "string" ? '{"result":null}' : resultText.length <= ${MAX_TOOL_RESULT_CHARS} ? '{"result":' + resultText + '}' : JSON.stringify({ result: resultText.slice(0, ${MAX_TOOL_RESULT_CHARS}), truncated: true });`,
538
+ ` const toolError = out && typeof out === "object" && !Array.isArray(out) && typeof out.error === "string" && out.ok !== true ? out.error.trim().slice(0, ${MAX_TOOL_ERROR_MESSAGE_CHARS}) : "";`,
539
+ ` const cutBody = toolError === "" ? { result: resultText.slice(0, ${MAX_TOOL_RESULT_CHARS}), truncated: true } : { result: resultText.slice(0, ${MAX_TOOL_RESULT_CHARS}), truncated: true, toolError: toolError };`,
540
+ ` const toolBody = typeof resultText !== "string" ? '{"result":null}' : resultText.length <= ${MAX_TOOL_RESULT_CHARS} ? '{"result":' + resultText + '}' : JSON.stringify(cutBody);`,
473
541
  ` return new Response(toolBody, { status: 200, headers: { "content-type": "application/json" } });`,
474
542
  ` } catch (e) {`,
475
543
  ` const tm = e && typeof e.message === "string" ? (typeof e.name === "string" ? e.name : "Error") + ": " + e.message : String(e);`,
@@ -508,10 +576,28 @@ export function buildBackendWorkerCode(input) {
508
576
  modules: {
509
577
  [MAIN_MODULE]: main,
510
578
  [BACKEND_MODULE]: input.module,
579
+ ...(hookLane ? { [HOOK_GUARD_MODULE]: BACKEND_HOOK_GUARD_SHIM } : {}),
511
580
  },
512
581
  globalOutbound: null,
513
582
  };
514
583
  }
584
+ export function settleOrAbort(call, signal) {
585
+ const aborted = new Promise((_resolve, reject) => {
586
+ function onAbort() {
587
+ reject(new Error("backend invocation aborted at its deadline"));
588
+ }
589
+ if (signal.aborted)
590
+ onAbort();
591
+ else
592
+ signal.addEventListener("abort", onAbort, { once: true });
593
+ });
594
+ call.then(function settled() {
595
+ return undefined;
596
+ }, function lateRejection() {
597
+ return undefined;
598
+ });
599
+ return Promise.race([call, aborted]);
600
+ }
515
601
  export const HANDLER_THREW_HEADER = "x-vibe-handler-threw";
516
602
  export function normalizeHandlerThrewMarker(res, throwMarker) {
517
603
  const value = res.headers.get(HANDLER_THREW_HEADER);
@@ -546,6 +632,7 @@ export class WorkerLoaderBackendExecutor {
546
632
  policyVersion: this.opts.policyVersion,
547
633
  vibe: this.opts.vibe,
548
634
  depsVersion: deps.depsVersion,
635
+ ...(input.handler === "hook" ? { lane: "hook" } : {}),
549
636
  });
550
637
  const id = await hashBackendWorkerCode(code);
551
638
  const nonce = input.db ? crypto.randomUUID() : undefined;
@@ -585,6 +672,7 @@ export class WorkerLoaderBackendExecutor {
585
672
  method: "POST",
586
673
  headers: { "content-type": "application/json" },
587
674
  redirect: "manual",
675
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
588
676
  body: JSON.stringify({
589
677
  handler: input.handler,
590
678
  trigger: input.trigger,
@@ -600,7 +688,9 @@ export class WorkerLoaderBackendExecutor {
600
688
  secrets: input.secrets ?? {},
601
689
  }),
602
690
  });
603
- return normalizeHandlerThrewMarker(await stub.getEntrypoint().fetch(request), throwMarker);
691
+ const call = stub.getEntrypoint().fetch(request);
692
+ const res = input.signal === undefined ? await call : await settleOrAbort(call, input.signal);
693
+ return normalizeHandlerThrewMarker(res, throwMarker);
604
694
  }
605
695
  finally {
606
696
  if (nonce)
package/index.d.ts CHANGED
@@ -44,4 +44,3 @@ export { useVibe, type UseVibeResult, type CanVerdict, type UseVibeMe } from "./
44
44
  export { useEnv } from "./use-env.js";
45
45
  export { createVibe, buildCreateVibeUrl, resolveBuilderOrigin, resolveBuilderOriginFrom, VIBES_DIY_BUILDER_URL, CREATE_VIBE_SAFE_URL_LENGTH, type CreateVibeOptions, } from "./create-vibe.js";
46
46
  export { buildGithubInstallUrl, buildGithubInstallUrlFrom, type GithubInstallVibe } from "./github-install-url.js";
47
- export { publicVibeBase } from "./short-self-link.js";
package/index.js CHANGED
@@ -40,4 +40,3 @@ export { useVibe } from "./use-vibe.js";
40
40
  export { useEnv } from "./use-env.js";
41
41
  export { createVibe, buildCreateVibeUrl, resolveBuilderOrigin, resolveBuilderOriginFrom, VIBES_DIY_BUILDER_URL, CREATE_VIBE_SAFE_URL_LENGTH, } from "./create-vibe.js";
42
42
  export { buildGithubInstallUrl, buildGithubInstallUrlFrom } from "./github-install-url.js";
43
- export { publicVibeBase } from "./short-self-link.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibes.diy/vibe-runtime",
3
- "version": "14.3.374",
3
+ "version": "14.3.375",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -36,9 +36,9 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@adviser/cement": "~0.5.37",
39
- "@vibes.diy/api-types": "14.3.374",
40
- "@vibes.diy/base": "14.3.374",
41
- "@vibes.diy/vibe-types": "14.3.374",
39
+ "@vibes.diy/api-types": "14.3.375",
40
+ "@vibes.diy/base": "14.3.375",
41
+ "@vibes.diy/vibe-types": "14.3.375",
42
42
  "arktype": "~2.2.9",
43
43
  "charwise": "~3.0.1",
44
44
  "es-module-lexer": "~3.0.4",
@@ -1,8 +1,8 @@
1
1
  import type { BackendHandler } from "./backend-executor.js";
2
2
  import { type GithubPermission } from "./github-permissions.js";
3
- import { MAX_BACKEND_TOOLS, type BackendToolDecl } from "./backend-tools.js";
3
+ import { MAX_BACKEND_TOOLS, type BackendHookDecl, type BackendToolDecl } from "./backend-tools.js";
4
4
  export { MAX_BACKEND_TOOLS };
5
- export type { BackendToolDecl };
5
+ export type { BackendToolDecl, BackendHookDecl };
6
6
  export declare const MIN_INTERVAL_MS = 5000;
7
7
  export declare const MAX_INTERVAL_MS = 3600000;
8
8
  export interface BackendSchedule {
@@ -36,6 +36,8 @@ export interface BackendConfigParseResult {
36
36
  readonly connections?: readonly BackendConnectionDecl[];
37
37
  readonly github?: BackendGithubDecl;
38
38
  readonly tools?: readonly BackendToolDecl[];
39
+ readonly hooks?: readonly BackendHookDecl[];
40
+ readonly warnings?: readonly string[];
39
41
  readonly errors: string[];
40
42
  }
41
43
  export declare function decodeStringLiteralBody(body: string): string | undefined;
@@ -1,6 +1,6 @@
1
1
  import { CONNECTION_PROVIDER_VOCABULARY } from "./connection-providers.js";
2
2
  import { GITHUB_PERMISSIONS, isGithubPermission } from "./github-permissions.js";
3
- import { BACKEND_TOOL_AUDIENCES, BACKEND_TOOL_FIELD_TYPES, MAX_BACKEND_TOOLS, MAX_TOOL_DESCRIPTION_LENGTH, MAX_TOOL_INPUT_FIELDS, TOOL_FIELD_NAME_PATTERN, TOOL_NAME_PATTERN, } from "./backend-tools.js";
3
+ import { BACKEND_TOOL_AUDIENCES, BACKEND_TOOL_FIELD_TYPES, MAX_BACKEND_TOOLS, MAX_TOOL_DESCRIPTION_LENGTH, MAX_TOOL_INPUT_FIELDS, MAX_TOOL_OUTPUT_FIELDS, MAX_TOOL_TITLE_LENGTH, BACKEND_HOOK_NAMES, PICTURE_PROMPT_HOOK_INPUT, TOOL_FIELD_NAME_PATTERN, TOOL_NAME_PATTERN, } from "./backend-tools.js";
4
4
  export { MAX_BACKEND_TOOLS };
5
5
  export const MIN_INTERVAL_MS = 5_000;
6
6
  export const MAX_INTERVAL_MS = 3_600_000;
@@ -964,6 +964,11 @@ const TOOLS_LANE = {
964
964
  "offer",
965
965
  "textsLater",
966
966
  "picturePrompt",
967
+ "title",
968
+ "annotations",
969
+ "readOnly",
970
+ "consequential",
971
+ "output",
967
972
  "db",
968
973
  "set",
969
974
  "key",
@@ -972,10 +977,32 @@ const TOOLS_LANE = {
972
977
  "enum",
973
978
  ],
974
979
  };
975
- const TOOL_KEYS = ["description", "for", "input", "handler", "write", "offer", "textsLater", "picturePrompt"];
980
+ const HOOKS_LANE = {
981
+ subject: "hooks",
982
+ shadowable: ["input", "run", "type", "description", "optional", "enum"],
983
+ };
984
+ const TOOL_KEYS = [
985
+ "title",
986
+ "description",
987
+ "for",
988
+ "input",
989
+ "output",
990
+ "annotations",
991
+ "handler",
992
+ "write",
993
+ "offer",
994
+ "textsLater",
995
+ "picturePrompt",
996
+ ];
997
+ const TOOL_OFFER_KEYS = ["textsLater"];
998
+ const TOOL_ANNOTATION_KEYS = ["readOnly", "consequential"];
999
+ const HOOK_KEYS = ["input", "run"];
976
1000
  const TOOL_FIELD_KEYS = ["type", "description", "optional", "enum"];
977
1001
  const TOOL_WRITE_KEYS = ["db", "set", "key"];
978
1002
  const TOOLS_SHAPE = 'tools must be `export const tools = { vote: { description: "…", input: { choice: "string" }, handler(input, ctx) { … } } }` with static literals';
1003
+ const HOOKS_SHAPE = 'hooks must be `export const hooks = { picturePrompt: { input: { addition: { type: "string", optional: true } }, run(input, ctx) { … } } }` with static literals';
1004
+ const TOOLS_FIELD_LANE = { lane: TOOLS_LANE, shape: TOOLS_SHAPE };
1005
+ const HOOKS_FIELD_LANE = { lane: HOOKS_LANE, shape: HOOKS_SHAPE };
979
1006
  function literalValue(raw) {
980
1007
  const s = raw.trim();
981
1008
  if (s === "true")
@@ -1062,8 +1089,8 @@ function toolStringPropertyAt(obj, key) {
1062
1089
  const start = key?.valueStart;
1063
1090
  return start === undefined ? undefined : toolStringLiteral(valueTextAt(obj, start));
1064
1091
  }
1065
- function toolObjectKeys(obj, where, allowed) {
1066
- const read = readableTopLevelKeys(obj, TOOLS_LANE, where);
1092
+ function toolObjectKeys(obj, where, allowed, fl = TOOLS_FIELD_LANE) {
1093
+ const read = readableTopLevelKeys(obj, fl.lane, where);
1067
1094
  if (read.keys === undefined)
1068
1095
  return { errors: read.errors };
1069
1096
  const out = new Map();
@@ -1071,11 +1098,11 @@ function toolObjectKeys(obj, where, allowed) {
1071
1098
  for (const k of read.keys) {
1072
1099
  const name = k.name ?? "";
1073
1100
  if (allowed.includes(name) === false) {
1074
- errors.push(`${TOOLS_SHAPE} — ${where} has an unknown key \`${name}\`; the keys are ${allowed.map((a) => `\`${a}\``).join(", ")}`);
1101
+ errors.push(`${fl.shape} — ${where} has an unknown key \`${name}\`; the keys are ${allowed.map((a) => `\`${a}\``).join(", ")}`);
1075
1102
  continue;
1076
1103
  }
1077
1104
  if (out.has(name)) {
1078
- errors.push(duplicateKeyError({ lane: TOOLS_LANE, where, key: name, count: named(read.keys, name).length }));
1105
+ errors.push(duplicateKeyError({ lane: fl.lane, where, key: name, count: named(read.keys, name).length }));
1079
1106
  continue;
1080
1107
  }
1081
1108
  out.set(name, k);
@@ -1091,13 +1118,13 @@ function objectValueOf(obj, key) {
1091
1118
  return undefined;
1092
1119
  return inner;
1093
1120
  }
1094
- function extractToolField(fields, key, where) {
1121
+ function extractToolField(fields, key, where, fl = TOOLS_FIELD_LANE) {
1095
1122
  const name = key.name ?? "";
1096
1123
  const at = `${where}.${name}`;
1097
1124
  if (TOOL_FIELD_NAME_PATTERN.test(name) === false) {
1098
- return { errors: [`${TOOLS_SHAPE} — ${at}: a field name is letters, digits and underscores, starting with a letter`] };
1125
+ return { errors: [`${fl.shape} — ${at}: a field name is letters, digits and underscores, starting with a letter`] };
1099
1126
  }
1100
- const typeError = `${TOOLS_SHAPE} — ${at} must be "string", "number" or "boolean", or { type: "string", description: "…", optional: true }`;
1127
+ const typeError = `${fl.shape} — ${at} must be "string", "number" or "boolean", or { type: "string", description: "…", optional: true }`;
1101
1128
  const isType = (t) => BACKEND_TOOL_FIELD_TYPES.some((x) => x === t);
1102
1129
  const shorthand = toolStringPropertyAt(fields, key);
1103
1130
  if (shorthand !== undefined) {
@@ -1106,7 +1133,7 @@ function extractToolField(fields, key, where) {
1106
1133
  const spec = objectValueOf(fields, key);
1107
1134
  if (spec === undefined)
1108
1135
  return { errors: [typeError] };
1109
- const specKeys = toolObjectKeys(spec, at, TOOL_FIELD_KEYS);
1136
+ const specKeys = toolObjectKeys(spec, at, TOOL_FIELD_KEYS, fl);
1110
1137
  if (specKeys.keys === undefined)
1111
1138
  return { errors: specKeys.errors };
1112
1139
  const type = toolStringPropertyAt(spec, specKeys.keys.get("type"));
@@ -1117,7 +1144,7 @@ function extractToolField(fields, key, where) {
1117
1144
  if (specKeys.keys.has("description")) {
1118
1145
  description = toolStringPropertyAt(spec, specKeys.keys.get("description"))?.trim();
1119
1146
  if (description === undefined || description === "" || description.length > MAX_TOOL_DESCRIPTION_LENGTH) {
1120
- errors.push(`${TOOLS_SHAPE} — ${at}.description must be a non-empty string literal of at most ${MAX_TOOL_DESCRIPTION_LENGTH} characters`);
1147
+ errors.push(`${fl.shape} — ${at}.description must be a non-empty string literal of at most ${MAX_TOOL_DESCRIPTION_LENGTH} characters`);
1121
1148
  }
1122
1149
  }
1123
1150
  let optional = false;
@@ -1125,7 +1152,7 @@ function extractToolField(fields, key, where) {
1125
1152
  const start = specKeys.keys.get("optional")?.valueStart;
1126
1153
  const v = start === undefined ? undefined : literalValue(valueTextAt(spec, start));
1127
1154
  if (typeof v !== "boolean")
1128
- errors.push(`${TOOLS_SHAPE} — ${at}.optional must be true or false`);
1155
+ errors.push(`${fl.shape} — ${at}.optional must be true or false`);
1129
1156
  else
1130
1157
  optional = v;
1131
1158
  }
@@ -1140,7 +1167,7 @@ function extractToolField(fields, key, where) {
1140
1167
  ? undefined
1141
1168
  : splitArrayEntries(body).map(toolStringLiteral);
1142
1169
  if (type !== "string" || parsed === undefined || parsed.length === 0 || parsed.some((v) => v === undefined || v === "")) {
1143
- errors.push(`${TOOLS_SHAPE} — ${at}.enum must be a non-empty array of string literals, on a "string" field`);
1170
+ errors.push(`${fl.shape} — ${at}.enum must be a non-empty array of string literals, on a "string" field`);
1144
1171
  }
1145
1172
  else {
1146
1173
  enumValues = parsed;
@@ -1159,6 +1186,37 @@ function extractToolField(fields, key, where) {
1159
1186
  errors,
1160
1187
  };
1161
1188
  }
1189
+ function extractToolFields(owner, key, o) {
1190
+ const fl = o.fl ?? TOOLS_FIELD_LANE;
1191
+ const out = [];
1192
+ const errors = [];
1193
+ const fields = objectValueOf(owner, key);
1194
+ const read = fields === undefined ? undefined : readableTopLevelKeys(fields, fl.lane, o.where);
1195
+ if (fields === undefined || read?.keys === undefined) {
1196
+ errors.push(...(read?.errors ?? [`${fl.shape} — ${o.where} must be an object literal of fields`]));
1197
+ }
1198
+ else if (read.keys.length > o.max) {
1199
+ errors.push(`${fl.shape} — ${o.where} declares ${read.keys.length} fields; ${o.tooMany} ${o.max}`);
1200
+ }
1201
+ else {
1202
+ for (const fk of read.keys) {
1203
+ if (out.some((f) => f.name === fk.name)) {
1204
+ errors.push(duplicateKeyError({ lane: fl.lane, where: o.where, key: fk.name ?? "?", count: named(read.keys, fk.name ?? "").length }));
1205
+ continue;
1206
+ }
1207
+ const field = extractToolField(fields, fk, o.where, fl);
1208
+ errors.push(...field.errors);
1209
+ if (field.value !== undefined)
1210
+ out.push(field.value);
1211
+ }
1212
+ }
1213
+ return { value: out, errors };
1214
+ }
1215
+ function booleanAt(obj, key) {
1216
+ const start = key?.valueStart;
1217
+ const v = start === undefined ? undefined : literalValue(valueTextAt(obj, start));
1218
+ return typeof v === "boolean" ? v : undefined;
1219
+ }
1162
1220
  function extractToolWrite(tool, key, where) {
1163
1221
  const at = `${where}.write`;
1164
1222
  const shape = `${TOOLS_SHAPE} — ${at} must be { db: "votes", set: { type: "vote" }, key: "caller" } with static literals`;
@@ -1247,33 +1305,22 @@ function extractTool(tools, key) {
1247
1305
  audience = known;
1248
1306
  }
1249
1307
  }
1308
+ let title;
1309
+ if (keys.keys.has("title")) {
1310
+ title = toolStringPropertyAt(tool, keys.keys.get("title"))?.trim();
1311
+ if (title === undefined || title === "" || title.length > MAX_TOOL_TITLE_LENGTH) {
1312
+ errors.push(`${TOOLS_SHAPE} — ${where}.title must be a non-empty string literal of at most ${MAX_TOOL_TITLE_LENGTH} characters; it is the short name a person sees`);
1313
+ }
1314
+ }
1250
1315
  const input = [];
1251
1316
  if (keys.keys.has("input")) {
1252
- const fields = objectValueOf(tool, keys.keys.get("input"));
1253
- const read = fields === undefined ? undefined : readableTopLevelKeys(fields, TOOLS_LANE, `${where}.input`);
1254
- if (fields === undefined || read?.keys === undefined) {
1255
- errors.push(...(read?.errors ?? [`${TOOLS_SHAPE} — ${where}.input must be an object literal of fields`]));
1256
- }
1257
- else if (read.keys.length > MAX_TOOL_INPUT_FIELDS) {
1258
- errors.push(`${TOOLS_SHAPE} — ${where}.input declares ${read.keys.length} fields; a tool takes at most ${MAX_TOOL_INPUT_FIELDS}`);
1259
- }
1260
- else {
1261
- for (const fk of read.keys) {
1262
- if (input.some((f) => f.name === fk.name)) {
1263
- errors.push(duplicateKeyError({
1264
- lane: TOOLS_LANE,
1265
- where: `${where}.input`,
1266
- key: fk.name ?? "?",
1267
- count: named(read.keys, fk.name ?? "").length,
1268
- }));
1269
- continue;
1270
- }
1271
- const field = extractToolField(fields, fk, `${where}.input`);
1272
- errors.push(...field.errors);
1273
- if (field.value !== undefined)
1274
- input.push(field.value);
1275
- }
1276
- }
1317
+ const read = extractToolFields(tool, keys.keys.get("input"), {
1318
+ where: `${where}.input`,
1319
+ max: MAX_TOOL_INPUT_FIELDS,
1320
+ tooMany: "a tool takes at most",
1321
+ });
1322
+ errors.push(...read.errors);
1323
+ input.push(...read.value);
1277
1324
  }
1278
1325
  const hasHandler = keys.keys.has("handler");
1279
1326
  const hasWrite = keys.keys.has("write");
@@ -1289,16 +1336,85 @@ function extractTool(tools, key) {
1289
1336
  errors.push(...w.errors);
1290
1337
  run = w.value;
1291
1338
  }
1339
+ let output;
1340
+ if (keys.keys.has("output")) {
1341
+ if (hasWrite) {
1342
+ errors.push(`${TOOLS_SHAPE} — ${where}.output goes on a handler tool; a declared write always answers { ok: true, id }`);
1343
+ }
1344
+ else {
1345
+ const read = extractToolFields(tool, keys.keys.get("output"), {
1346
+ where: `${where}.output`,
1347
+ max: MAX_TOOL_OUTPUT_FIELDS,
1348
+ tooMany: "a tool's output names at most",
1349
+ });
1350
+ errors.push(...read.errors);
1351
+ if (read.errors.length === 0)
1352
+ output = read.value;
1353
+ }
1354
+ }
1355
+ let annotations;
1356
+ if (keys.keys.has("annotations")) {
1357
+ const at = `${where}.annotations`;
1358
+ const obj = objectValueOf(tool, keys.keys.get("annotations"));
1359
+ const aKeys = obj === undefined ? undefined : toolObjectKeys(obj, at, TOOL_ANNOTATION_KEYS);
1360
+ if (obj === undefined) {
1361
+ errors.push(`${TOOLS_SHAPE} — ${at} must be an object literal like { readOnly: true } or { consequential: true }`);
1362
+ }
1363
+ else if (aKeys?.keys === undefined) {
1364
+ errors.push(...(aKeys?.errors ?? []));
1365
+ }
1366
+ else {
1367
+ const flags = { readOnly: false, consequential: false };
1368
+ let readable = true;
1369
+ for (const flag of TOOL_ANNOTATION_KEYS) {
1370
+ if (aKeys.keys.has(flag) === false)
1371
+ continue;
1372
+ const v = booleanAt(obj, aKeys.keys.get(flag));
1373
+ if (v === undefined) {
1374
+ errors.push(`${TOOLS_SHAPE} — ${at}.${flag} must be true or false`);
1375
+ readable = false;
1376
+ }
1377
+ else
1378
+ flags[flag] = v;
1379
+ }
1380
+ if (readable && flags.readOnly && flags.consequential) {
1381
+ errors.push(`${TOOLS_SHAPE} — ${at} says both readOnly and consequential; a tool that changes nothing has nothing to ask about first, so keep one`);
1382
+ }
1383
+ else if (readable && flags.readOnly && hasWrite) {
1384
+ errors.push(`${TOOLS_SHAPE} — ${at}.readOnly can't go on a declared write, which saves a record every time`);
1385
+ }
1386
+ else if (readable && (flags.readOnly || flags.consequential)) {
1387
+ annotations = flags.readOnly ? { readOnly: true } : { consequential: true };
1388
+ }
1389
+ }
1390
+ }
1292
1391
  let offer = false;
1392
+ let offerTextsLater = false;
1293
1393
  if (keys.keys.has("offer")) {
1294
- const start = keys.keys.get("offer")?.valueStart;
1295
- const v = start === undefined ? undefined : literalValue(valueTextAt(tool, start));
1296
- if (typeof v !== "boolean")
1297
- errors.push(`${TOOLS_SHAPE} — ${where}.offer must be true or false`);
1298
- else
1394
+ const offerShape = `${TOOLS_SHAPE} — ${where}.offer must be true or false, or { textsLater: true } for an offered tool that texts later`;
1395
+ const v = booleanAt(tool, keys.keys.get("offer"));
1396
+ const obj = v === undefined ? objectValueOf(tool, keys.keys.get("offer")) : undefined;
1397
+ if (v !== undefined)
1299
1398
  offer = v;
1399
+ else if (obj === undefined)
1400
+ errors.push(offerShape);
1401
+ else {
1402
+ const oKeys = toolObjectKeys(obj, `${where}.offer`, TOOL_OFFER_KEYS);
1403
+ if (oKeys.keys === undefined)
1404
+ errors.push(...oKeys.errors);
1405
+ else {
1406
+ offer = true;
1407
+ if (oKeys.keys.has("textsLater")) {
1408
+ const t = booleanAt(obj, oKeys.keys.get("textsLater"));
1409
+ if (t === undefined)
1410
+ errors.push(`${TOOLS_SHAPE} — ${where}.offer.textsLater must be true or false`);
1411
+ else
1412
+ offerTextsLater = t;
1413
+ }
1414
+ }
1415
+ }
1300
1416
  }
1301
- let textsLater = false;
1417
+ let textsLater = offerTextsLater;
1302
1418
  if (keys.keys.has("textsLater")) {
1303
1419
  const start = keys.keys.get("textsLater")?.valueStart;
1304
1420
  const v = start === undefined ? undefined : literalValue(valueTextAt(tool, start));
@@ -1307,7 +1423,7 @@ function extractTool(tools, key) {
1307
1423
  else if (v && !offer)
1308
1424
  errors.push(`${TOOLS_SHAPE} — ${where}.textsLater goes with offer: true, on the one tool the agent offers`);
1309
1425
  else
1310
- textsLater = v;
1426
+ textsLater = v || offerTextsLater;
1311
1427
  }
1312
1428
  let picturePrompt = false;
1313
1429
  if (keys.keys.has("picturePrompt")) {
@@ -1333,11 +1449,14 @@ function extractTool(tools, key) {
1333
1449
  for: audience,
1334
1450
  input,
1335
1451
  run,
1452
+ ...(title === undefined ? {} : { title }),
1453
+ ...(annotations === undefined ? {} : { annotations }),
1454
+ ...(output === undefined ? {} : { output }),
1336
1455
  ...(offer ? { offer: true } : {}),
1337
1456
  ...(textsLater ? { textsLater: true } : {}),
1338
- ...(picturePrompt ? { picturePrompt: true } : {}),
1339
1457
  },
1340
1458
  errors,
1459
+ ...(picturePrompt ? { picturePrompt: true } : {}),
1341
1460
  };
1342
1461
  }
1343
1462
  function extractTools(src) {
@@ -1358,6 +1477,7 @@ function extractTools(src) {
1358
1477
  }
1359
1478
  const errors = [];
1360
1479
  const decls = [];
1480
+ const builders = [];
1361
1481
  for (const key of read.keys) {
1362
1482
  if (decls.some((d) => d.name === key.name)) {
1363
1483
  errors.push(duplicateKeyError({
@@ -1372,15 +1492,117 @@ function extractTools(src) {
1372
1492
  errors.push(...t.errors);
1373
1493
  if (t.value !== undefined)
1374
1494
  decls.push(t.value);
1495
+ if (t.value !== undefined && t.picturePrompt === true)
1496
+ builders.push(t.value);
1375
1497
  }
1376
1498
  const offered = decls.filter((d) => d.offer === true);
1377
1499
  if (offered.length > 1) {
1378
1500
  errors.push(`${TOOLS_SHAPE} — ${offered.map((d) => `tools.${d.name}`).join(" and ")} both say offer: true; at most one tool may be the offer, the one the agent asks about after posting this vibe's picture`);
1379
1501
  }
1380
- const builders = decls.filter((d) => d.picturePrompt === true);
1381
1502
  if (builders.length > 1) {
1382
1503
  errors.push(`${TOOLS_SHAPE} — ${builders.map((d) => `tools.${d.name}`).join(" and ")} both say picturePrompt: true; at most one tool may build the picture prompt`);
1383
1504
  }
1505
+ if (errors.length > 0)
1506
+ return { errors };
1507
+ const builder = builders[0];
1508
+ if (builder === undefined)
1509
+ return { value: decls, errors };
1510
+ return {
1511
+ value: decls.filter((d) => d !== builder),
1512
+ errors,
1513
+ legacyHook: { name: "picturePrompt", input: builder.input, legacyTool: builder.name, for: builder.for },
1514
+ };
1515
+ }
1516
+ function plainlyNotAFunction(obj, key) {
1517
+ const start = key?.valueStart;
1518
+ if (start === undefined)
1519
+ return false;
1520
+ if (/^\s*`/.test(obj.raw.slice(start)))
1521
+ return true;
1522
+ const text = valueTextAt(obj, start).trim();
1523
+ return text === "" || /^(?:(?:null|undefined|true|false)\b|[-+]?\d|["'`[{])/.test(text);
1524
+ }
1525
+ function isHookName(name) {
1526
+ return BACKEND_HOOK_NAMES.some((n) => n === name);
1527
+ }
1528
+ function pictureHookInputProblem(input) {
1529
+ const fixed = 'input: { addition: { type: "string", optional: true } }';
1530
+ const [addition, ...rest] = input;
1531
+ if (addition === undefined || addition.name !== "addition" || rest.length > 0) {
1532
+ return `takes exactly one field, ${fixed}: the person's words, absent on a first photo`;
1533
+ }
1534
+ if (addition.type !== "string" || addition.optional === false || addition.enum !== undefined) {
1535
+ return `declares addition as an optional string with no enum: ${fixed}`;
1536
+ }
1537
+ return undefined;
1538
+ }
1539
+ function extractHooks(src) {
1540
+ if (exportsName(src.code, "hooks") === false)
1541
+ return { errors: [] };
1542
+ const hooks = extractExportedObject(src, "hooks", { wholeInitializer: true });
1543
+ if (hooks === undefined)
1544
+ return { errors: [`${HOOKS_SHAPE} — declare it once, as an exported top-level object literal`] };
1545
+ const known = BACKEND_HOOK_NAMES.map((n) => `\`${n}\``).join(", ");
1546
+ const read = readableTopLevelKeys(hooks, HOOKS_LANE, "the exported hooks object");
1547
+ if (read.keys === undefined)
1548
+ return { errors: read.errors };
1549
+ const errors = [];
1550
+ const decls = [];
1551
+ for (const key of read.keys) {
1552
+ const name = key.name;
1553
+ if (isHookName(name) === false) {
1554
+ errors.push(`${HOOKS_SHAPE} — hooks has no hook named \`${name ?? "?"}\`; the hooks are ${known}`);
1555
+ continue;
1556
+ }
1557
+ const where = `hooks.${name}`;
1558
+ if (decls.some((d) => d.name === name)) {
1559
+ errors.push(duplicateKeyError({
1560
+ lane: HOOKS_LANE,
1561
+ where: "the exported hooks object",
1562
+ key: name,
1563
+ count: named(read.keys, name).length,
1564
+ }));
1565
+ continue;
1566
+ }
1567
+ const hook = objectValueOf(hooks, key);
1568
+ if (hook === undefined) {
1569
+ errors.push(`${HOOKS_SHAPE} — ${where} must be an object literal with a run function`);
1570
+ continue;
1571
+ }
1572
+ const keys = toolObjectKeys(hook, where, HOOK_KEYS, HOOKS_FIELD_LANE);
1573
+ if (keys.keys === undefined) {
1574
+ errors.push(...keys.errors);
1575
+ continue;
1576
+ }
1577
+ if (keys.keys.has("run") === false) {
1578
+ errors.push(`${HOOKS_SHAPE} — ${where} needs run(input, ctx), the function the platform calls`);
1579
+ continue;
1580
+ }
1581
+ if (plainlyNotAFunction(hook, keys.keys.get("run"))) {
1582
+ errors.push(`${HOOKS_SHAPE} — ${where}.run must be a function: run(input, ctx) { … }, or the name of one`);
1583
+ continue;
1584
+ }
1585
+ let input = PICTURE_PROMPT_HOOK_INPUT;
1586
+ if (keys.keys.has("input")) {
1587
+ const fields = extractToolFields(hook, keys.keys.get("input"), {
1588
+ where: `${where}.input`,
1589
+ max: MAX_TOOL_INPUT_FIELDS,
1590
+ tooMany: "a hook takes at most",
1591
+ fl: HOOKS_FIELD_LANE,
1592
+ });
1593
+ if (fields.errors.length > 0) {
1594
+ errors.push(...fields.errors);
1595
+ continue;
1596
+ }
1597
+ const problem = pictureHookInputProblem(fields.value);
1598
+ if (problem !== undefined) {
1599
+ errors.push(`${HOOKS_SHAPE} — ${where} ${problem}`);
1600
+ continue;
1601
+ }
1602
+ input = fields.value;
1603
+ }
1604
+ decls.push({ name, input });
1605
+ }
1384
1606
  if (errors.length > 0)
1385
1607
  return { errors };
1386
1608
  return { value: decls, errors };
@@ -1431,6 +1653,18 @@ export function parseBackendConfig(source) {
1431
1653
  const parsedTools = extractTools(src);
1432
1654
  errors.push(...parsedTools.errors);
1433
1655
  const tools = parsedTools.value;
1656
+ const parsedHooks = extractHooks(src);
1657
+ errors.push(...parsedHooks.errors);
1658
+ const warnings = [];
1659
+ const legacyHook = parsedTools.legacyHook;
1660
+ const declaredHooks = parsedHooks.value ?? [];
1661
+ if (legacyHook !== undefined && declaredHooks.some((h) => h.name === legacyHook.name)) {
1662
+ errors.push(`${HOOKS_SHAPE} — hooks.picturePrompt and tools.${legacyHook.legacyTool} (picturePrompt: true) both build the picture prompt; keep hooks.picturePrompt and take picturePrompt: true off the tool`);
1663
+ }
1664
+ else if (legacyHook !== undefined) {
1665
+ warnings.push(`tools.${legacyHook.legacyTool}.picturePrompt: true is deprecated: move its handler to \`export const hooks = { picturePrompt: { input: { addition: { type: "string", optional: true } }, run(input, ctx) { … } } }\`. It still runs, as that hook: read-only (no ctx.db writes, no ctx.callAI, no ctx.notify, no outbound fetch), and it is no longer listed as a tool.`);
1666
+ }
1667
+ const hooks = legacyHook === undefined ? declaredHooks : [...declaredHooks, legacyHook];
1434
1668
  return {
1435
1669
  handlers,
1436
1670
  hasConfig,
@@ -1439,6 +1673,8 @@ export function parseBackendConfig(source) {
1439
1673
  connections,
1440
1674
  github,
1441
1675
  ...(tools === undefined ? {} : { tools }),
1676
+ ...(hooks.length === 0 || errors.length > 0 ? {} : { hooks }),
1677
+ ...(warnings.length === 0 ? {} : { warnings }),
1442
1678
  errors,
1443
1679
  };
1444
1680
  }
@@ -1,5 +1,4 @@
1
1
  export declare const SHORT_LINK_STRIP_PARAMS: ReadonlySet<string>;
2
- export declare function publicVibeBase(host: string): string | undefined;
3
2
  export declare function shortSelfLinks(text: string, host: string): string;
4
3
  export interface ShortSelfLinkHooks {
5
4
  readonly nav?: Navigator;
@@ -26,9 +26,6 @@ function appOwnedSearch(search) {
26
26
  }
27
27
  const PUBLIC_ORIGIN = "https://vibes.diy";
28
28
  const VIBE_LABEL_RE = /^([a-z0-9][a-z0-9-]*?)--([a-z0-9][a-z0-9-]+)$/i;
29
- export function publicVibeBase(host) {
30
- return publicBaseFor(host);
31
- }
32
29
  function publicBaseFor(host) {
33
30
  const label = host.split(":")[0]?.split(".")[0] ?? "";
34
31
  const m = VIBE_LABEL_RE.exec(label);