@vibes.diy/api-svc 14.2.6 → 14.2.8

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 (140) hide show
  1. package/cf-serve.js +1 -1
  2. package/cf-serve.js.map +1 -1
  3. package/check-auth.d.ts +3 -2
  4. package/check-build-auth.d.ts +18 -0
  5. package/check-build-auth.js +73 -0
  6. package/check-build-auth.js.map +1 -0
  7. package/create-handler.js +13 -6
  8. package/create-handler.js.map +1 -1
  9. package/evento-handler-manifest.js +5 -0
  10. package/evento-handler-manifest.js.map +1 -1
  11. package/guest-build-token.d.ts +16 -0
  12. package/guest-build-token.js +44 -0
  13. package/guest-build-token.js.map +1 -0
  14. package/index.d.ts +0 -2
  15. package/index.js +0 -2
  16. package/index.js.map +1 -1
  17. package/intern/agent-actor.d.ts +1 -0
  18. package/intern/agent-actor.js +1 -1
  19. package/intern/agent-actor.js.map +1 -1
  20. package/intern/agent-assembly.d.ts +0 -2
  21. package/intern/agent-assembly.js +1 -4
  22. package/intern/agent-assembly.js.map +1 -1
  23. package/intern/agent-first-turn-eligible.d.ts +1 -7
  24. package/intern/agent-first-turn-eligible.js +2 -5
  25. package/intern/agent-first-turn-eligible.js.map +1 -1
  26. package/intern/agent-router.d.ts +1 -3
  27. package/intern/agent-router.js +1 -17
  28. package/intern/agent-router.js.map +1 -1
  29. package/intern/agent-session-instruction.js.map +1 -1
  30. package/intern/agent-turn.d.ts +1 -4
  31. package/intern/agent-turn.js +4 -7
  32. package/intern/agent-turn.js.map +1 -1
  33. package/intern/agent-wake.d.ts +2 -3
  34. package/intern/agent-wake.js +2 -24
  35. package/intern/agent-wake.js.map +1 -1
  36. package/intern/attach-draft-handle.d.ts +2 -1
  37. package/intern/attach-draft-handle.js +128 -68
  38. package/intern/attach-draft-handle.js.map +1 -1
  39. package/intern/automatic-draft-attachment.d.ts +10 -0
  40. package/intern/automatic-draft-attachment.js +25 -0
  41. package/intern/automatic-draft-attachment.js.map +1 -0
  42. package/intern/codegen-build-lock.d.ts +0 -5
  43. package/intern/codegen-build-lock.js +0 -3
  44. package/intern/codegen-build-lock.js.map +1 -1
  45. package/intern/draft-continuation.d.ts +6 -0
  46. package/intern/draft-continuation.js +86 -0
  47. package/intern/draft-continuation.js.map +1 -0
  48. package/intern/draft-runtime-store.d.ts +10 -0
  49. package/intern/draft-runtime-store.js +46 -0
  50. package/intern/draft-runtime-store.js.map +1 -0
  51. package/intern/ensure-chat-id.d.ts +4 -3
  52. package/intern/ensure-chat-id.js +23 -4
  53. package/intern/ensure-chat-id.js.map +1 -1
  54. package/intern/first-build-request.d.ts +10 -0
  55. package/intern/first-build-request.js +69 -0
  56. package/intern/first-build-request.js.map +1 -0
  57. package/intern/get-model-defaults.d.ts +1 -0
  58. package/intern/get-model-defaults.js +4 -1
  59. package/intern/get-model-defaults.js.map +1 -1
  60. package/intern/guest-build-issuance.d.ts +9 -0
  61. package/intern/guest-build-issuance.js +83 -0
  62. package/intern/guest-build-issuance.js.map +1 -0
  63. package/intern/guest-build-start.d.ts +8 -0
  64. package/intern/guest-build-start.js +66 -0
  65. package/intern/guest-build-start.js.map +1 -0
  66. package/intern/guest-build-store.d.ts +50 -0
  67. package/intern/guest-build-store.js +231 -0
  68. package/intern/guest-build-store.js.map +1 -0
  69. package/intern/guest-build-usage.d.ts +7 -0
  70. package/intern/guest-build-usage.js +18 -0
  71. package/intern/guest-build-usage.js.map +1 -0
  72. package/intern/mint-decision.js.map +1 -1
  73. package/intern/mint-fire-core.js.map +1 -1
  74. package/intern/mint-job-store.d.ts +11 -1
  75. package/intern/mint-job-store.js +44 -6
  76. package/intern/mint-job-store.js.map +1 -1
  77. package/intern/open-turn-store.d.ts +0 -4
  78. package/intern/open-turn-store.js +1 -6
  79. package/intern/open-turn-store.js.map +1 -1
  80. package/intern/open-turn-sweep.js +0 -1
  81. package/intern/open-turn-sweep.js.map +1 -1
  82. package/intern/prompt-assembly.d.ts +1 -0
  83. package/intern/prompt-assembly.js +1 -0
  84. package/intern/prompt-assembly.js.map +1 -1
  85. package/models.json +1 -0
  86. package/package.json +12 -12
  87. package/public/attach-draft-handle.js +16 -3
  88. package/public/attach-draft-handle.js.map +1 -1
  89. package/public/draft-runtime.d.ts +5 -0
  90. package/public/draft-runtime.js +299 -0
  91. package/public/draft-runtime.js.map +1 -0
  92. package/public/get-chat-details.js +14 -6
  93. package/public/get-chat-details.js.map +1 -1
  94. package/public/get-chat-response.js +16 -9
  95. package/public/get-chat-response.js.map +1 -1
  96. package/public/guest-build-generation.d.ts +8 -0
  97. package/public/guest-build-generation.js +218 -0
  98. package/public/guest-build-generation.js.map +1 -0
  99. package/public/guest-build.d.ts +7 -0
  100. package/public/guest-build.js +127 -0
  101. package/public/guest-build.js.map +1 -0
  102. package/public/llm-dispatch.d.ts +9 -7
  103. package/public/llm-dispatch.js +22 -10
  104. package/public/llm-dispatch.js.map +1 -1
  105. package/public/open-chat.d.ts +5 -1
  106. package/public/open-chat.js +72 -38
  107. package/public/open-chat.js.map +1 -1
  108. package/public/prompt-chat-section.d.ts +2 -1
  109. package/public/prompt-chat-section.js +293 -303
  110. package/public/prompt-chat-section.js.map +1 -1
  111. package/public/shared-mint.js +4 -2
  112. package/public/shared-mint.js.map +1 -1
  113. package/public/stream-assembly.d.ts +9 -7
  114. package/public/stream-assembly.js +19 -5
  115. package/public/stream-assembly.js.map +1 -1
  116. package/types.d.ts +2 -0
  117. package/types.js.map +1 -1
  118. package/usage-report/billing-reconcile-util.d.ts +1 -0
  119. package/usage-report/billing-reconcile-util.js +2 -1
  120. package/usage-report/billing-reconcile-util.js.map +1 -1
  121. package/usage-report/codegen-delivery-alert-util.js.map +1 -1
  122. package/usage-report/draft-output-alert.d.ts +13 -0
  123. package/usage-report/draft-output-alert.js +25 -0
  124. package/usage-report/draft-output-alert.js.map +1 -0
  125. package/usage-report/new-user-alert-util.d.ts +1 -0
  126. package/usage-report/new-user-alert-util.js +19 -4
  127. package/usage-report/new-user-alert-util.js.map +1 -1
  128. package/usage-report/new-user-alert.js +16 -10
  129. package/usage-report/new-user-alert.js.map +1 -1
  130. package/usage-report/prompt-cost-sql.d.ts +2 -0
  131. package/usage-report/prompt-cost-sql.js +2 -0
  132. package/usage-report/prompt-cost-sql.js.map +1 -1
  133. package/usage-report/user-journey.js +2 -2
  134. package/usage-report/user-journey.js.map +1 -1
  135. package/intern/agent-instruction.d.ts +0 -2
  136. package/intern/agent-instruction.js +0 -433
  137. package/intern/agent-instruction.js.map +0 -1
  138. package/intern/agent-lane-flag.d.ts +0 -21
  139. package/intern/agent-lane-flag.js +0 -10
  140. package/intern/agent-lane-flag.js.map +0 -1
