@happyvertical/smrt-chat 0.60.18 → 0.61.1

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 (86) hide show
  1. package/AGENTS.md +16 -22
  2. package/README.md +78 -0
  3. package/agents/owner-approvals.md +161 -0
  4. package/agents/runtime-exposure.md +28 -0
  5. package/agents/runtime-report-tools.md +26 -0
  6. package/agents/token-streaming.md +6 -0
  7. package/agents/tool-loop.md +13 -0
  8. package/agents/tool-summaries.md +155 -0
  9. package/agents/turn-drivers.md +293 -0
  10. package/dist/assistant-approvals.d.ts +45 -0
  11. package/dist/assistant-approvals.d.ts.map +1 -0
  12. package/dist/assistant-approvals.js +83 -0
  13. package/dist/assistant-approvals.js.map +1 -0
  14. package/dist/assistant-turn-driver.d.ts +73 -0
  15. package/dist/assistant-turn-driver.d.ts.map +1 -0
  16. package/dist/assistant-turn-events.d.ts +28 -1
  17. package/dist/assistant-turn-events.d.ts.map +1 -1
  18. package/dist/assistant-turn-events.js +2 -2
  19. package/dist/assistant-turn.d.ts +24 -37
  20. package/dist/assistant-turn.d.ts.map +1 -1
  21. package/dist/chunks/{ChatService-BGBAqmZq.js → ChatService-C1UBz0MR.js} +684 -657
  22. package/dist/chunks/ChatService-C1UBz0MR.js.map +1 -0
  23. package/dist/chunks/{assistant-turn-events-BbZUf-Ju.js → assistant-turn-events-DwdCZzQ0.js} +15 -2
  24. package/dist/chunks/assistant-turn-events-DwdCZzQ0.js.map +1 -0
  25. package/dist/chunks/chat-stream-4jlK2XS2.js +3571 -0
  26. package/dist/chunks/chat-stream-4jlK2XS2.js.map +1 -0
  27. package/dist/engines.d.ts +34 -0
  28. package/dist/engines.d.ts.map +1 -0
  29. package/dist/engines.js +260 -0
  30. package/dist/engines.js.map +1 -0
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +8 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/internal/agent-runtime.js +1 -1
  36. package/dist/manifest.json +3 -1
  37. package/dist/persona-conversation.d.ts.map +1 -1
  38. package/dist/runtime-report-tools.d.ts.map +1 -1
  39. package/dist/services/ChatService.d.ts +3 -13
  40. package/dist/services/ChatService.d.ts.map +1 -1
  41. package/dist/smrt-knowledge.json +46 -9
  42. package/dist/smrt-knowledge.okf.md +29 -4
  43. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte +198 -0
  44. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts +34 -0
  45. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts.map +1 -0
  46. package/dist/svelte/components/assistant/AssistantComposer.svelte +6 -3
  47. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts +2 -0
  48. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts.map +1 -1
  49. package/dist/svelte/components/assistant/AssistantDock.svelte +66 -17
  50. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +2 -0
  51. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -1
  52. package/dist/svelte/components/assistant/assistant-http-client.d.ts +2 -0
  53. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  54. package/dist/svelte/components/assistant/assistant-http-client.js +28 -1
  55. package/dist/svelte/components/assistant/assistant-transport.d.ts +18 -1
  56. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -1
  57. package/dist/svelte/components/assistant/assistant-transport.js +2 -0
  58. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +5 -1
  59. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -1
  60. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +80 -4
  61. package/dist/svelte/i18n.d.ts +14 -0
  62. package/dist/svelte/i18n.d.ts.map +1 -1
  63. package/dist/svelte/i18n.js +14 -0
  64. package/dist/svelte/i18n.messages.d.ts +13 -0
  65. package/dist/svelte/i18n.messages.d.ts.map +1 -1
  66. package/dist/svelte/i18n.messages.js +13 -0
  67. package/dist/svelte/index.d.ts +2 -1
  68. package/dist/svelte/index.d.ts.map +1 -1
  69. package/dist/svelte/index.js +1 -0
  70. package/dist/sveltekit.d.ts +72 -4
  71. package/dist/sveltekit.d.ts.map +1 -1
  72. package/dist/sveltekit.js +439 -21
  73. package/dist/sveltekit.js.map +1 -1
  74. package/dist/tool-loop.d.ts +36 -3
  75. package/dist/tool-loop.d.ts.map +1 -1
  76. package/dist/tool-summary.d.ts +15 -0
  77. package/dist/tool-summary.d.ts.map +1 -0
  78. package/dist/tool-summary.js +95 -0
  79. package/dist/tool-summary.js.map +1 -0
  80. package/dist/work-profile.d.ts +64 -0
  81. package/dist/work-profile.d.ts.map +1 -0
  82. package/package.json +36 -22
  83. package/dist/chunks/ChatService-BGBAqmZq.js.map +0 -1
  84. package/dist/chunks/assistant-turn-events-BbZUf-Ju.js.map +0 -1
  85. package/dist/chunks/chat-stream-Blri3lj0.js +0 -2743
  86. package/dist/chunks/chat-stream-Blri3lj0.js.map +0 -1