@@ -1,3 +1,5 @@
1
+ import { checkBuildAuth } from "../check-build-auth.js";
2
+ import { handleGuestPrompt } from "./guest-build-generation.js";
1
3
  import { Result, Option, EventoResult, exception2Result } from "@adviser/cement";
2
4
  import { scopey } from "@adviser/scopey";
3
5
  import { isReqCreationPromptChatSection, isReqPromptApplicationChatSection, isReqPromptFSChatSection, isReqPromptImageChatSection, isReqPromptLLMChatSection, reqPromptChatSection, canonicalModelUsage, isBuildNotifyMode, isSourceChangingMode, shouldNotify, RESEARCH_BLOCK_SEQ, } from "@vibes.diy/api-types";
@@ -27,12 +29,11 @@ import { bumpAppRecency } from "../intern/bump-app-recency.js";
27
29
  import { waitChatPersistIdle } from "../intern/chat-persist-gate.js";
28
30
  import { peekInFlightTurns } from "../intern/in-flight-turns.js";
29
31
  import { acquireTurnBuildLock, peekBuildLockEntry, releaseTurnBuildLock } from "../intern/codegen-build-lock.js";
30
- import { agentFirstTurnEnabled, agentLaneEnabled, agentSessionEnabled } from "../intern/agent-lane-flag.js";
31
32
  import { deliverAgentSession } from "../intern/agent-session-runtime.js";
32
33
  import { readAgentSession } from "../intern/agent-session-store.js";
33
34
  import { runEditVibeTool } from "../intern/agent-build-tools.js";
34
35
  import { claimFirstTurnMint, claimMintJob, getMintJob } from "../intern/mint-job-store.js";
35
- import { codegenTurnLane, legacyVariantHint, mintRowSaysFirstTurnIsAgents, routeAgentTurn, } from "../intern/agent-router.js";
36
+ import { codegenTurnLane, mintRowSaysFirstTurnIsAgents, routeAgentTurn } from "../intern/agent-router.js";
36
37
  import { assembleAgentPayload } from "../intern/agent-assembly.js";
37
38
  import { claimAgentAppContext, composeAgentRequest, isAppContextMessage, markJournalCacheTail, } from "../intern/agent-request-frame.js";
38
39
  import { createAgentBelt } from "../intern/agent-belt.js";
@@ -121,7 +122,7 @@ async function getResChatFromMode(vctx, req, orig) {
121
122
  const resChat = { ...iResChat, mode: orig.mode };
122
123
  return Result.Ok(resChat);
123
124
  }