package/dist/sveltekit.js CHANGED
@@ -1,8 +1,12 @@
1
- import { i as clientRequestMessageId, n as ChatService, t as ChatClientRequestConflictError } from "./chunks/ChatService-BGBAqmZq.js";
2
- import { $ as isFallbackReply, D as createSessionContinuationStore, I as MAX_CLIENT_TOOL_RESULT_CHARS, N as FALLBACK_HISTORY_PLACEHOLDER, O as runAssistantTurn, T as createAssistantTurnResponse, X as buildManifestToolCatalog, at as sanitizeClientToolDeclarations, vt as chatUnavailableBody, y as ASSISTANT_TURN_GENERIC_ERROR, yt as chatUnconfiguredBody } from "./chunks/chat-stream-Blri3lj0.js";
3
- import { resolveInferenceTarget } from "@happyvertical/smrt-core";
4
- import { getCurrentSessionPermissionContext, getRequestScopedDatabase } from "@happyvertical/smrt-users";
1
+ import { a as sendAgentReply, i as clientRequestMessageId, n as ChatService, t as ChatClientRequestConflictError } from "./chunks/ChatService-C1UBz0MR.js";
2
+ import { $ as isFallbackReply, D as createSessionContinuationStore, I as MAX_CLIENT_TOOL_RESULT_CHARS, N as FALLBACK_HISTORY_PLACEHOLDER, O as runAssistantTurn, Q as invokeManifestTool, St as assertWorkProfileTool, T as createAssistantTurnResponse, X as buildManifestToolCatalog, b as AssistantTurnUserError, bt as chatUnconfiguredBody, ot as sanitizeClientToolDeclarations, xt as WorkProfileEscalation, y as ASSISTANT_TURN_GENERIC_ERROR, yt as chatUnavailableBody } from "./chunks/chat-stream-4jlK2XS2.js";
3
+ import { createAssistantApprovalBridge } from "./assistant-approvals.js";
4
+ import { describeAssistantTool } from "./tool-summary.js";
5
+ import { ObjectRegistry, resolveDatabase, resolveInferenceTarget } from "@happyvertical/smrt-core";
5
6
  import { withTenant } from "@happyvertical/smrt-tenancy";
7
+ import { PrincipalToolNotAllowedError, executeAsPrincipal } from "@happyvertical/smrt-agents";
8
+ import { PermissionResolver, getCurrentSessionPermissionContext, getRequestScopedDatabase } from "@happyvertical/smrt-users";
9
+ import { OwnerApprovalAuthority, OwnerApprovalError, createSqliteOwnerApprovalStore, isApprovalOwner } from "@happyvertical/smrt-app-runtime";
6
10
  import { AIProviderNotConfiguredError, getConfig, loadConfig, resolveConfiguredAIProvider, toAIClientOptions } from "@happyvertical/smrt-config";
7
11
  //#region src/sveltekit.ts
8
12
  var AssistantRouteError = class extends Error {
@@ -102,6 +106,7 @@ async function configuredAssistantAI(context) {
102
106
  ...base ? { base } : {},
103
107
  tenantId: principal.tenantId,
104
108
  className: "AssistantRoute",
109
+ ...context.workProfile ? { tier: context.workProfile.tier } : {},
105
110
  usage: {
106
111
  className: "AssistantRoute",
107
112
  tenantId: principal.tenantId
@@ -110,7 +115,10 @@ async function configuredAssistantAI(context) {
110
115
  }));
111
116
  if (!resolved.options) throw notConfigured;
112
117
  const { getAI } = await import("@happyvertical/ai");
113
- return getAI(resolved.options);
118
+ return getAI({
119
+ ...resolved.options,
120
+ ...context.workProfile?.model ? { model: context.workProfile.model } : {}
121
+ });
114
122
  }
115
123
  function unprovidedToolNames(requested, offered, registeredOnly) {
116
124
  const provided = new Set(offered.map((tool) => tool.slug));
@@ -238,6 +246,10 @@ function toAssistantMessageWire(message) {
238
246
  createdAt: toIso(message.created_at) ?? (/* @__PURE__ */ new Date(0)).toISOString(),
239
247
  ...attachments.length > 0 ? { attachments } : {},
240
248
  ...toolCallData ? { toolCallData } : {},
249
+ ...metadata && ("workRun" in metadata || "designRunId" in metadata) ? { metadata: {
250
+ ..."workRun" in metadata ? { workRun: metadata.workRun } : {},
251
+ ...typeof metadata.designRunId === "string" ? { designRunId: metadata.designRunId } : {}
252
+ } } : {},
241
253
  ...clientRequestId ? { clientRequestId } : {}
242
254
  };
243
255
  }
@@ -246,6 +258,9 @@ function isAuthorizationFailure(error) {
246
258
  return /authorization denied|not found|not active/i.test(message);
247
259
  }
248
260
  var ROUTE_METHODS = {
261
+ "owner-approvals": ["GET"],
262
+ approvals: ["GET"],
263
+ "decide-approval": ["POST"],
249
264
  threads: ["GET", "POST"],
250
265
  "thread-messages": ["GET", "POST"],
251
266
  "thread-resume": ["POST"],
@@ -255,6 +270,15 @@ var ROUTE_METHODS = {
255
270
  function matchRoute(segments) {
256
271
  const [a, b, c, ...rest] = segments;
257
272
  if (rest.length > 0) return null;
273
+ if (a === "approvals" && b === void 0) return { route: "owner-approvals" };
274
+ if (a === "threads" && b && c === "approvals") return {
275
+ route: "approvals",
276
+ threadId: b
277
+ };
278
+ if (a === "approvals" && b && c === "decide") return {
279
+ route: "decide-approval",
280
+ id: b
281
+ };
258
282
  if (a === "threads" && b === void 0) return { route: "threads" };
259
283
  if (a === "threads" && b && c === "messages") return {
260
284
  route: "thread-messages",
@@ -289,6 +313,42 @@ function mountAssistantRoutes(options = {}) {
289
313
  const maxBody = options.maxBodyBytes ?? 1048576;
290
314
  const maxContent = options.maxContentLength ?? 12e3;
291
315
  const historyLimit = Math.max(0, options.historyLimit ?? 20);
316
+ const internalRequests = /* @__PURE__ */ new WeakSet();
317
+ const publicMessage = (message) => {
318
+ const wire = toAssistantMessageWire(message);
319
+ if (options.toolPresentation !== "generic" || wire.role !== "tool") return wire;
320
+ const approval = parseObject(wire.toolCallData?.approval);
321
+ if (typeof approval?.id === "string") return {
322
+ ...wire,
323
+ content: "Review this change",
324
+ toolCallData: { approval: {
325
+ id: approval.id,
326
+ tool: "change",
327
+ callId: approval.id,
328
+ summary: "Review this change"
329
+ } }
330
+ };
331
+ const tool = wire.toolCallData;
332
+ const name = typeof tool?.name === "string" ? tool.name : typeof tool?.tool === "string" ? tool.tool : "";
333
+ const ok = ![
334
+ "error",
335
+ "refused",
336
+ "rejected",
337
+ "denied"
338
+ ].includes(String(tool?.status));
339
+ const label = describeAssistantTool(name, void 0, {
340
+ ok,
341
+ observation: void 0
342
+ }, { recordLabels: "generic" });
343
+ return {
344
+ ...wire,
345
+ content: label,
346
+ toolCallData: {
347
+ label,
348
+ status: ok ? "success" : "error"
349
+ }
350
+ };
351
+ };
292
352
  const checkOrigin = options.checkOrigin ?? true;
293
353
  const trustedOrigins = options.trustedOrigins ?? [];
294
354
  const resolvePrincipal = options.resolvePrincipal ?? ((event) => resolveAssistantPrincipalFromLocals(event.locals));
@@ -420,10 +480,29 @@ function mountAssistantRoutes(options = {}) {
420
480
  };
421
481
  };
422
482
  const prepareTurn = async (context, body) => {
423
- const model = resolveModel(body.model);
483
+ const workProfile = await options.resolveWorkProfile?.(context);
484
+ context = {
485
+ ...context,
486
+ workProfile
487
+ };
488
+ const model = workProfile?.model ?? resolveModel(body.model);
424
489
  const allowedTools = await allowedToolsFor(context);
425
490
  const clientTools = sanitizeClientToolDeclarations(body.clientTools, options.clientToolAllowList ?? []);
426
- const ai = await resolveAI(context, model);
491
+ let turnDriver;
492
+ try {
493
+ turnDriver = await options.resolveTurnDriver?.({
494
+ ...context,
495
+ model
496
+ }) ?? options.turnDriver;
497
+ if (turnDriver && typeof turnDriver.run !== "function") throw new Error("The turn driver has no run method.");
498
+ } catch (error) {
499
+ const unavailable = unavailableRouteError(error);
500
+ if (unavailable) throw unavailable;
501
+ if (error instanceof AssistantTurnUserError) throw new AssistantRouteError(503, error.code, error.message);
502
+ safeLog(error);
503
+ throw new AssistantRouteError(503, "assistant_unavailable", "The assistant is unavailable right now. Please try again later.");
504
+ }
505
+ const ai = turnDriver ? void 0 : await resolveAI(context, model);
427
506
  const abort = new AbortController();
428
507
  const requestSignal = context.event.request.signal;
429
508
  if (requestSignal.aborted) abort.abort();
@@ -431,9 +510,11 @@ function mountAssistantRoutes(options = {}) {
431
510
  return {
432
511
  abort,
433
512
  ai,
513
+ turnDriver,
434
514
  model,
435
515
  allowedTools,
436
- clientTools
516
+ clientTools,
517
+ workProfile
437
518
  };
438
519
  };
439
520
  const turnSetup = async (context, chat, session, thread, prepared, mirror = true) => {
@@ -445,7 +526,7 @@ function mountAssistantRoutes(options = {}) {
445
526
  dbFor(context)
446
527
  ]);
447
528
  const tools = await manifestToolsFor(context, allowedTools, extraTools ?? [], db);
448
- if (options.authorInvocation && mirror) {
529
+ if (mirror) {
449
530
  const current = session.getAllowedTools();
450
531
  if (current.length !== allowedTools.length || current.some((tool, index) => tool !== allowedTools[index])) await chat.updateAgentSessionConfig({
451
532
  agentSessionId: String(session.id),
@@ -454,6 +535,28 @@ function mountAssistantRoutes(options = {}) {
454
535
  allowedTools
455
536
  });
456
537
  }
538
+ const approvalPolicy = await resolveValue(options.approvalPolicy, context);
539
+ let bridge;
540
+ const bridgeFor = () => bridge ??= authorityFor(context).then(async (authority) => createAssistantApprovalBridge({
541
+ authority,
542
+ tenantId: principal.tenantId,
543
+ requestedBy: principal.userId,
544
+ policy: approvalPolicy,
545
+ context: JSON.parse(JSON.stringify({
546
+ principal,
547
+ permissionCeiling: principal.permissions ?? [...(await (await PermissionResolver.create({ ...db ? { db } : {} })).resolvePermissions(principal.userId, principal.tenantId)).permissions],
548
+ threadId: String(thread.id),
549
+ agentSessionId: String(session.id),
550
+ driver: prepared.turnDriver ? "external" : "builtin",
551
+ allowedTools
552
+ }))
553
+ }));
554
+ const approvals = {
555
+ policy: approvalPolicy,
556
+ request: async (call) => (await bridgeFor()).request(call),
557
+ wait: async (request, driverContext) => (await bridgeFor()).wait(request, driverContext),
558
+ complete: async (request, ok, result) => (await bridgeFor()).complete(request, ok, result)
559
+ };
457
560
  const continuations = continuationStoreFor(context, chat, session);
458
561
  return {
459
562
  abort,
@@ -464,6 +567,36 @@ function mountAssistantRoutes(options = {}) {
464
567
  continuationKey: String(thread.id),
465
568
  turn: {
466
569
  ai,
570
+ turnDriver: prepared.turnDriver,
571
+ workProfile: prepared.workProfile,
572
+ deferDesignTurn: await resolveValue(options.deferDesignTurn, context),
573
+ designTools: options.designTools,
574
+ resolveWorkProfileRuntime: async (workProfile) => {
575
+ const nextContext = {
576
+ ...context,
577
+ workProfile
578
+ };
579
+ const turnDriver = await options.resolveTurnDriver?.({
580
+ ...nextContext,
581
+ model: workProfile.model
582
+ }) ?? options.turnDriver;
583
+ return {
584
+ turnDriver,
585
+ ai: turnDriver ? void 0 : await resolveAI(nextContext, workProfile.model)
586
+ };
587
+ },
588
+ onWorkRun: options.onWorkRun,
589
+ ...options.formatAssistantReply ? { formatAssistantReply: (content) => options.formatAssistantReply(content, context) } : {},
590
+ ...options.onDesignEscalation ? { onDesignEscalation: (input) => options.onDesignEscalation(context, input) } : {},
591
+ ...options.resolveWorkProfile ? { resolveWorkProfile: (name) => options.resolveWorkProfile(context, name) } : {},
592
+ waitForApproval: options.waitForApproval,
593
+ approvalPolicy,
594
+ approvals: prepared.turnDriver && (options.waitForApproval || prepared.turnDriver.waitForApproval) && !options.approvals ? void 0 : approvals,
595
+ thread: {
596
+ id: String(thread.id),
597
+ roomId: String(session.chatRoomId),
598
+ agentSessionId: String(session.id)
599
+ },
467
600
  principal: {
468
601
  runAsUserId: principal.userId,
469
602
  tenantId: principal.tenantId,
@@ -500,31 +633,88 @@ function mountAssistantRoutes(options = {}) {
500
633
  } } : {},
501
634
  ...options.describeTool ? { describeTool: options.describeTool } : {},
502
635
  onError: safeLog,
503
- serializeMessage: (message) => toAssistantMessageWire(message),
636
+ serializeMessage: (message) => {
637
+ if (!internalRequests.has(context.event.request)) return publicMessage(message);
638
+ const wire = toAssistantMessageWire(message);
639
+ const metadata = parseObject(message.metadata);
640
+ return {
641
+ ...wire,
642
+ ...metadata && "designOutput" in metadata ? { metadata: {
643
+ ...wire.metadata,
644
+ designOutput: metadata.designOutput
645
+ } } : {}
646
+ };
647
+ },
504
648
  author: {
505
649
  chatService: chat,
506
650
  agentSessionId: String(session.id),
507
651
  tenantId: principal.tenantId,
508
652
  threadId: String(thread.id),
653
+ ...internalRequests.has(context.event.request) ? { metadata: { assistantInternalTurn: true } } : {},
509
654
  ...options.authorInvocation ? { authorInvocation: options.authorInvocation } : {},
510
655
  ...options.collapseRecoveredFailures ? { collapseRecoveredFailures: true } : {}
511
656
  }
512
657
  }
513
658
  };
514
659
  };
515
- const stream = (events, abort) => createAssistantTurnResponse(events, {
660
+ const stream = (events, abort, internalTurn = false) => createAssistantTurnResponse((async function* () {
661
+ for await (const event of events) {
662
+ if (internalTurn || options.toolPresentation !== "generic") {
663
+ yield event;
664
+ continue;
665
+ }
666
+ if (event.type === "token") continue;
667
+ if (event.type === "step" && event.step.kind !== "thinking") {
668
+ const step = event.step;
669
+ const label = describeAssistantTool(step.tool, void 0, step.kind === "tool_result" ? {
670
+ ok: step.ok,
671
+ observation: void 0
672
+ } : void 0, { recordLabels: "generic" });
673
+ yield {
674
+ ...event,
675
+ step: {
676
+ ...step,
677
+ tool: "change",
678
+ label: step.kind === "tool_call" ? "Working on this action" : label,
679
+ ...step.kind === "tool_result" ? { error: void 0 } : {}
680
+ }
681
+ };
682
+ } else if (event.type === "status") yield {
683
+ ...event,
684
+ status: {
685
+ ...event.status,
686
+ label: event.status.state === "working" ? "Working on your request" : event.status.state === "done" ? "Done" : event.status.state === "error" ? "Could not complete this request" : null
687
+ }
688
+ };
689
+ else if (event.type === "approval_needed") yield {
690
+ ...event,
691
+ approval: {
692
+ id: event.approval.id,
693
+ callId: event.approval.id,
694
+ tool: "change",
695
+ summary: "Review this change"
696
+ }
697
+ };
698
+ else if (event.type === "error") yield {
699
+ ...event,
700
+ error: "Could not complete this request."
701
+ };
702
+ else yield event;
703
+ }
704
+ })(), {
516
705
  ...options.heartbeatMs !== void 0 ? { heartbeatMs: options.heartbeatMs } : {},
517
706
  onError: safeLog,
518
707
  onCancel: () => abort.abort()
519
708
  });
520
709
  const respondWithTurn = async (context, chat, session, thread, prepared, setup, first, start, durableSend) => {
710
+ const internalTurn = internalRequests.has(context.event.request);
521
711
  const transaction = requestTransaction();
522
- if (!transaction) return stream(detached(first, pump(start(chat, setup))).events, prepared.abort);
712
+ if (!transaction) return stream(detached(first, pump(start(chat, setup))).events, prepared.abort, internalTurn);
523
713
  const isActive = transaction.isActive;
524
714
  if (!runtime || typeof isActive !== "function") {
525
715
  const turn = detached(first, pump(start(chat, setup)));
526
716
  await turn.settled;
527
- return stream(turn.events, prepared.abort);
717
+ return stream(turn.events, prepared.abort, internalTurn);
528
718
  }
529
719
  const { principal } = context;
530
720
  const bound = {
@@ -611,7 +801,7 @@ function mountAssistantRoutes(options = {}) {
611
801
  });
612
802
  }
613
803
  };
614
- return stream(detached(first, ownLifetime).events, prepared.abort);
804
+ return stream(detached(first, ownLifetime).events, prepared.abort, internalTurn);
615
805
  };
616
806
  const listThreads = async (context) => {
617
807
  const chat = await chatFor(context);
@@ -650,12 +840,52 @@ function mountAssistantRoutes(options = {}) {
650
840
  const chat = await chatFor(context);
651
841
  const session = await findSession(chat, principal);
652
842
  await requireOwnThread(chat, principal, session, threadId);
653
- return json({ items: (await chat.getThreadMessages({
843
+ let items = (await chat.getThreadMessages({
654
844
  threadId,
655
845
  actorProfileId: principal.profileId,
656
846
  tenantId: principal.tenantId,
657
- limit: 200
658
- })).map(toAssistantMessageWire) });
847
+ limit: 200,
848
+ visibility: "conversation"
849
+ })).map(publicMessage);
850
+ if (options.approvals || options.approvalContinuations) {
851
+ let approvals = [];
852
+ try {
853
+ approvals = await ownedThreadApprovals(context, threadId);
854
+ } catch (error) {
855
+ if (!(error instanceof OwnerApprovalError) || error.code !== "forbidden") throw error;
856
+ }
857
+ const shown = new Set(items.flatMap((message) => {
858
+ const approval = parseObject(message.toolCallData?.approval);
859
+ return typeof approval?.id === "string" ? [approval.id] : [];
860
+ }));
861
+ const oldestPersisted = items.length ? Math.min(...items.map((message) => Date.parse(message.createdAt))) : -Infinity;
862
+ const unsettled = new Set(approvals.filter((record) => record.continuation && [
863
+ "pending",
864
+ "approved",
865
+ "executing"
866
+ ].includes(record.status)).map((record) => record.id));
867
+ for (const record of approvals) {
868
+ if (!record.continuation || !unsettled.has(record.id) && record.createdAt < oldestPersisted || shown.has(record.id)) continue;
869
+ const view = await publicApproval(record);
870
+ items.push({
871
+ id: `approval:${record.id}`,
872
+ threadId,
873
+ role: "tool",
874
+ content: view.summary,
875
+ createdAt: new Date(record.createdAt).toISOString(),
876
+ toolCallData: { approval: view }
877
+ });
878
+ shown.add(record.id);
879
+ }
880
+ items.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
881
+ const outstanding = items.filter((message) => {
882
+ const approval = parseObject(message.toolCallData?.approval);
883
+ return typeof approval?.id === "string" && unsettled.has(approval.id);
884
+ });
885
+ const outstandingIds = new Set(outstanding.map((message) => message.id));
886
+ items = [...items.filter((message) => !outstandingIds.has(message.id)).slice(-200), ...outstanding].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
887
+ }
888
+ return json({ items });
659
889
  };
660
890
  const reservationAnswer = async (context, chat, session, threadId, messageId) => {
661
891
  const { principal } = context;
@@ -663,12 +893,13 @@ function mountAssistantRoutes(options = {}) {
663
893
  threadId,
664
894
  messageId,
665
895
  actorProfileId: principal.profileId,
666
- tenantId: principal.tenantId
896
+ tenantId: principal.tenantId,
897
+ visibility: "conversation"
667
898
  });
668
899
  const anchor = stored?.message;
669
900
  if (!stored || anchor?.role !== "user" || anchor.senderProfileId !== principal.profileId) return null;
670
- const userMessage = toAssistantMessageWire(anchor);
671
- const after = stored.replies.map(toAssistantMessageWire);
901
+ const userMessage = publicMessage(anchor);
902
+ const after = stored.replies.map(publicMessage);
672
903
  const assistantMessage = [...after].reverse().find((message) => message.role === "assistant");
673
904
  const answer = (outcome) => {
674
905
  return json({
@@ -743,6 +974,38 @@ function mountAssistantRoutes(options = {}) {
743
974
  const session = await findSession(chat, principal);
744
975
  const thread = await requireOwnThread(chat, principal, session, threadId);
745
976
  if (!session?.chatRoomId) throw notFound();
977
+ const internal = await options.internalTurn?.(context);
978
+ if (internal) {
979
+ if (!internal.userMessage.trim()) throw badRequest("The pass input is empty.");
980
+ if (internal.originMessageId) {
981
+ const original = await chat.getThreadMessageReplies({
982
+ threadId,
983
+ messageId: internal.originMessageId,
984
+ actorProfileId: principal.profileId,
985
+ tenantId: principal.tenantId
986
+ });
987
+ if (original?.message?.role !== "user" || original.message.senderProfileId !== principal.profileId) throw notFound();
988
+ }
989
+ internalRequests.add(context.event.request);
990
+ const prepared2 = await prepareTurn(context, body);
991
+ const setup2 = await turnSetup(context, chat, session, thread, prepared2);
992
+ const history = (historyLimit > 0 ? await chat.getThreadMessages({
993
+ threadId,
994
+ actorProfileId: principal.profileId,
995
+ tenantId: principal.tenantId,
996
+ limit: historyLimit,
997
+ roles: HISTORY_REPLAY_ROLES
998
+ }) : []).filter((message) => message.role === "user" || message.role === "assistant").map((message) => ({
999
+ role: message.role,
1000
+ content: message.role === "assistant" && isFallbackReply(message) ? FALLBACK_HISTORY_PLACEHOLDER : message.content
1001
+ }));
1002
+ return respondWithTurn(context, chat, session, thread, prepared2, setup2, null, (_turnChat, turnSetupFor) => runAssistantTurn({
1003
+ ...turnSetupFor.turn,
1004
+ history,
1005
+ userMessage: internal.userMessage,
1006
+ originMessageId: internal.originMessageId
1007
+ }));
1008
+ }
746
1009
  const reservationId = clientRequestMessageId({
747
1010
  tenantId: principal.tenantId,
748
1011
  roomId: session.chatRoomId,
@@ -917,6 +1180,154 @@ function mountAssistantRoutes(options = {}) {
917
1180
  }, 500);
918
1181
  }
919
1182
  };
1183
+ const authorityFor = async (context) => {
1184
+ const supplied = await resolveValue(options.approvals, context);
1185
+ if (supplied) return supplied;
1186
+ const configured = await dbFor(context);
1187
+ const db = configured ? await resolveDatabase(configured) : (await ObjectRegistry.getCollection("@happyvertical/smrt-chat:AgentSession", {})).db;
1188
+ return new OwnerApprovalAuthority(await createSqliteOwnerApprovalStore(db), (actor) => isApprovalOwner(db, actor));
1189
+ };
1190
+ const approvalActor = (context) => ({
1191
+ id: context.principal.userId,
1192
+ tenantId: context.principal.tenantId
1193
+ });
1194
+ const publicApproval = async (record) => {
1195
+ const presentation = options.toolPresentation === "generic" ? await options.presentApproval?.(record) : void 0;
1196
+ return {
1197
+ id: record.id,
1198
+ tool: options.toolPresentation === "generic" ? "change" : record.tool,
1199
+ callId: record.continuation || options.toolPresentation === "generic" ? record.id : record.callId,
1200
+ summary: options.toolPresentation === "generic" ? presentation?.summary ?? "Review this change" : record.summary,
1201
+ ...presentation ? { presentation: { summary: presentation.summary } } : {},
1202
+ status: record.status,
1203
+ decidedBy: record.decidedBy,
1204
+ decidedAt: record.decidedAt,
1205
+ ...options.toolPresentation === "generic" || record.continuation || record.result === void 0 ? {} : { result: record.result }
1206
+ };
1207
+ };
1208
+ const ownedThreadApprovals = async (context, threadId) => {
1209
+ const chat = await chatFor(context);
1210
+ await requireOwnThread(chat, context.principal, await findSession(chat, context.principal), threadId);
1211
+ return (await (await authorityFor(context)).list(approvalActor(context), false)).filter((record) => {
1212
+ const principal = parseObject(record.context.principal);
1213
+ return record.tenantId === context.principal.tenantId && record.requestedBy === context.principal.userId && record.context.threadId === threadId && principal?.userId === context.principal.userId && principal.tenantId === context.principal.tenantId && principal.profileId === context.principal.profileId;
1214
+ });
1215
+ };
1216
+ const listApprovals = async (context, threadId) => json({ approvals: await Promise.all((await ownedThreadApprovals(context, threadId)).map(publicApproval)) });
1217
+ const decideApproval = async (context, id) => {
1218
+ const body = await readJsonObject(context.event.request, maxBody);
1219
+ if (typeof body.approve !== "boolean") throw badRequest("Choose approve or deny.");
1220
+ const authority = await authorityFor(context);
1221
+ await authority.authorize(approvalActor(context));
1222
+ const record = await authority.get(context.principal.tenantId, id);
1223
+ if (!record) throw notFound();
1224
+ if (record.continuation) {
1225
+ const continuations = await resolveValue(options.approvalContinuations, context);
1226
+ if (!continuations) throw notFound();
1227
+ return json({ approval: await publicApproval(await continuations.decide(approvalActor(context), id, body.approve)) });
1228
+ }
1229
+ const original = record.context.principal;
1230
+ const originalContext = {
1231
+ event: context.event,
1232
+ principal: original
1233
+ };
1234
+ const chat = await chatFor(originalContext);
1235
+ const session = await findSession(chat, original);
1236
+ const threadId = String(record.context.threadId);
1237
+ await requireOwnThread(chat, original, session, threadId);
1238
+ if (!session || String(session.id) !== record.context.agentSessionId) throw notFound();
1239
+ let decision = await authority.decide(approvalActor(context), id, body.approve);
1240
+ const authorResult = async (content, ok, refused = false, label = content) => sendAgentReply(chat, {
1241
+ tenantId: original.tenantId,
1242
+ agentSessionId: String(session.id),
1243
+ threadId,
1244
+ replyToMessageId: typeof record.context.originMessageId === "string" ? record.context.originMessageId : null,
1245
+ kind: "tool",
1246
+ messageType: "tool_result",
1247
+ content,
1248
+ toolCallData: {
1249
+ id: record.callId,
1250
+ name: record.tool,
1251
+ args: record.args,
1252
+ status: refused ? "refused" : ok ? "success" : "error",
1253
+ approvalId: id,
1254
+ label
1255
+ }
1256
+ });
1257
+ if (decision.status === "denied") {
1258
+ await authorResult("The owner denied this tool call. It did not run.", false);
1259
+ await sendAgentReply(chat, {
1260
+ tenantId: original.tenantId,
1261
+ agentSessionId: String(session.id),
1262
+ threadId,
1263
+ kind: "assistant",
1264
+ messageType: "text",
1265
+ content: "The owner denied this tool call. It did not run.",
1266
+ metadata: {
1267
+ approvalId: id,
1268
+ approvalStatus: "denied"
1269
+ }
1270
+ });
1271
+ } else if (decision.status === "approved" && record.context.driver === "builtin") {
1272
+ await authority.consume(original.tenantId, id);
1273
+ let result;
1274
+ let ok = false;
1275
+ let refused = false;
1276
+ try {
1277
+ const allowed = (await allowedToolsFor(originalContext)).filter((name) => record.context.allowedTools.includes(name) && session.getAllowedTools().includes(name));
1278
+ const db = await dbFor(originalContext);
1279
+ const permissions = [...(await (await PermissionResolver.create({ ...db ? { db } : {} })).resolvePermissions(original.userId, original.tenantId)).permissions].filter((permission) => record.context.permissionCeiling.includes(permission));
1280
+ const extra = [...await resolveValue(options.extraTools, originalContext) ?? []];
1281
+ const tools = await manifestToolsFor(originalContext, allowed, extra, db);
1282
+ result = await executeAsPrincipal({
1283
+ principal: {
1284
+ runAsUserId: original.userId,
1285
+ tenantId: original.tenantId,
1286
+ allowedTools: allowed
1287
+ },
1288
+ ...db ? { db } : {},
1289
+ permissions,
1290
+ postgresRls: options.postgresRls,
1291
+ audit: options.audit
1292
+ }, async (run) => {
1293
+ run.assertToolAllowed(record.tool);
1294
+ const tool = tools.find((tool2) => tool2.slug === record.tool);
1295
+ if (tool) return invokeManifestTool(run, tool, record.args, { db: run.context.database ?? db });
1296
+ const custom = extra.find((tool2) => tool2.slug === record.tool);
1297
+ if (!custom) throw new Error("The approved tool is no longer offered.");
1298
+ return custom.execute({
1299
+ run,
1300
+ args: record.args,
1301
+ db: run.context.database ?? db
1302
+ });
1303
+ });
1304
+ ok = !(result && typeof result === "object" && "isError" in result && result.isError === true);
1305
+ } catch (error) {
1306
+ safeLog(error);
1307
+ refused = error instanceof PrincipalToolNotAllowedError;
1308
+ result = {
1309
+ ...refused ? { status: "refused" } : {},
1310
+ error: "The approved tool could not run."
1311
+ };
1312
+ }
1313
+ await authority.complete(original.tenantId, id, ok, result);
1314
+ const completed = await authority.get(original.tenantId, id);
1315
+ if (!completed) throw notFound();
1316
+ decision = completed;
1317
+ let label = describeAssistantTool(record.tool, record.args, {
1318
+ ok,
1319
+ observation: completed.result
1320
+ });
1321
+ try {
1322
+ label = options.describeTool?.(record.tool, record.args, {
1323
+ ok,
1324
+ observation: completed.result
1325
+ }) || label;
1326
+ } catch {}
1327
+ await authorResult(ok ? label : JSON.stringify(completed.result ?? null), ok, refused, label);
1328
+ }
1329
+ return json({ approval: await publicApproval(decision) });
1330
+ };
920
1331
  const handle = async (event) => {
921
1332
  try {
922
1333
  const segments = segmentsOf(event);
@@ -937,6 +1348,9 @@ function mountAssistantRoutes(options = {}) {
937
1348
  principal
938
1349
  };
939
1350
  switch (match.route) {
1351
+ case "owner-approvals": return json({ approvals: await Promise.all((await (await authorityFor(context)).list(approvalActor(context), false)).map(publicApproval)) });
1352
+ case "approvals": return await listApprovals(context, requireId(match.threadId, "thread id"));
1353
+ case "decide-approval": return await decideApproval(context, requireId(match.id, "approval id"));
940
1354
  case "threads": return method === "GET" ? await listThreads(context) : await createThread(context);
941
1355
  case "thread-messages": {
942
1356
  const threadId = requireId(match.threadId, "thread id");
@@ -947,6 +1361,10 @@ function mountAssistantRoutes(options = {}) {
947
1361
  case "actions": return await runAction(context, match.phase);
948
1362
  }
949
1363
  } catch (error) {
1364
+ if (error instanceof OwnerApprovalError) return json({
1365
+ error: error.message,
1366
+ code: error.code
1367
+ }, error.code === "forbidden" ? 403 : error.code === "not_found" ? 404 : error.code === "invalid_request" ? 400 : 409);
950
1368
  if (error instanceof AssistantRouteError) return errorResponse(error);
951
1369
  if (isAuthorizationFailure(error)) return errorResponse(notFound());
952
1370
  safeLog(error);
@@ -1030,6 +1448,6 @@ function detached(first, produce) {
1030
1448
  };
1031
1449
  }
1032
1450
  //#endregion
1033
- export { ASSISTANT_DOCK_SESSION_KEY, AssistantRouteError, DEFAULT_ASSISTANT_ABANDONED_TURN_MS, DEFAULT_ASSISTANT_AGENT_ID, DEFAULT_ASSISTANT_MAX_ATTACHMENT_BYTES, DEFAULT_ASSISTANT_MAX_BODY_BYTES, DEFAULT_ASSISTANT_TURN_START_TIMEOUT_MS, MAX_ASSISTANT_REQUEST_CONTEXT_BYTES, mountAssistantRoutes, resolveAssistantPrincipalFromLocals, toAssistantMessageWire, toAssistantThreadWire };
1451
+ export { ASSISTANT_DOCK_SESSION_KEY, AssistantRouteError, DEFAULT_ASSISTANT_ABANDONED_TURN_MS, DEFAULT_ASSISTANT_AGENT_ID, DEFAULT_ASSISTANT_MAX_ATTACHMENT_BYTES, DEFAULT_ASSISTANT_MAX_BODY_BYTES, DEFAULT_ASSISTANT_TURN_START_TIMEOUT_MS, MAX_ASSISTANT_REQUEST_CONTEXT_BYTES, WorkProfileEscalation, assertWorkProfileTool, configuredAssistantAI, mountAssistantRoutes, resolveAssistantPrincipalFromLocals, toAssistantMessageWire, toAssistantThreadWire };
1034
1452
 
1035
1453
  //# sourceMappingURL=sveltekit.js.map