124
- export const promptChatSection = {
125
+ const accountPromptChatSection = {
125
126
  hash: "prompt-chat-section-handler",
126
127
  validate: unwrapMsgBase(async (msg) => {
127
128
  const ret = reqPromptChatSection(msg.payload);
@@ -159,9 +160,8 @@ export const promptChatSection = {
159
160
  const agentWakeBudget = readAgentWakeBudget(orig.agentWakeBudget);
160
161
  const agentWakeNoteRaw = orig.agentWakeNote;
161
162
  const agentWakeNote = agentWakeTurn === true && typeof agentWakeNoteRaw === "string" ? agentWakeNoteRaw : undefined;
162
- const agentLane = agentLaneEnabled(vctx);
163
- const firstTurnAgent = agentLane && agentFirstTurnEnabled(vctx) && orig.firstTurnAgent === true;
164
- const nonInteractive = agentLane && orig.nonInteractive === true;
163
+ const firstTurnAgent = orig.firstTurnAgent === true;
164
+ const nonInteractive = orig.nonInteractive === true;
165
165
  let agentFetchUrlContext;
166
166
  await waitChatPersistIdle(vctx.connections, req.chatId, { logger: vctx.logger });
167
167
  const rResChat = await getResChatFromMode(vctx, req, orig);
@@ -207,7 +207,6 @@ export const promptChatSection = {
207
207
  }
208
208
  }
209
209
  const routeInput = {
210
- agentLane,
211
210
  codegenChatTurn: true,
212
211
  dryRun: orig.dryRun === true,
213
212
  directBuildRequested,
@@ -216,10 +215,8 @@ export const promptChatSection = {
216
215
  firstTurnAgent,
217
216
  };
218
217
  let agentRoute = routeAgentTurn(routeInput);
219
- const mintRowWorthReading = agentLane &&
220
- agentFirstTurnEnabled(vctx) &&
221
- ((agentRoute.route === "codegen" && agentRoute.skip === "first-turn") ||
222
- (agentRoute.route === "agent" && hasPriorTurn === true));
218
+ const mintRowWorthReading = (agentRoute.route === "codegen" && agentRoute.skip === "first-turn") ||
219
+ (agentRoute.route === "agent" && hasPriorTurn === true);
223
220
  if (mintRowWorthReading) {
224
221
  const rJob = await getMintJob(vctx, req.chatId);
225
222
  if (rJob.isErr()) {
@@ -249,184 +246,179 @@ export const promptChatSection = {
249
246
  appSlug: resChat.appSlug,
250
247
  activatedUrls: activateWorkUrls(currentUserMessageText(orig.prompt.messages.filter(isChatMessage))),
251
248
  });
252
- const legacyHint = legacyVariantHint(orig.variant);
253
249
  const buildInFlight = peekBuildLockEntry(vctx.connections, req.chatId);
254
- const rSeenHead = agentSessionEnabled(vctx) ? await readAgentSession(vctx.sql, req.chatId) : undefined;
255
- if (rSeenHead !== undefined && rSeenHead.isErr())
250
+ const rSeenHead = await readAgentSession(vctx.sql, req.chatId);
251
+ if (rSeenHead.isErr())
256
252
  vctx.logger.Warn().Err(rSeenHead).Str("chatId", req.chatId).Msg("agent-session-head-read-failed");
257
- const lastSeenHeadFsId = rSeenHead !== undefined && rSeenHead.isOk() ? rSeenHead.Ok().snapshot?.headFsId : undefined;
253
+ const lastSeenHeadFsId = rSeenHead.isOk() ? rSeenHead.Ok().snapshot?.headFsId : undefined;
258
254
  const rAgent = await assembleAgentPayload(vctx, {
259
255
  chatId: req.chatId,
260
256
  userId: req._auth.verifiedAuth.claims.userId,
261
- model: modelId,
257
+ model: orig.prompt.model ?? rDefaults.Ok().agent.model.id,
262
258
  ownerHandle: resChat.ownerHandle,
263
259
  appSlug: resChat.appSlug,
264
260
  newUserMessages: orig.prompt.messages.filter(isChatMessage),
265
- ...(legacyHint === undefined ? {} : { legacyHint }),
266
261
  ...(agentWakeNote === undefined ? {} : { wakeNote: agentWakeNote }),
267
262
  ...(buildInFlight === undefined ? {} : { buildInFlight: { promptId: buildInFlight.promptId } }),
268
263
  ...(agentFirstTurnMint ? { noAppYet: true } : {}),
269
264
  ...(nonInteractive ? { nonInteractive: true } : {}),
270
- ...(agentSessionEnabled(vctx) ? { session: true } : {}),
271
265
  ...(lastSeenHeadFsId === undefined ? {} : { lastSeenHeadFsId }),
272
266
  });
273
267
  if (rAgent.isErr())
274
268
  return Result.Err(rAgent);
275
269
  agentAssembled = { model: rAgent.Ok().model, messages: rAgent.Ok().messages };
276
- if (agentSessionEnabled(vctx)) {
277
- const rawIncoming = orig.prompt.messages.filter(isUserChatMessage);
278
- const newMessageCount = orig.prompt.messages.filter(isChatMessage).length;
279
- const incoming = newMessageCount === 0 ? [] : rAgent.Ok().messages.slice(-newMessageCount).filter(isUserChatMessage);
280
- const delivered = incoming.length === 0 && agentWakeTurn
281
- ? [
282
- {
283
- role: "user",
284
- content: [
285
- {
286
- type: "text",
287
- text: agentWakeNote ??
288
- "[session resumed] Continue from your persisted context and pending results. Inspect outcomes before retrying interrupted tools.",
289
- },
290
- ],
291
- },
292
- ]
293
- : incoming;
294
- const acquired = await deliverAgentSession(vctx, {
270
+ const rawIncoming = orig.prompt.messages.filter(isUserChatMessage);
271
+ const newMessageCount = orig.prompt.messages.filter(isChatMessage).length;
272
+ const incoming = newMessageCount === 0 ? [] : rAgent.Ok().messages.slice(-newMessageCount).filter(isUserChatMessage);
273
+ const delivered = incoming.length === 0 && agentWakeTurn
274
+ ? [
275
+ {
276
+ role: "user",
277
+ content: [
278
+ {
279
+ type: "text",
280
+ text: agentWakeNote ??
281
+ "[session resumed] Continue from your persisted context and pending results. Inspect outcomes before retrying interrupted tools.",
282
+ },
283
+ ],
284
+ },
285
+ ]
286
+ : incoming;
287
+ const acquired = await deliverAgentSession(vctx, {
288
+ chatId: req.chatId,
289
+ userId: req._auth.verifiedAuth.claims.userId,
290
+ ownerHandle: resChat.ownerHandle,
291
+ appSlug: resChat.appSlug,
292
+ }, { id: ctx.validated.tid, messages: delivered }, rAgent.Ok().messages.filter((message) => message.role === "system" || isAppContextMessage(message)));
293
+ if (acquired.isErr())
294
+ return Result.Err(acquired.Err());
295
+ const { live, created } = acquired.Ok();
296
+ const composedHead = rAgent.Ok().headFsId;
297
+ if (composedHead !== undefined) {
298
+ const noted = await live.session.observeHead(composedHead);
299
+ if (noted.isErr())
300
+ vctx.logger.Warn().Err(noted).Str("chatId", req.chatId).Msg("agent-session-head-note-failed");
301
+ }
302
+ if (created === false) {
303
+ const receiptId = vctx.sthis.nextId(12).str;
304
+ const receiptEvidence = createAgentEvidenceWriter({
295
305
  chatId: req.chatId,
296
- userId: req._auth.verifiedAuth.claims.userId,
297
- ownerHandle: resChat.ownerHandle,
298
- appSlug: resChat.appSlug,
299
- }, { id: ctx.validated.tid, messages: delivered }, rAgent.Ok().messages.filter((message) => message.role === "system" || isAppContextMessage(message)));
300
- if (acquired.isErr())
301
- return Result.Err(acquired.Err());
302
- const { live, created } = acquired.Ok();
303
- const composedHead = rAgent.Ok().headFsId;
304
- if (composedHead !== undefined) {
305
- const noted = await live.session.observeHead(composedHead);
306
- if (noted.isErr())
307
- vctx.logger.Warn().Err(noted).Str("chatId", req.chatId).Msg("agent-session-head-note-failed");
308
- }
309
- if (created === false) {
310
- const receiptId = vctx.sthis.nextId(12).str;
311
- const receiptEvidence = createAgentEvidenceWriter({
306
+ promptId: receiptId,
307
+ sessionId: live.promptId,
308
+ append: (evt, blockSeq) => appendBlockEvent({ ctx, vctx, req, promptId: receiptId, blockSeq, evt }),
309
+ });
310
+ const linked = await receiptEvidence({ kind: "active" });
311
+ if (linked.isErr())
312
+ return Result.Err(linked.Err());
313
+ await ctx.send.send(ctx, wrapMsgBase(ctx.validated, {
314
+ payload: {
315
+ type: "vibes.diy.res-prompt-chat-section",
312
316
  chatId: req.chatId,
317
+ ownerHandle: resChat.ownerHandle,
318
+ appSlug: resChat.appSlug,
313
319
  promptId: receiptId,
314
- sessionId: live.promptId,
315
- append: (evt, blockSeq) => appendBlockEvent({ ctx, vctx, req, promptId: receiptId, blockSeq, evt }),
316
- });
317
- const linked = await receiptEvidence({ kind: "active" });
318
- if (linked.isErr())
319
- return Result.Err(linked.Err());
320
- await ctx.send.send(ctx, wrapMsgBase(ctx.validated, {
321
- payload: {
322
- type: "vibes.diy.res-prompt-chat-section",
323
- chatId: req.chatId,
324
- ownerHandle: resChat.ownerHandle,
325
- appSlug: resChat.appSlug,
326
- promptId: receiptId,
327
- outerTid: req.outerTid,
328
- mode: req.mode,
329
- },
330
- tid: ctx.validated.tid,
331
- src: "agentSession",
332
- }));
333
- const echo = await appendBlockEvent({
334
- ctx,
335
- vctx,
336
- req,
337
- promptId: receiptId,
338
- blockSeq: 0,
339
- evt: {
340
- type: "prompt.req",
341
- ...(orig.mode === "codegen" && orig.source === "suggestion" ? { source: "suggestion" } : {}),
342
- streamId: receiptId,
343
- chatId: req.chatId,
344
- seq: 0,
345
- request: { messages: rawIncoming },
346
- timestamp: new Date(),
347
- },
348
- });
349
- if (echo.isErr())
350
- return Result.Err(echo.Err());
351
- const terminal = await appendBlockEvent({
352
- ctx,
353
- vctx,
354
- req,
355
- promptId: receiptId,
356
- blockSeq: 1,
357
- evt: {
358
- type: "block.end",
359
- streamId: receiptId,
360
- blockId: receiptId,
361
- blockNr: 0,
362
- seq: 1,
363
- timestamp: new Date(),
364
- stats: {
365
- toplevel: { lines: 0, bytes: 0 },
366
- code: { lines: 0, bytes: 0 },
367
- image: { lines: 0, bytes: 0 },
368
- total: { lines: 0, bytes: 0 },
369
- },
370
- usage: { given: [], calculated: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 } },
320
+ outerTid: req.outerTid,
321
+ mode: req.mode,
322
+ },
323
+ tid: ctx.validated.tid,
324
+ src: "agentSession",
325
+ }));
326
+ const echo = await appendBlockEvent({
327
+ ctx,
328
+ vctx,
329
+ req,
330
+ promptId: receiptId,
331
+ blockSeq: 0,
332
+ evt: {
333
+ type: "prompt.req",
334
+ ...(orig.mode === "codegen" && orig.source === "suggestion" ? { source: "suggestion" } : {}),
335
+ streamId: receiptId,
336
+ chatId: req.chatId,
337
+ seq: 0,
338
+ request: { messages: rawIncoming },
339
+ timestamp: new Date(),
340
+ },
341
+ });
342
+ if (echo.isErr())
343
+ return Result.Err(echo.Err());
344
+ const terminal = await appendBlockEvent({
345
+ ctx,
346
+ vctx,
347
+ req,
348
+ promptId: receiptId,
349
+ blockSeq: 1,
350
+ evt: {
351
+ type: "block.end",
352
+ streamId: receiptId,
353
+ blockId: receiptId,
354
+ blockNr: 0,
355
+ seq: 1,
356
+ timestamp: new Date(),
357
+ stats: {
358
+ toplevel: { lines: 0, bytes: 0 },
359
+ code: { lines: 0, bytes: 0 },
360
+ image: { lines: 0, bytes: 0 },
361
+ total: { lines: 0, bytes: 0 },
371
362
  },
372
- });
373
- if (terminal.isErr())
374
- return Result.Err(terminal.Err());
375
- const ended = await appendBlockEvent({
376
- ctx,
377
- vctx,
378
- req,
379
- promptId: receiptId,
380
- blockSeq: 2,
381
- evt: { type: "prompt.block-end", streamId: receiptId, chatId: req.chatId, seq: 2, timestamp: new Date() },
382
- });
383
- if (ended.isErr())
384
- return Result.Err(ended.Err());
385
- return Result.Ok(EventoResult.Continue);
386
- }
387
- agentSession = live;
388
- agentEvidence = observeEvidenceLine(createAgentEvidenceWriter({
389
- chatId: req.chatId,
390
- promptId: live.promptId,
391
- sessionId: live.promptId,
392
- append: (evt, blockSeq) => appendBlockEvent({ ctx, vctx, req, promptId: live.promptId, blockSeq, evt }),
393
- }), turnLatency);
394
- const active = await agentEvidence({
395
- kind: "active",
396
- ...(live.supersedes === undefined ? {} : { supersedes: live.supersedes }),
363
+ usage: { given: [], calculated: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 } },
364
+ },
397
365
  });
398
- if (active.isErr()) {
399
- live.close();
400
- return Result.Err(active.Err());
401
- }
402
- if (live.session.messages().length === 0) {
403
- const initial = agentAssembled.messages.slice(0, agentAssembled.messages.length - newMessageCount - (agentWakeNote === undefined ? 0 : 1));
404
- const saved = await live.session.checkpoint(initial);
405
- if (saved.isErr()) {
406
- live.close();
407
- return Result.Err(saved.Err());
408
- }
409
- }
410
- const events = await nextAgentSessionMessages(live.session, agentEvidence);
411
- if (events.isErr()) {
412
- live.close();
413
- return Result.Err(events.Err());
414
- }
415
- agentAssembled = {
416
- ...agentAssembled,
417
- messages: composeAgentRequest({
418
- system: agentAssembled.messages.filter((message) => message.role === "system"),
419
- journal: markJournalCacheTail(live.session.messages()),
420
- context: agentAssembled.messages.filter(isAppContextMessage),
421
- tail: events.Ok() ?? [],
422
- }),
423
- };
424
- const saved = await live.session.checkpoint(agentAssembled.messages);
366
+ if (terminal.isErr())
367
+ return Result.Err(terminal.Err());
368
+ const ended = await appendBlockEvent({
369
+ ctx,
370
+ vctx,
371
+ req,
372
+ promptId: receiptId,
373
+ blockSeq: 2,
374
+ evt: { type: "prompt.block-end", streamId: receiptId, chatId: req.chatId, seq: 2, timestamp: new Date() },
375
+ });
376
+ if (ended.isErr())
377
+ return Result.Err(ended.Err());
378
+ return Result.Ok(EventoResult.Continue);
379
+ }
380
+ agentSession = live;
381
+ agentEvidence = observeEvidenceLine(createAgentEvidenceWriter({
382
+ chatId: req.chatId,
383
+ promptId: live.promptId,
384
+ sessionId: live.promptId,
385
+ append: (evt, blockSeq) => appendBlockEvent({ ctx, vctx, req, promptId: live.promptId, blockSeq, evt }),
386
+ }), turnLatency);
387
+ const active = await agentEvidence({
388
+ kind: "active",
389
+ ...(live.supersedes === undefined ? {} : { supersedes: live.supersedes }),
390
+ });
391
+ if (active.isErr()) {
392
+ live.close();
393
+ return Result.Err(active.Err());
394
+ }
395
+ if (live.session.messages().length === 0) {
396
+ const initial = agentAssembled.messages.slice(0, agentAssembled.messages.length - newMessageCount - (agentWakeNote === undefined ? 0 : 1));
397
+ const saved = await live.session.checkpoint(initial);
425
398
  if (saved.isErr()) {
426
399
  live.close();
427
400
  return Result.Err(saved.Err());
428
401
  }
429
402
  }
403
+ const events = await nextAgentSessionMessages(live.session, agentEvidence);
404
+ if (events.isErr()) {
405
+ live.close();
406
+ return Result.Err(events.Err());
407
+ }
408
+ agentAssembled = {
409
+ ...agentAssembled,
410
+ messages: composeAgentRequest({
411
+ system: agentAssembled.messages.filter((message) => message.role === "system"),
412
+ journal: markJournalCacheTail(live.session.messages()),
413
+ context: agentAssembled.messages.filter(isAppContextMessage),
414
+ tail: events.Ok() ?? [],
415
+ }),
416
+ };
417
+ const saved = await live.session.checkpoint(agentAssembled.messages);
418
+ if (saved.isErr()) {
419
+ live.close();
420
+ return Result.Err(saved.Err());
421
+ }
430
422
  }
431
423
  else {
432
424
  const rAssembled = await assemblePromptPayload(vctx, {
@@ -552,8 +544,10 @@ export const promptChatSection = {
552
544
  }
553
545
  else if (agentAssembled !== undefined && isReqPromptLLMChatSection(orig)) {
554
546
  const agentPayload = agentAssembled;
547
+ const liveSession = agentSession;
548
+ if (liveSession === undefined)
549
+ return Result.Err("Agent turn has no session");
555
550
  prompSectionAction = async (scope, blockSeq) => {
556
- const liveSession = agentSession;
557
551
  const rActor = await resolveAgentActor(vctx, {
558
552
  userId: req._auth.verifiedAuth.claims.userId,
559
553
  scope: agentFirstTurnMint
@@ -570,12 +564,9 @@ export const promptChatSection = {
570
564
  appSlug: resChat.appSlug,
571
565
  editBaseFsId: undefined,
572
566
  });
573
- if (liveSession !== undefined && rVfs.isErr())
567
+ if (rVfs.isErr())
574
568
  return Result.Err(rVfs.Err());
575
- if (rVfs.isErr()) {
576
- vctx.logger.Warn().Err(rVfs).Str("chatId", req.chatId).Msg("agent-turn-vfs-load-failed");
577
- }
578
- const vfs = new Map(rVfs.isOk() ? rVfs.Ok() : []);
569
+ const vfs = new Map(rVfs.Ok());
579
570
  function extendDeadlineForAwaitedBuild(awaiting) {
580
571
  void extendOpenTurnDeadline(vctx.sql, {
581
572
  chatId: req.chatId,
@@ -597,18 +588,14 @@ export const promptChatSection = {
597
588
  const dispatcher = createAgentBuildDispatcher({
598
589
  vctx,
599
590
  host: ctx,
600
- auth: orig.auth,
591
+ auth: req.auth,
601
592
  outerTid: req.outerTid,
602
593
  handle: (dispatchCtx) => promptChatSection.handle(dispatchCtx),
603
- wakeBudget: liveSession === undefined ? agentWakeBudget : 0,
604
- ...(agentSession === undefined
605
- ? {}
606
- : {
607
- onPendingBuild: (t) => {
608
- extendDeadlineForAwaitedBuild(t.promptId);
609
- return agentSession?.watch(t.promptId);
610
- },
611
- }),
594
+ wakeBudget: 0,
595
+ onPendingBuild: (t) => {
596
+ extendDeadlineForAwaitedBuild(t.promptId);
597
+ return liveSession.watch(t.promptId);
598
+ },
612
599
  ...(agentFirstTurnMint
613
600
  ? {
614
601
  firstTurn: {
@@ -643,8 +630,8 @@ export const promptChatSection = {
643
630
  : {}),
644
631
  ...(agentFetchUrlContext === undefined ? {} : { fetchUrl: agentFetchUrlContext }),
645
632
  dispatcher,
646
- ...(liveSession === undefined ? {} : { queueEdit: (input) => liveSession.queue(input) }),
647
- ...(liveSession === undefined ? {} : { fileSession: liveSession }),
633
+ queueEdit: (input) => liveSession.queue(input),
634
+ fileSession: liveSession,
648
635
  onStyleApplied: async (applied) => {
649
636
  await appendBlockEvent({
650
637
  ctx,
@@ -666,7 +653,7 @@ export const promptChatSection = {
666
653
  },
667
654
  onDispatch: (dispatched) => {
668
655
  liveAppSlug = dispatched.appSlug;
669
- liveSession?.claimAppAddress(dispatched.appSlug);
656
+ liveSession.claimAppAddress(dispatched.appSlug);
670
657
  firstTurnAppClaimed = true;
671
658
  vctx.logger
672
659
  .Info()
@@ -675,106 +662,104 @@ export const promptChatSection = {
675
662
  },
676
663
  });
677
664
  turnToolsOffered = belt.definitions.map((d) => d.function.name);
678
- if (agentSession !== undefined) {
679
- await agentSession.bind((input) => runEditVibeTool(vctx, {
680
- actor: rActor.Ok(),
681
- chatId: req.chatId,
682
- input,
683
- dispatcher,
684
- toolsOffered: belt.definitions.map((d) => d.function.name),
685
- }), async (commit) => {
686
- if (firstTurnAppClaimed === false)
687
- return Result.Ok({
688
- ok: false,
689
- reason: "no-app-yet",
690
- message: "Call create_vibe first; there is no app to edit until it has been created.",
691
- });
692
- const currentActor = await resolveAgentActor(vctx, {
693
- userId: rActor.Ok().userId,
694
- requestedHandle: rActor.Ok().ownerHandle,
695
- scope: rActor.Ok().scope,
665
+ await liveSession.bind((input) => runEditVibeTool(vctx, {
666
+ actor: rActor.Ok(),
667
+ chatId: req.chatId,
668
+ input,
669
+ dispatcher,
670
+ toolsOffered: belt.definitions.map((d) => d.function.name),
671
+ }), async (commit) => {
672
+ if (firstTurnAppClaimed === false)
673
+ return Result.Ok({
674
+ ok: false,
675
+ reason: "no-app-yet",
676
+ message: "Call create_vibe first; there is no app to edit until it has been created.",
696
677
  });
697
- if (currentActor.isErr())
698
- return Result.Err(currentActor.Err());
699
- const scoped = await resolveChatApp(vctx, currentActor.Ok(), req.chatId);
700
- if (scoped.isErr())
701
- return Result.Err(scoped.Err());
702
- const commitId = vctx.sthis.nextId(12).str;
703
- const lock = acquireTurnBuildLock({
704
- vctx,
678
+ const currentActor = await resolveAgentActor(vctx, {
679
+ userId: rActor.Ok().userId,
680
+ requestedHandle: rActor.Ok().ownerHandle,
681
+ scope: rActor.Ok().scope,
682
+ });
683
+ if (currentActor.isErr())
684
+ return Result.Err(currentActor.Err());
685
+ const scoped = await resolveChatApp(vctx, currentActor.Ok(), req.chatId);
686
+ if (scoped.isErr())
687
+ return Result.Err(scoped.Err());
688
+ const commitId = vctx.sthis.nextId(12).str;
689
+ const lock = acquireTurnBuildLock({
690
+ vctx,
691
+ chatId: req.chatId,
692
+ promptId: commitId,
693
+ movesFilesystem: true,
694
+ wakesOnTerminal: false,
695
+ });
696
+ if (lock.acquired === false)
697
+ return Result.Err("A build is running; the staged commit could not acquire the write lane.");
698
+ const committed = { promptBlockEndEmitted: false };
699
+ const saved = await exception2Result(() => handleFSPrompt({
700
+ scope,
701
+ vctx,
702
+ ctx,
703
+ promptId: commitId,
704
+ blockSeq: 0,
705
+ terminal: committed,
706
+ beginDirect: true,
707
+ resChat: { ...resChat, mode: "fs-update" },
708
+ req: {
709
+ type: "vibes.diy.req-prompt-chat-section",
710
+ mode: "fs-update",
711
+ auth: req.auth,
712
+ _auth: req._auth,
705
713
  chatId: req.chatId,
706
- promptId: commitId,
707
- movesFilesystem: true,
708
- wakesOnTerminal: false,
709
- });
710
- if (lock.acquired === false)
711
- return Result.Err("A build is running; the staged commit could not acquire the write lane.");
712
- const committed = { promptBlockEndEmitted: false };
713
- const saved = await exception2Result(() => handleFSPrompt({
714
- scope,
715
- vctx,
714
+ outerTid: req.outerTid,
715
+ agentFileCommit: commit,
716
+ fsUpdate: {
717
+ update: commit.changes.map((file) => ({
718
+ type: "code-block",
719
+ filename: file.path,
720
+ content: file.contents,
721
+ lang: langForFilename(file.path),
722
+ })),
723
+ remove: [],
724
+ },
725
+ },
726
+ })).finally(() => {
727
+ committed.releasePersistGate?.();
728
+ releaseTurnBuildLock(vctx, req.chatId, commitId);
729
+ });
730
+ if (saved.isErr()) {
731
+ const last = await maxPersistedBlockSeq(vctx.sql, { chatId: req.chatId, promptId: commitId });
732
+ if (last.isErr())
733
+ return Result.Err(last.Err());
734
+ const seq = (last.Ok() ?? -1) + 1;
735
+ await appendBlockEvent({
716
736
  ctx,
737
+ vctx,
738
+ req,
717
739
  promptId: commitId,
718
- blockSeq: 0,
719
- terminal: committed,
720
- beginDirect: true,
721
- resChat: { ...resChat, mode: "fs-update" },
722
- req: {
723
- type: "vibes.diy.req-prompt-chat-section",
724
- mode: "fs-update",
725
- auth: orig.auth,
726
- _auth: req._auth,
740
+ blockSeq: seq,
741
+ evt: {
742
+ type: "prompt.error",
743
+ streamId: commitId,
727
744
  chatId: req.chatId,
728
- outerTid: req.outerTid,
729
- agentFileCommit: commit,
730
- fsUpdate: {
731
- update: commit.changes.map((file) => ({
732
- type: "code-block",
733
- filename: file.path,
734
- content: file.contents,
735
- lang: langForFilename(file.path),
736
- })),
737
- remove: [],
738
- },
745
+ seq,
746
+ timestamp: new Date(),
747
+ error: saved.Err().message,
739
748
  },
740
- })).finally(() => {
741
- committed.releasePersistGate?.();
742
- releaseTurnBuildLock(vctx, req.chatId, commitId);
743
- });
744
- if (saved.isErr()) {
745
- const last = await maxPersistedBlockSeq(vctx.sql, { chatId: req.chatId, promptId: commitId });
746
- if (last.isErr())
747
- return Result.Err(last.Err());
748
- const seq = (last.Ok() ?? -1) + 1;
749
- await appendBlockEvent({
750
- ctx,
751
- vctx,
752
- req,
753
- promptId: commitId,
754
- blockSeq: seq,
755
- evt: {
756
- type: "prompt.error",
757
- streamId: commitId,
758
- chatId: req.chatId,
759
- seq,
760
- timestamp: new Date(),
761
- error: saved.Err().message,
762
- },
763
- });
764
- return Result.Err(saved.Err());
765
- }
766
- if (committed.fsRef === undefined)
767
- return Result.Err("The commit did not persist a version.");
768
- const committedPaths = commit.changes.map((file) => file.path);
769
- return Result.Ok({
770
- ok: true,
771
- saved: true,
772
- fsRef: committed.fsRef,
773
- paths: committedPaths,
774
- entryTouched: classifyTurnReach(committedPaths).entryTouched,
775
749
  });
750
+ return Result.Err(saved.Err());
751
+ }
752
+ if (committed.fsRef === undefined)
753
+ return Result.Err("The commit did not persist a version.");
754
+ const committedPaths = commit.changes.map((file) => file.path);
755
+ return Result.Ok({
756
+ ok: true,
757
+ saved: true,
758
+ fsRef: committed.fsRef,
759
+ paths: committedPaths,
760
+ entryTouched: classifyTurnReach(committedPaths).entryTouched,
776
761
  });
777
- }
762
+ });
778
763
  const res = await handlerLlmRequest({
779
764
  ctx,
780
765
  blockSeq,
@@ -784,13 +769,14 @@ export const promptChatSection = {
784
769
  resChat,
785
770
  promptId,
786
771
  preAssembled: { ...agentPayload, isInitialTurn: false },
772
+ modelUsage: "agent",
787
773
  serverTools: belt.definitions,
788
774
  });
789
775
  const evidence = agentEvidence ??
790
776
  observeEvidenceLine(createAgentEvidenceWriter({
791
777
  chatId: req.chatId,
792
778
  promptId,
793
- ...(liveSession === undefined ? {} : { sessionId: liveSession.promptId }),
779
+ sessionId: liveSession.promptId,
794
780
  append: (evt, blockSeq) => appendBlockEvent({ ctx, vctx, req, promptId, blockSeq, evt }),
795
781
  }), turnLatency);
796
782
  let providerStream;
@@ -810,33 +796,29 @@ export const promptChatSection = {
810
796
  stream: rSse.Ok(),
811
797
  abort: res.abort,
812
798
  onToolEvidence: ({ kind, call, text, round, epoch }) => evidence({ kind, callId: call.id, name: call.name, text, round, epoch }),
813
- ...(liveSession === undefined
814
- ? {}
815
- : {
816
- session: {
817
- checkpoint: async (messages) => {
818
- const saved = await liveSession.session.checkpoint(messages);
819
- if (saved.isErr())
820
- return saved;
821
- const extended = await extendOpenTurnDeadline(vctx.sql, {
822
- chatId: req.chatId,
823
- promptId,
824
- deadlineAtMs: Date.now() + agentTotalBudgetMs(vctx) + OPEN_TURN_AWAIT_BUILD_EXTENSION_MS,
825
- });
826
- if (extended.isErr())
827
- return Result.Err(extended.Err());
828
- return Result.Ok();
829
- },
830
- next: () => nextAgentSessionMessages(liveSession.session, evidence),
831
- head: () => liveSession.session.head(),
832
- dispatchBudgetMs: agentTotalBudgetMs(vctx),
833
- },
834
- }),
799
+ session: {
800
+ checkpoint: async (messages) => {
801
+ const saved = await liveSession.session.checkpoint(messages);
802
+ if (saved.isErr())
803
+ return saved;
804
+ const extended = await extendOpenTurnDeadline(vctx.sql, {
805
+ chatId: req.chatId,
806
+ promptId,
807
+ deadlineAtMs: Date.now() + agentTotalBudgetMs(vctx) + OPEN_TURN_AWAIT_BUILD_EXTENSION_MS,
808
+ });
809
+ if (extended.isErr())
810
+ return Result.Err(extended.Err());
811
+ return Result.Ok();
812
+ },
813
+ next: () => nextAgentSessionMessages(liveSession.session, evidence),
814
+ head: () => liveSession.session.head(),
815
+ dispatchBudgetMs: agentTotalBudgetMs(vctx),
816
+ },
835
817
  dispatch: async ({ request, budget }) => {
836
818
  const messages = agentFirstTurnMint && firstTurnAppClaimed
837
819
  ? claimAgentAppContext(request.messages, { ownerHandle: resChat.ownerHandle, appSlug: liveAppSlug })
838
820
  : request.messages;
839
- if (agentSession !== undefined) {
821
+ {
840
822
  const latest = await loadWorkVfs(vctx, {
841
823
  chatId: req.chatId,
842
824
  ownerHandle: resChat.ownerHandle,
@@ -933,6 +915,7 @@ export const promptChatSection = {
933
915
  abort: res.abort,
934
916
  terminal,
935
917
  researchRequested: res.urlResearchJob !== undefined,
918
+ frontendDraft: preAssembled?.frontendDraft === true && req.mode === "codegen",
936
919
  codegenTheme: preAssembled?.codegenTheme,
937
920
  codegenVariety: preAssembled?.codegenVariety,
938
921
  editBaseFsId: preAssembled?.editBaseFsId,
@@ -966,7 +949,6 @@ export const promptChatSection = {
966
949
  const promptId = agentSession?.promptId ?? vctx.sthis.nextId(96 / 8).str;
967
950
  const movesFilesystem = isSourceChangingMode(req.mode) && agentAssembled === undefined;
968
951
  const wakesOnTerminal = decideAgentWake({
969
- agentLane,
970
952
  agentDispatched: agentDispatchedBuild,
971
953
  movedFilesystem: movesFilesystem,
972
954
  budget: agentWakeBudget,
@@ -1181,10 +1163,9 @@ export const promptChatSection = {
1181
1163
  };
1182
1164
  const { consumed } = settleTurnTerminal(vctx.connections, req.chatId, promptId, landingOutcome);
1183
1165
  const wake = decideAgentWake({
1184
- agentLane,
1185
1166
  agentDispatched: agentDispatchedBuild,
1186
1167
  movedFilesystem: movesFilesystem,
1187
- budget: agentSessionEnabled(vctx) ? 1 : agentWakeBudget,
1168
+ budget: 1,
1188
1169
  });
1189
1170
  if (consumed === true) {
1190
1171
  vctx.logger
@@ -1197,11 +1178,11 @@ export const promptChatSection = {
1197
1178
  fireAgentWakeTurn({
1198
1179
  vctx,
1199
1180
  host: ctx,
1200
- auth: orig.auth,
1181
+ auth: req.auth,
1201
1182
  outerTid: req.outerTid,
1202
1183
  chatId: req.chatId,
1203
1184
  budget: wake.budget,
1204
- note: renderAgentWakeNote(landingOutcome, agentSessionEnabled(vctx)),
1185
+ note: renderAgentWakeNote(landingOutcome),
1205
1186
  handle: (wakeCtx) => promptChatSection.handle(promptDispatchContext(ctx, wakeCtx.validated)),
1206
1187
  });
1207
1188
  }
@@ -1212,7 +1193,6 @@ export const promptChatSection = {
1212
1193
  chatId: req.chatId,
1213
1194
  promptId,
1214
1195
  skip: wake.skip,
1215
- agentLane,
1216
1196
  agentDispatched: agentDispatchedBuild,
1217
1197
  movedFilesystem: movesFilesystem,
1218
1198
  budget: agentWakeBudget,
@@ -1293,4 +1273,14 @@ export const promptChatSection = {
1293
1273
  return Result.Ok(EventoResult.Continue);
1294
1274
  }),
1295
1275
  };
1276
+ export const promptChatSection = {
1277
+ ...accountPromptChatSection,
1278
+ handle: checkBuildAuth(async (ctx) => {
1279
+ if (ctx.validated.payload._auth.type !== "VerifiedGuestBuildAuth")
1280
+ return accountPromptChatSection.handle(ctx);
1281
+ const build = handleGuestPrompt(ctx);
1282
+ ctx.ctx.getOrThrow("vibesApiCtx").waitUntil?.(build);
1283
+ return build;
1284
+ }),
1285
+ };
1296
1286
  //# sourceMappingURL=prompt-chat-section.js.map