@qvac/core 0.10.4 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/dist-lib/lib/assistant/history.d.ts +2 -1
  3. package/dist-lib/lib/assistant/history.js +14 -3
  4. package/dist-lib/lib/assistant/message.d.ts +3 -0
  5. package/dist-lib/lib/assistant/message.js +8 -0
  6. package/dist-lib/lib/assistant/pdf-budget.d.ts +3 -0
  7. package/dist-lib/lib/assistant/pdf-budget.js +13 -0
  8. package/dist-lib/lib/assistant-tree.d.ts +1 -0
  9. package/dist-lib/lib/assistant-tree.js +9 -2
  10. package/dist-lib/lib/assistant.d.ts +4 -1
  11. package/dist-lib/lib/assistant.js +98 -33
  12. package/dist-lib/lib/core/departures.js +6 -0
  13. package/dist-lib/lib/core/document-attachment.d.ts +7 -0
  14. package/dist-lib/lib/core/document-attachment.js +6 -0
  15. package/dist-lib/lib/core/identity.d.ts +2 -0
  16. package/dist-lib/lib/core/identity.js +19 -0
  17. package/dist-lib/lib/core/pdf/rasterize.d.ts +0 -1
  18. package/dist-lib/lib/core/pdf/rasterize.js +0 -1
  19. package/dist-lib/lib/core.d.ts +1 -0
  20. package/dist-lib/lib/core.js +25 -6
  21. package/dist-lib/lib/credential-pusher.d.ts +1 -0
  22. package/dist-lib/lib/credential-pusher.js +34 -48
  23. package/dist-lib/lib/errors.d.ts +8 -0
  24. package/dist-lib/lib/errors.js +8 -0
  25. package/dist-lib/lib/oauth/flow-core.js +2 -0
  26. package/dist-lib/lib/oauth/loopback.d.ts +1 -0
  27. package/dist-lib/lib/oauth/loopback.js +31 -1
  28. package/dist-lib/lib/oauth/register.js +33 -18
  29. package/dist-lib/lib/oauth/request.d.ts +10 -0
  30. package/dist-lib/lib/oauth/request.js +22 -0
  31. package/dist-lib/lib/oauth/token-exchange-core.js +29 -32
  32. package/dist-lib/lib/oauth/types.d.ts +3 -0
  33. package/dist-lib/lib/oauth.d.ts +2 -1
  34. package/dist-lib/lib/oauth.js +1 -0
  35. package/dist-lib/lib/run-replay.d.ts +8 -2
  36. package/dist-lib/lib/run-replay.js +29 -11
  37. package/package.json +5 -4
package/CHANGELOG.md CHANGED
@@ -13,6 +13,39 @@ release.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.11.0] - 2026-10-23
17
+
18
+ ### Added
19
+
20
+ - `OAuthFlowDeps.onStage` reports `awaiting-callback` and `exchanging-code`, so a
21
+ host can log where a connect flow stopped. (#550)
22
+ - `deliverOAuthCallback(address)` in `@qvac/core/oauth` settles a waiting
23
+ sign-in from a callback address the user pastes, for a browser that cannot
24
+ reach the loopback. (#551)
25
+
26
+ ### Changed
27
+
28
+ - The OAuth loopback done page tells the user to return to QV.AC to finish
29
+ connecting. (#550)
30
+ - The PDF page-image cap scales with the run's context window, between 2 and
31
+ 32 pages, instead of a fixed 10. (#526)
32
+
33
+ ### Fixed
34
+
35
+ - An OAuth connect whose provider stops answering now fails after 30 s instead
36
+ of waiting forever: the code exchange after the browser hands back the code
37
+ with `OAUTH_TOKEN_EXCHANGE_TIMEOUT`, and dynamic client registration, before
38
+ the browser opens, with `OAUTH_REGISTRATION_TIMEOUT`.
39
+ `OAuthFlowDeps.requestTimeoutMs` sets the limit per request. (#555)
40
+ - A PDF cut at the page-image cap tells the model the last page shown. (#525)
41
+ - Each user turn renders the same bytes on every request, so the chat's KV
42
+ cache is reused. (#528)
43
+ - Two devices that take turns to leave the account and pair back can both still
44
+ `meshInvite`. Before, the fourth pairing left a device refused with
45
+ `DEVICE_INVITE_CHAIN_TOO_LONG`. (#513)
46
+ - `joinMesh` no longer hangs when a device pairs back right after it unpaired,
47
+ while the removal its leave left behind is still being delivered. (#513)
48
+
16
49
  ## [0.10.4] - 2026-10-22
17
50
 
18
51
  ### Added
@@ -1892,7 +1925,8 @@ Published under the `release-0.1` dist-tag.
1892
1925
  await assistant.ready()
1893
1926
  ```
1894
1927
 
1895
- [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.10.4...HEAD
1928
+ [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.11.0...HEAD
1929
+ [0.11.0]: https://github.com/tetherto/qvac-core/compare/v0.10.4...v0.11.0
1896
1930
  [0.10.4]: https://github.com/tetherto/qvac-core/compare/v0.10.3...v0.10.4
1897
1931
  [0.10.3]: https://github.com/tetherto/qvac-core/compare/v0.10.2...v0.10.3
1898
1932
  [0.10.2]: https://github.com/tetherto/qvac-core/compare/v0.10.1...v0.10.2
@@ -37,8 +37,9 @@ export declare function senderAttribution(names: ReadonlyMap<string, string>): s
37
37
  export interface HistoryReplay {
38
38
  readonly senderNames?: ReadonlyMap<string, string>;
39
39
  readonly sentRuns?: ReadonlyMap<string, ReadonlyArray<ChatMessage>>;
40
+ readonly askedRuns?: ReadonlyMap<string, string>;
40
41
  }
41
- export declare function historyFromChunks(chunks: ReadonlyArray<AssistantChunk>, stale?: Partial<StaleToolRuns>, { senderNames, sentRuns }?: HistoryReplay): ChatMessage[];
42
+ export declare function historyFromChunks(chunks: ReadonlyArray<AssistantChunk>, stale?: Partial<StaleToolRuns>, { senderNames, sentRuns, askedRuns }?: HistoryReplay): ChatMessage[];
42
43
  export declare function inputAvailableToRun(chunk: AssistantChunk, requestSeq: number): boolean;
43
44
  export declare function normalizeQuestion(text: string): string;
44
45
  export declare const GENERIC_ACKNOWLEDGEMENTS: Set<string>;
@@ -87,7 +87,7 @@ function derivedAttachments(chunks) {
87
87
  }
88
88
  return derived;
89
89
  }
90
- export function historyFromChunks(chunks, stale = {}, { senderNames = new Map(), sentRuns = new Map() } = {}) {
90
+ export function historyFromChunks(chunks, stale = {}, { senderNames = new Map(), sentRuns = new Map(), askedRuns = new Map() } = {}) {
91
91
  const attemptStarts = latestAttemptStarts(chunks);
92
92
  const shared = new Set(senderNames.values()).size > 1;
93
93
  const staleRunIds = stale.runIds ?? new Set();
@@ -113,12 +113,18 @@ export function historyFromChunks(chunks, stale = {}, { senderNames = new Map(),
113
113
  }
114
114
  const byRun = new Map();
115
115
  const kept = new Set();
116
+ let asking = null;
116
117
  const anchor = (runId) => {
117
118
  let turn = byRun.get(runId);
118
119
  if (!turn) {
119
120
  turn = { role: 'assistant', content: '' };
120
121
  byRun.set(runId, turn);
121
- const sent = runId && !staleRunIds.has(runId) ? sentRuns.get(runId) : undefined;
122
+ const live = runId && !staleRunIds.has(runId) ? runId : undefined;
123
+ const asked = live ? askedRuns.get(live) : undefined;
124
+ if (asking && asked !== undefined) {
125
+ asking.sentContent = asked;
126
+ }
127
+ const sent = live ? sentRuns.get(live) : undefined;
122
128
  if (sent) {
123
129
  const replayed = sent.map((message) => ({ ...message }));
124
130
  history.push(...replayed);
@@ -136,10 +142,15 @@ export function historyFromChunks(chunks, stale = {}, { senderNames = new Map(),
136
142
  continue;
137
143
  }
138
144
  const sender = shared ? senderNames.get(chunk.id) : undefined;
139
- const turn = { role: 'user', content: chunk.userMessage.text };
145
+ const turn = {
146
+ role: 'user',
147
+ content: chunk.userMessage.text,
148
+ sentAt: chunk.createdAt
149
+ };
140
150
  if (sender) {
141
151
  turn.sender = sender;
142
152
  }
153
+ asking = turn;
143
154
  const refs = (byMessage.get(chunk.id) ?? [])
144
155
  .flatMap((attachmentChunk) => attachmentChunk.attachment ?? [])
145
156
  .filter((ref) => !ref.deletedAt);
@@ -3,6 +3,8 @@ export interface ChatMessage {
3
3
  role: 'user' | 'assistant' | 'tool';
4
4
  content: string;
5
5
  sender?: string;
6
+ sentAt?: number;
7
+ sentContent?: string;
6
8
  attachments?: {
7
9
  path: string;
8
10
  }[];
@@ -63,4 +65,5 @@ export interface AttachmentMeta {
63
65
  export interface FetchedAttachment extends AttachmentMeta {
64
66
  bytes: Uint8Array;
65
67
  }
68
+ export declare function restoreSentContent(messages: ChatMessage[]): void;
66
69
  export declare function nameSenders(messages: ReadonlyArray<ChatMessage>): ChatMessage[];
@@ -80,6 +80,14 @@ function displayableSender(name) {
80
80
  const flat = name?.replace(/\s+/g, ' ').trim();
81
81
  return flat ? Array.from(flat).slice(0, MAX_SENDER_NAME_CHARS).join('') : undefined;
82
82
  }
83
+ export function restoreSentContent(messages) {
84
+ for (const turn of messages) {
85
+ if (turn.sentContent === undefined)
86
+ continue;
87
+ turn.content = turn.sentContent;
88
+ delete turn.sentContent;
89
+ }
90
+ }
83
91
  export function nameSenders(messages) {
84
92
  return messages.map(({ sender, ...turn }) => {
85
93
  const name = displayableSender(sender);
@@ -0,0 +1,3 @@
1
+ export declare const MIN_PDF_PAGE_IMAGES = 2;
2
+ export declare const MAX_PDF_PAGE_IMAGES = 32;
3
+ export declare function pdfPageBudget(ctxSize: number): number;
@@ -0,0 +1,13 @@
1
+ import { MAX_IMAGE_WIDTH } from '../core/image/normalize.js';
2
+ import { frameTokens } from './video-budget.js';
3
+ const PAGE_TOKENS = frameTokens({
4
+ width: MAX_IMAGE_WIDTH,
5
+ height: Math.ceil(MAX_IMAGE_WIDTH * Math.SQRT2)
6
+ });
7
+ const PDF_SHARE = 0.5;
8
+ export const MIN_PDF_PAGE_IMAGES = 2;
9
+ export const MAX_PDF_PAGE_IMAGES = 32;
10
+ export function pdfPageBudget(ctxSize) {
11
+ const fits = Math.floor((ctxSize * PDF_SHARE) / PAGE_TOKENS);
12
+ return Math.min(MAX_PDF_PAGE_IMAGES, Math.max(MIN_PDF_PAGE_IMAGES, fits));
13
+ }
@@ -12,6 +12,7 @@ export type HarnessFactory = (ctx: HarnessContext) => Harness | Promise<Harness>
12
12
  export type EmbedderFactory = (harness: Harness) => IndexingEmbedder | null | undefined;
13
13
  export type OnHarnessDisposer = (() => void | Promise<void>) & {
14
14
  sync?: () => Promise<void>;
15
+ ready?: () => Promise<void>;
15
16
  };
16
17
  export type OnHarness = (harness: Harness, ctx: {
17
18
  engine: Client;
@@ -126,7 +126,10 @@ export function assistantTree(opts) {
126
126
  unload: (name) => assistant.unloadModel(name)
127
127
  });
128
128
  offModelUsers = core.registerModelUsers((name) => assistant.modelUsers(name));
129
- offSkills = core.registerSkills((agentId, modelName, options) => assistant.skills(agentId, modelName, options));
129
+ offSkills = core.registerSkills(async (agentId, modelName, options) => {
130
+ await offHarness?.ready?.();
131
+ return assistant.skills(agentId, modelName, options);
132
+ });
130
133
  const transcribe = harnessTranscribe(harness);
131
134
  offTranscribe = core.registerTranscribe(async (request) => {
132
135
  await assistant.ensureMediaModelUnpaused('transcription', request.model);
@@ -144,7 +147,11 @@ export function assistantTree(opts) {
144
147
  await assistant.ensureMediaModelUnpaused('tts');
145
148
  yield* speakStream(text);
146
149
  })());
147
- offSkillCatalog = core.registerSkillCatalog(harnessSkillCatalog(assistant, () => offHarness?.sync?.()));
150
+ const skillCatalog = harnessSkillCatalog(assistant, () => offHarness?.sync?.());
151
+ offSkillCatalog = core.registerSkillCatalog(async (agentId, modelName, options) => {
152
+ await offHarness?.ready?.();
153
+ return skillCatalog(agentId, modelName, options);
154
+ });
148
155
  offSkillManagement = core.registerSkillManagement(harnessSkillManagement(harness));
149
156
  offTools = core.registerTools(harnessTools(assistant));
150
157
  const emb = embedder?.(harness);
@@ -13,7 +13,7 @@ import type { Skill } from './assistant/skill-encode.ts';
13
13
  import { type CompactOptions, type CompactResult } from './assistant/history.ts';
14
14
  export { harnessClearKvCache, harnessDeleteModel, harnessListModels, harnessPreviewModelSource, harnessSkillCatalog, harnessSkillManagement, harnessDetectLanguage, harnessSpeak, harnessSpeakStream, harnessTools, harnessTranscribe, type DeleteModelSummary, type Harness, type HarnessInfo, type ListModelsOptions, type ModelInfo, type ModelType, type ToolCatalogEntry } from './assistant/harness.ts';
15
15
  export { type Skill } from './assistant/skill-encode.ts';
16
- export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT, nameSenders } from './assistant/message.ts';
16
+ export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT, nameSenders, restoreSentContent } from './assistant/message.ts';
17
17
  export { couldNameSenders, historyFromChunks, listHistoryChunks, senderAttribution, senderNamesFrom, staleToolRunIds, type CompactOptions, type CompactResult, type CompactionTrigger, type StaleToolRuns } from './assistant/history.ts';
18
18
  export declare const CAPTURE_INFERENCE_CALLS_KEY = "inspector.captureInferenceCalls";
19
19
  export declare const CAPTURE_ON = "on";
@@ -224,6 +224,9 @@ export declare class QvacAssistant extends ReadyResource {
224
224
  private _hydrateTurnImages;
225
225
  private _hydrateImage;
226
226
  private _hydratePdfPages;
227
+ private _pdfPageBudget;
228
+ private _customModel;
229
+ private _hydrateTurnPdfs;
227
230
  private _tryHydratePdf;
228
231
  private _hydratePdf;
229
232
  private _renderPdf;
@@ -22,10 +22,10 @@ import { buildTitlePrompt, deriveChatTitle, isDefaultChatTitle, parseTitleRespon
22
22
  import { matchApprovalRule } from './core/approval-rules.js';
23
23
  import { isAudioAttachment } from './core/audio-attachment.js';
24
24
  import { attachTurnDocumentIds, formatRagContext, chooseRagNotice, RAG_KNOWLEDGE_OFF_NOTICE, RAG_TRUNCATED_NOTICE, RAG_UNAVAILABLE_NOTICE, createRagSourceTagFilter, citedByPhraseOverlap, formatFullDocumentContext, isFullTextHit, isTruncatedFullTextHit, sourcesFromHits, WEB_TOOLS, webSourcesFromToolResult, withoutDataChannel } from './core/files/index.js';
25
- import { annotateDocumentAttachments, documentUnreadNotice, documentUnreadReason } from './core/document-attachment.js';
25
+ import { annotateDocumentAttachments, documentUnreadNotice, documentUnreadReason, pdfPagesCutNotice, pdfPagesSkippedNotice } from './core/document-attachment.js';
26
26
  import { imageCacheKey, imageCacheName, sweepImageCache } from './core/image/cache-sweep.js';
27
27
  import { IMAGE_MIMES, normalizeImageForModel } from './core/image/normalize.js';
28
- import { MAX_PDF_PAGE_IMAGES, createPdfRasterizer } from './core/pdf/rasterize.js';
28
+ import { createPdfRasterizer } from './core/pdf/rasterize.js';
29
29
  import { recordBackends, summarizeRuns } from './diagnostics.js';
30
30
  import { resolveFsGrants } from './fs-drive-bridge.js';
31
31
  import { InferenceCallStore } from './inference-calls.js';
@@ -44,17 +44,19 @@ import { isLifecycleTeardown, knownAbortOutcome, RUN_ABORT_REASONS, RUN_FAILURE_
44
44
  import { unref } from './unref.js';
45
45
  import { encodeAgentSkillReadiness } from './skill-readiness.js';
46
46
  import { harnessClearKvCache, harnessDeathReason, harnessDeleteModel, harnessDied, harnessListModels, harnessPreviewModelSource, harnessSkillCatalog, harnessSkillManagement, harnessDetectLanguage, harnessSpeak, harnessSpeakStream, harnessTools, harnessTranscribe, heldLoadModel, droppedHeldLoadModel, imageDownloadProgress, isHarnessEvent, modelCatalogChanged, toolReportEntry } from './assistant/harness.js';
47
- import { annotateUnreadableImages, audioTranscriptBlock, backfillDocumentOnlyTurn, backfillImageOnlyTurns, silentAudioNotice, unheardAudioNotice, nameSenders, hiddenVideoNotice, lentVideoNotice, unreadVideoNotice, unsyncedVideoNotice, VIDEO_NO_AUDIO, VIDEO_SILENT, videoAnnotation, videoTranscriptBlock } from './assistant/message.js';
47
+ import { annotateUnreadableImages, audioTranscriptBlock, backfillDocumentOnlyTurn, backfillImageOnlyTurns, silentAudioNotice, unheardAudioNotice, nameSenders, restoreSentContent, hiddenVideoNotice, lentVideoNotice, unreadVideoNotice, unsyncedVideoNotice, VIDEO_NO_AUDIO, VIDEO_SILENT, videoAnnotation, videoTranscriptBlock } from './assistant/message.js';
48
48
  import { frameTimes, probeVideo, sampleFrames } from './core/video/frames.js';
49
49
  import { packVideoDigest, parseVideoDigestHeader, unpackVideoDigest, VIDEO_DIGEST_MIME, videoDigestFileName } from './core/video/digest.js';
50
50
  import { VIDEO_FRAME_EDGE, videoFrameCount } from './assistant/video-budget.js';
51
51
  import { drainBody, raceInactivity } from './assistant/fetch-body.js';
52
+ import { pdfPageBudget } from './assistant/pdf-budget.js';
53
+ import { effectiveCtxSize } from './api/effective-ctx-size.js';
52
54
  import { GENERIC_ACKNOWLEDGEMENTS, HISTORY_TYPES, SKILL_TOOL, TERMINAL_STATES, couldNameSenders, historyFromChunks, inputAvailableToRun, listHistoryChunks, senderAttribution, senderNamesFrom, staleToolRunIds } from './assistant/history.js';
53
55
  import { errorMessage, isRecord } from './guards.js';
54
56
  import { CoreError, isCoreError } from './errors.js';
55
57
  export { harnessClearKvCache, harnessDeleteModel, harnessListModels, harnessPreviewModelSource, harnessSkillCatalog, harnessSkillManagement, harnessDetectLanguage, harnessSpeak, harnessSpeakStream, harnessTools, harnessTranscribe } from './assistant/harness.js';
56
58
  export {} from './assistant/skill-encode.js';
57
- export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT, nameSenders } from './assistant/message.js';
59
+ export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT, nameSenders, restoreSentContent } from './assistant/message.js';
58
60
  export { couldNameSenders, historyFromChunks, listHistoryChunks, senderAttribution, senderNamesFrom, staleToolRunIds } from './assistant/history.js';
59
61
  const NO_SENDERS = new Map();
60
62
  const DEFAULT_PROFILE = 'mid';
@@ -110,6 +112,20 @@ const RunOccupancySchema = z.object({
110
112
  export const CAPTURE_INFERENCE_CALLS_KEY = 'inspector.captureInferenceCalls';
111
113
  export const CAPTURE_ON = 'on';
112
114
  export const CAPTURE_OFF = 'off';
115
+ function pdfCut(doc, from) {
116
+ const pageCount = doc.pageCount();
117
+ for (let page = from; page < pageCount; page++) {
118
+ try {
119
+ const flags = doc.pageFlags(page);
120
+ if (flags.hasImage || !flags.hasText) {
121
+ return { lastPage: page, pageCount };
122
+ }
123
+ }
124
+ catch {
125
+ }
126
+ }
127
+ return undefined;
128
+ }
113
129
  function attachPages(turn, files) {
114
130
  if (!files.length)
115
131
  return;
@@ -1272,18 +1288,21 @@ export class QvacAssistant extends ReadyResource {
1272
1288
  }
1273
1289
  async _sentRuns(chatId, holder) {
1274
1290
  try {
1275
- return await this._runReplay.load({ holder, chatId });
1291
+ return {
1292
+ sentRuns: await this._runReplay.load({ holder, chatId }),
1293
+ askedRuns: await this._runReplay.loadAsked({ holder, chatId })
1294
+ };
1276
1295
  }
1277
1296
  catch (err) {
1278
1297
  this._log?.warn('assistant', 'run replay unreadable', { chatId, err });
1279
1298
  await this._deleteChatKvCache(chatId, 'run replay unreadable', holder);
1280
- return new Map();
1299
+ return { sentRuns: new Map(), askedRuns: new Map() };
1281
1300
  }
1282
1301
  }
1283
- async _recordSentRun(chatId, { runId, turns, holder }) {
1302
+ async _recordSentRun(chatId, { runId, turns, asked, holder }) {
1284
1303
  if (turns) {
1285
1304
  try {
1286
- await this._runReplay.save({ holder, chatId }, runId, turns);
1305
+ await this._runReplay.save({ holder, chatId }, runId, { messages: turns, asked });
1287
1306
  return;
1288
1307
  }
1289
1308
  catch (err) {
@@ -1730,8 +1749,12 @@ export class QvacAssistant extends ReadyResource {
1730
1749
  await this._reconcileAttribution(chatId, senders, holder);
1731
1750
  }
1732
1751
  const stale = staleToolRunIds(history, priorAsks ?? [], runId);
1733
- const sentRuns = await this._sentRuns(chatId, holder);
1734
- const messages = historyFromChunks(history, stale, { senderNames: senders, sentRuns });
1752
+ const { sentRuns, askedRuns } = await this._sentRuns(chatId, holder);
1753
+ const messages = historyFromChunks(history, stale, {
1754
+ senderNames: senders,
1755
+ sentRuns,
1756
+ askedRuns
1757
+ });
1735
1758
  const typedText = currentRepair
1736
1759
  ? undefined
1737
1760
  : history.findLast((chunk) => chunk.userMessage)?.userMessage?.text;
@@ -1753,7 +1776,7 @@ export class QvacAssistant extends ReadyResource {
1753
1776
  const seesImages = sendsFiles && carriesMedia && (await this._seesImages(model));
1754
1777
  let unreadableImages = new Map();
1755
1778
  const sampled = [];
1756
- let renderedPdfIds = new Set();
1779
+ let pdfPages = { rendered: new Set(), cuts: [] };
1757
1780
  if (!seesImages) {
1758
1781
  const dropped = messages.reduce((count, turn) => count + (turn.images?.length ?? 0), 0);
1759
1782
  if (dropped && (this._harness.supportsImages ?? this._info.supportsImages)) {
@@ -1857,6 +1880,7 @@ export class QvacAssistant extends ReadyResource {
1857
1880
  let runVerdict = 'completed';
1858
1881
  let sentRun = null;
1859
1882
  let inputLength = 0;
1883
+ let asked;
1860
1884
  const writeText = async (type, raw) => {
1861
1885
  const text = type === 'content' ? sourceTagFilter.push(raw) : raw;
1862
1886
  if (!text) {
@@ -1964,10 +1988,17 @@ export class QvacAssistant extends ReadyResource {
1964
1988
  }
1965
1989
  backfillImageOnlyTurns(messages);
1966
1990
  if (seesImages) {
1967
- renderedPdfIds = await this._hydratePdfPages(messages, controller.signal, runId);
1991
+ pdfPages = await this._hydratePdfPages(messages, {
1992
+ signal: controller.signal,
1993
+ runId,
1994
+ window: { ctxSize: configuredAgent.ctxSize, modelName: model }
1995
+ });
1968
1996
  }
1969
1997
  annotateDocumentAttachments(messages);
1970
- const unreadIds = attachTurnIds.filter((id) => !renderedPdfIds.has(id));
1998
+ for (const { turn, notice } of pdfPages.cuts) {
1999
+ turn.content = `${turn.content}\n${notice}`;
2000
+ }
2001
+ const unreadIds = attachTurnIds.filter((id) => !pdfPages.rendered.has(id));
1971
2002
  if (!diagramRepair && unreadIds.length > 0 && !injected.documentsInjected) {
1972
2003
  const reason = documentUnreadReason({
1973
2004
  knowledgeOn: toolsetEnabled('knowledge', runAgent.disabledToolsets),
@@ -2006,6 +2037,8 @@ export class QvacAssistant extends ReadyResource {
2006
2037
  cacheKey,
2007
2038
  turns: messages.length
2008
2039
  });
2040
+ restoreSentContent(messages);
2041
+ asked = messages.findLast((turn) => turn.role === 'user')?.content;
2009
2042
  const input = nameSenders(messages);
2010
2043
  inputLength = input.length;
2011
2044
  const inspecting = await this._capturingInferenceCalls();
@@ -2156,6 +2189,7 @@ export class QvacAssistant extends ReadyResource {
2156
2189
  await this._recordSentRun(chatId, {
2157
2190
  runId,
2158
2191
  turns: sentRun.turns(inputLength),
2192
+ asked,
2159
2193
  holder
2160
2194
  });
2161
2195
  sentRun = null;
@@ -2803,36 +2837,66 @@ export class QvacAssistant extends ReadyResource {
2803
2837
  });
2804
2838
  return file;
2805
2839
  }
2806
- async _hydratePdfPages(messages, signal, runId) {
2840
+ async _hydratePdfPages(messages, { signal, runId, window }) {
2807
2841
  const rendered = new Set();
2842
+ const cuts = [];
2808
2843
  const turns = messages.filter((turn) => turn.pdfs?.length);
2809
2844
  if (!turns.length) {
2810
- return rendered;
2845
+ return { rendered, cuts };
2811
2846
  }
2812
2847
  const dir = this._imageCacheDir;
2813
2848
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
2814
2849
  const pinned = this._runImageCacheNames.get(runId) ?? new Set();
2815
2850
  this._runImageCacheNames.set(runId, pinned);
2816
2851
  const latestUser = messages.findLast((turn) => turn.role === 'user');
2852
+ const maxPages = await this._pdfPageBudget(window);
2817
2853
  for (const turn of turns) {
2818
- let budget = MAX_PDF_PAGE_IMAGES;
2819
- for (const pdf of turn.pdfs ?? []) {
2820
- if (budget <= 0)
2821
- break;
2822
- const pages = await this._tryHydratePdf(dir, turn, {
2823
- pdf,
2824
- pinned,
2825
- maxPages: budget,
2826
- signal
2827
- });
2828
- budget -= pages.tried;
2829
- if (turn === latestUser && pages.names.length) {
2830
- rendered.add(pdf.id);
2854
+ const { shown, notices } = await this._hydrateTurnPdfs(turn, {
2855
+ dir,
2856
+ pinned,
2857
+ signal,
2858
+ maxPages
2859
+ });
2860
+ if (turn === latestUser) {
2861
+ for (const id of shown) {
2862
+ rendered.add(id);
2831
2863
  }
2832
2864
  }
2833
- delete turn.pdfs;
2865
+ cuts.push(...notices.map((notice) => ({ turn, notice })));
2866
+ }
2867
+ return { rendered, cuts };
2868
+ }
2869
+ async _pdfPageBudget({ ctxSize, modelName }) {
2870
+ const custom = await this._customModel(modelName);
2871
+ const window = effectiveCtxSize({ ctxSize, modelName }, { appCtxSize: 0, platform: this._platform, custom });
2872
+ return pdfPageBudget(window);
2873
+ }
2874
+ async _customModel(name) {
2875
+ for await (const list of this._engine.customModelsWatch({})) {
2876
+ return list.models?.find((row) => row.name === name) ?? null;
2877
+ }
2878
+ return null;
2879
+ }
2880
+ async _hydrateTurnPdfs(turn, { dir, pinned, signal, maxPages }) {
2881
+ const shown = [];
2882
+ const notices = [];
2883
+ let budget = maxPages;
2884
+ for (const pdf of turn.pdfs ?? []) {
2885
+ if (budget <= 0) {
2886
+ notices.push(pdfPagesSkippedNotice(pdf.fileName));
2887
+ continue;
2888
+ }
2889
+ const pages = await this._tryHydratePdf(dir, turn, { pdf, pinned, maxPages: budget, signal });
2890
+ budget -= pages.tried;
2891
+ if (pages.names.length) {
2892
+ shown.push(pdf.id);
2893
+ }
2894
+ if (pages.cut) {
2895
+ notices.push(pdfPagesCutNotice({ fileName: pdf.fileName, ...pages.cut }));
2896
+ }
2834
2897
  }
2835
- return rendered;
2898
+ delete turn.pdfs;
2899
+ return { shown, notices };
2836
2900
  }
2837
2901
  async _tryHydratePdf(dir, turn, opts) {
2838
2902
  try {
@@ -2882,8 +2946,9 @@ export class QvacAssistant extends ReadyResource {
2882
2946
  try {
2883
2947
  const names = [];
2884
2948
  let tried = 0;
2885
- const count = doc.pageCount();
2886
- for (let page = 0; page < count && tried < maxPages; page++) {
2949
+ let page = 0;
2950
+ const pageCount = doc.pageCount();
2951
+ for (; page < pageCount && tried < maxPages; page++) {
2887
2952
  if (signal.aborted)
2888
2953
  throw new Error('hydration aborted');
2889
2954
  const outcome = await this._renderPdfPage(doc, { dir, pdf, page, pinned, signal });
@@ -2894,7 +2959,7 @@ export class QvacAssistant extends ReadyResource {
2894
2959
  names.push(outcome.name);
2895
2960
  }
2896
2961
  }
2897
- return { names, tried };
2962
+ return { names, tried, cut: pdfCut(doc, page) };
2898
2963
  }
2899
2964
  finally {
2900
2965
  doc.close();
@@ -163,6 +163,9 @@ async function admitted(mesh) {
163
163
  return true;
164
164
  if (await mesh.ownWriterRefused())
165
165
  return false;
166
+ if (mesh.closing) {
167
+ return false;
168
+ }
166
169
  return new Promise((resolve) => {
167
170
  const settle = (ok) => {
168
171
  mesh.autobee.off('writable', onWritable);
@@ -188,6 +191,9 @@ function waitForDelivery(mesh) {
188
191
  if (delivered()) {
189
192
  return Promise.resolve(true);
190
193
  }
194
+ if (mesh.closing) {
195
+ return Promise.resolve(false);
196
+ }
191
197
  return new Promise((resolve) => {
192
198
  const settle = (ok) => {
193
199
  local.off('upload', onUpload);
@@ -23,6 +23,13 @@ export interface DocumentReadState {
23
23
  }
24
24
  export declare function documentUnreadReason({ knowledgeOn, failedFiles, attachedCount }: DocumentReadState): DocumentUnreadReason;
25
25
  export declare function documentUnreadNotice(reason: DocumentUnreadReason, plural: boolean): string;
26
+ export interface PdfPagesCutState {
27
+ readonly fileName: string;
28
+ readonly lastPage: number;
29
+ readonly pageCount: number;
30
+ }
31
+ export declare function pdfPagesCutNotice({ fileName, lastPage, pageCount }: PdfPagesCutState): string;
32
+ export declare function pdfPagesSkippedNotice(fileName: string): string;
26
33
  export interface AnnotatedMessage {
27
34
  content: string;
28
35
  documents?: DocumentAttachment[];
@@ -33,6 +33,12 @@ export function documentUnreadNotice(reason, plural) {
33
33
  }[reason];
34
34
  return `[The attached document${plural ? 's' : ''} could not be read for this reply: ${why}.]`;
35
35
  }
36
+ export function pdfPagesCutNotice({ fileName, lastPage, pageCount }) {
37
+ return `[Only pages 1–${lastPage} of "${fileName}" (${pageCount} pages) were shown to you as images; pages ${lastPage + 1}–${pageCount} were not, and no tool can show them. If asked about a later page you have no excerpt for, tell the user only the first ${lastPage} pages could be read. Do not guess its content.]`;
38
+ }
39
+ export function pdfPagesSkippedNotice(fileName) {
40
+ return `[No page of "${fileName}" was shown to you as an image: the files before it in this message used up the page images, and no tool can show them. If asked about it and you have no excerpt, tell the user it could not be read. Do not guess its content.]`;
41
+ }
36
42
  export function annotateDocumentAttachments(messages) {
37
43
  for (const turn of messages.filter((message) => message.documents?.length)) {
38
44
  const block = (turn.documents ?? []).map(documentAttachmentLine).join('\n');
@@ -18,6 +18,8 @@ export declare function generateMnemonic(): Promise<string>;
18
18
  export declare function openIdentity(mnemonic: string): Promise<IdentityKey>;
19
19
  export declare function mintIdentity(mnemonic: string, devicePublicKey: Buffer): Promise<MintedIdentity>;
20
20
  export declare function attestDeviceProof(devicePublicKey: Buffer, parent: KeyPair, parentProof: Buffer): Promise<Buffer>;
21
+ export declare function pairingAnchorSeed(accountSeed: Buffer, memberId: Buffer): Buffer;
22
+ export declare function chainTo(proof: Buffer, publicKey: Buffer): Buffer | null;
21
23
  export declare function delegationFits(proof: Buffer, delegate: KeyPair): Promise<boolean>;
22
24
  export declare function verifyDeviceProof(proof: Buffer, expected: ExpectedDeviceProof): Promise<boolean>;
23
25
  export declare function claimAttestation(meshPublicKey: Buffer, deviceId: Buffer, writerKey: Buffer): Buffer;
@@ -1,8 +1,10 @@
1
+ import b4a from 'b4a';
1
2
  import c from 'compact-encoding';
2
3
  import crypto from 'hypercore-crypto';
3
4
  import { ProofEncoding } from 'keet-identity-key/lib/encoding.js';
4
5
  export const MAX_PROOF_BYTES = 1024;
5
6
  const [CLAIM_NAMESPACE] = crypto.namespace('@qvac/core/member-claim', 1);
7
+ const [ANCHOR_NAMESPACE] = crypto.namespace('@qvac/core/pairing-anchor', 1);
6
8
  let loaded = null;
7
9
  async function identityKey() {
8
10
  if (loaded === null) {
@@ -25,6 +27,23 @@ export async function attestDeviceProof(devicePublicKey, parent, parentProof) {
25
27
  throw new Error('attestDeviceProof needs the parent proof');
26
28
  return (await identityKey()).attestDevice(devicePublicKey, parent, parentProof);
27
29
  }
30
+ export function pairingAnchorSeed(accountSeed, memberId) {
31
+ return crypto.hash([ANCHOR_NAMESPACE, accountSeed, memberId]);
32
+ }
33
+ export function chainTo(proof, publicKey) {
34
+ let decoded;
35
+ try {
36
+ decoded = c.decode(ProofEncoding, proof);
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ const at = decoded.chain.findIndex((link) => b4a.equals(link.publicKey, publicKey));
42
+ if (at === -1) {
43
+ return null;
44
+ }
45
+ return c.encode(ProofEncoding, { ...decoded, chain: decoded.chain.slice(0, at + 1) });
46
+ }
28
47
  export async function delegationFits(proof, delegate) {
29
48
  const device = crypto.keyPair();
30
49
  const extended = await attestDeviceProof(device.publicKey, delegate, proof);
@@ -1,6 +1,5 @@
1
1
  import type { LoggerInterface } from '@qvac/logging';
2
2
  export declare const PDF_RENDER_SCALE = 2;
3
- export declare const MAX_PDF_PAGE_IMAGES = 10;
4
3
  interface PageFlags {
5
4
  hasImage: boolean;
6
5
  hasText: boolean;
@@ -1,6 +1,5 @@
1
1
  import { MAX_IMAGE_WIDTH, rasterToModelJpeg } from '../image/normalize.js';
2
2
  export const PDF_RENDER_SCALE = 2;
3
- export const MAX_PDF_PAGE_IMAGES = 10;
4
3
  export function renderScale(pageWidth) {
5
4
  return Math.min(PDF_RENDER_SCALE, MAX_IMAGE_WIDTH / pageWidth);
6
5
  }
@@ -431,6 +431,7 @@ export declare class Core extends ReadyResource {
431
431
  private _assertMeshIsHere;
432
432
  getMeshInvite(opts?: MeshInviteOptions): Promise<MeshInvite | null>;
433
433
  private _delegatePairing;
434
+ private _shortestAnchorProof;
434
435
  previewMeshInvite(invite: string): MeshInvitePreview;
435
436
  private _closeSwarm;
436
437
  pushSkillSecret(request: SecretRequest): Promise<void>;
@@ -40,7 +40,7 @@ import { createInferenceCallsReceiver } from './core/inference-calls-receiver.js
40
40
  import { SkillOverlayHandoff } from './core/skill-overlay-handoff.js';
41
41
  import { createSkillOverlayReceiver } from './core/skill-overlay-receiver.js';
42
42
  import { createSkillSecretReceiver } from './core/skill-secrets.js';
43
- import { attestDeviceProof, attestMemberClaim, claimAttestation, delegationFits, openIdentity } from './core/identity.js';
43
+ import { attestDeviceProof, attestMemberClaim, chainTo, claimAttestation, delegationFits, openIdentity, pairingAnchorSeed } from './core/identity.js';
44
44
  import { openRecoveryCore, publishRecovery, readRecovery, recoveryKeys } from './core/account-recovery.js';
45
45
  import { claimOwnMembership, legacyNameStamp, namedAt, renameFoundedMember } from './core/membership.js';
46
46
  import { runMigrations } from './core/migrations/index.js';
@@ -3622,17 +3622,36 @@ export class Core extends ReadyResource {
3622
3622
  async _delegatePairing(account) {
3623
3623
  const keyPair = this._requireDeviceKeyPair();
3624
3624
  const own = await account.view.get(DEVICES, { id: keyPair.publicKey });
3625
- if (!own?.memberProof) {
3625
+ if (!own?.memberId || !own.memberProof) {
3626
3626
  return null;
3627
3627
  }
3628
- const deviceSeed = crypto.randomBytes(32);
3629
- const delegate = crypto.keyPair(deviceSeed);
3630
- const deviceProof = await attestDeviceProof(delegate.publicKey, keyPair, own.memberProof);
3631
- if (!(await delegationFits(deviceProof, delegate))) {
3628
+ const deviceSeed = pairingAnchorSeed(account.seed, own.memberId);
3629
+ const anchor = crypto.keyPair(deviceSeed);
3630
+ const deviceProof = await this._shortestAnchorProof(account, {
3631
+ anchor,
3632
+ memberId: own.memberId,
3633
+ memberProof: own.memberProof
3634
+ });
3635
+ if (!(await delegationFits(deviceProof, anchor))) {
3632
3636
  throw new CoreError('DEVICE_INVITE_CHAIN_TOO_LONG');
3633
3637
  }
3634
3638
  return { deviceSeed, deviceProof };
3635
3639
  }
3640
+ async _shortestAnchorProof(account, { anchor, memberId, memberProof }) {
3641
+ const keyPair = this._requireDeviceKeyPair();
3642
+ let shortest = await attestDeviceProof(anchor.publicKey, keyPair, memberProof);
3643
+ for await (const row of account.view.find(DEVICES)) {
3644
+ if (row.revoked || !row.memberId || !row.memberProof)
3645
+ continue;
3646
+ if (!b4a.equals(row.memberId, memberId))
3647
+ continue;
3648
+ const cut = chainTo(row.memberProof, anchor.publicKey);
3649
+ if (cut && cut.byteLength < shortest.byteLength) {
3650
+ shortest = cut;
3651
+ }
3652
+ }
3653
+ return shortest;
3654
+ }
3636
3655
  previewMeshInvite(invite) {
3637
3656
  const decoded = decodeMeshInvite(invite);
3638
3657
  if (!decoded) {
@@ -63,6 +63,7 @@ export interface CredentialPusherLogger {
63
63
  }
64
64
  export type CredentialPusherHandle = (() => Promise<void>) & {
65
65
  sync(): Promise<void>;
66
+ ready(): Promise<void>;
66
67
  };
67
68
  export declare function nextRefreshDelay(entries: ReadonlyArray<Pick<CredentialEntry, 'expiresAt'>>, now?: number): number;
68
69
  export declare function credentialOwners(catalog: ReadonlyArray<PusherSkill>): ReadonlyMap<string, readonly string[]>;
@@ -101,52 +101,39 @@ function fanOut(entry, owners) {
101
101
  const skills = owners.get(entry.key) ?? [];
102
102
  return skills.length > 0 ? skills.map((skill) => ({ ...entry, skill })) : [entry];
103
103
  }
104
- async function resolveScope(agentId, { engine, last, owners, specs, logger }) {
105
- const entries = [];
106
- for (const spec of specs) {
107
- const mk = storeKey(spec.credentialKey, agentId);
108
- try {
109
- const entry = await oauthEntry(engine, spec, agentId);
110
- if (entry) {
111
- last.set(mk, entry);
112
- entries.push(...fanOut(entry, owners));
113
- }
114
- else {
115
- last.delete(mk);
116
- }
117
- }
118
- catch (err) {
119
- logger?.warn('credential-pusher', `credential resolve failed for ${spec.credentialKey}`, errorMessage(err));
120
- const kept = last.get(mk);
121
- if (kept) {
122
- entries.push(...fanOut(kept, owners));
123
- }
104
+ async function resolveEntry({ mk, failure, read }, { last, owners, logger }) {
105
+ try {
106
+ const entry = await read();
107
+ if (!entry) {
108
+ last.delete(mk);
109
+ return [];
124
110
  }
111
+ last.set(mk, entry);
112
+ return fanOut(entry, owners);
125
113
  }
126
- const specKeys = new Set(specs.map((spec) => spec.credentialKey));
127
- for (const key of PLAIN_KEYS) {
128
- if (specKeys.has(key))
129
- continue;
130
- const mk = storeKey(key, agentId);
131
- try {
132
- const entry = await plainEntry(engine, key, agentId);
133
- if (entry) {
134
- last.set(mk, entry);
135
- entries.push(...fanOut(entry, owners));
136
- }
137
- else {
138
- last.delete(mk);
139
- }
140
- }
141
- catch (err) {
142
- logger?.warn('credential-pusher', `credential read failed for ${key}`, errorMessage(err));
143
- const kept = last.get(mk);
144
- if (kept) {
145
- entries.push(...fanOut(kept, owners));
146
- }
147
- }
114
+ catch (err) {
115
+ logger?.warn('credential-pusher', failure, errorMessage(err));
116
+ const kept = last.get(mk);
117
+ return kept ? fanOut(kept, owners) : [];
148
118
  }
149
- return entries;
119
+ }
120
+ async function resolveScope(agentId, resolution) {
121
+ const { engine, specs } = resolution;
122
+ const specKeys = new Set(specs.map((spec) => spec.credentialKey));
123
+ const pending = [
124
+ ...specs.map((spec) => ({
125
+ mk: storeKey(spec.credentialKey, agentId),
126
+ failure: `credential resolve failed for ${spec.credentialKey}`,
127
+ read: () => oauthEntry(engine, spec, agentId)
128
+ })),
129
+ ...PLAIN_KEYS.filter((key) => !specKeys.has(key)).map((key) => ({
130
+ mk: storeKey(key, agentId),
131
+ failure: `credential read failed for ${key}`,
132
+ read: () => plainEntry(engine, key, agentId)
133
+ }))
134
+ ];
135
+ const resolved = await Promise.all(pending.map((entry) => resolveEntry(entry, resolution)));
136
+ return resolved.flat();
150
137
  }
151
138
  async function resolveSettings(engine, scopes, { catalog, logger }) {
152
139
  const fields = settingFields(catalog);
@@ -289,9 +276,8 @@ export function startCredentialPusher(harness, engine, logger) {
289
276
  syncWatches(specs.map((spec) => spec.credentialKey), scopes);
290
277
  syncAgentsWatch(meshId);
291
278
  const resolution = { engine, last, owners, specs, logger };
292
- for (const agentId of scopes) {
293
- entries.push(...(await resolveScope(agentId, resolution)));
294
- }
279
+ const resolved = await Promise.all(scopes.map((agentId) => resolveScope(agentId, resolution)));
280
+ entries.push(...resolved.flat());
295
281
  if (disposed) {
296
282
  return;
297
283
  }
@@ -346,7 +332,7 @@ export function startCredentialPusher(harness, engine, logger) {
346
332
  pushLock.unlock();
347
333
  }
348
334
  };
349
- schedule();
335
+ const first = schedule();
350
336
  const stop = async () => {
351
337
  if (disposed)
352
338
  return;
@@ -366,6 +352,6 @@ export function startCredentialPusher(harness, engine, logger) {
366
352
  pushLock.destroy();
367
353
  await pushLock.flush();
368
354
  };
369
- return Object.assign(stop, { sync });
355
+ return Object.assign(stop, { sync, ready: () => first });
370
356
  }
371
357
  function noop() { }
@@ -588,6 +588,14 @@ declare const DEFINITIONS: {
588
588
  readonly code: 101218;
589
589
  readonly message: (status: number, text: string) => string;
590
590
  };
591
+ readonly OAUTH_TOKEN_EXCHANGE_TIMEOUT: {
592
+ readonly code: 101219;
593
+ readonly message: () => string;
594
+ };
595
+ readonly OAUTH_REGISTRATION_TIMEOUT: {
596
+ readonly code: 101220;
597
+ readonly message: () => string;
598
+ };
591
599
  readonly SIDECAR_ENTRY_MISSING: {
592
600
  readonly code: 101301;
593
601
  readonly message: () => string;
@@ -518,6 +518,14 @@ const DEFINITIONS = {
518
518
  code: 101218,
519
519
  message: (status, text) => `Token refresh failed (${status}): ${text}`
520
520
  },
521
+ OAUTH_TOKEN_EXCHANGE_TIMEOUT: {
522
+ code: 101219,
523
+ message: () => 'OAuth token exchange timed out'
524
+ },
525
+ OAUTH_REGISTRATION_TIMEOUT: {
526
+ code: 101220,
527
+ message: () => 'OAuth client registration timed out'
528
+ },
521
529
  SIDECAR_ENTRY_MISSING: {
522
530
  code: 101301,
523
531
  message: () => 'sidecar mode needs a stowed bundle entry'
@@ -32,10 +32,12 @@ export async function runOAuthFlowWithRuntime(config, deps, runtime) {
32
32
  state,
33
33
  pkce
34
34
  });
35
+ deps.onStage?.('awaiting-callback');
35
36
  const callback = await redirect.authorize(`${config.authUrl}?${authParams.toString()}`, deps.timeoutMs, state);
36
37
  if (callback.state !== state) {
37
38
  throw new CoreError('OAUTH_STATE_MISMATCH');
38
39
  }
40
+ deps.onStage?.('exchanging-code');
39
41
  return exchangeCodeWithFetch(config, {
40
42
  clientId,
41
43
  redirectUri: redirect.redirectUri,
@@ -1,3 +1,4 @@
1
1
  import type { OAuthLoopbackServer, OAuthLoopbackTarget } from './redirect-types.ts';
2
2
  export declare function abortOAuthLoopback(credentialKey: string): Promise<boolean>;
3
+ export declare function deliverOAuthCallback(address: string): boolean;
3
4
  export declare function openOAuthLoopback(port: number, target: OAuthLoopbackTarget): Promise<OAuthLoopbackServer>;
@@ -1,7 +1,7 @@
1
1
  import { createServer } from 'http';
2
2
  import { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, oauthRedirectUri } from './keys.js';
3
3
  import { CoreError } from '../errors.js';
4
- const DONE_PAGE = '<html><body><p>Authorization complete. You may close this tab.</p>' +
4
+ const DONE_PAGE = '<html><body><p>Authorization complete. Return to QV.AC to finish connecting. You may close this tab.</p>' +
5
5
  '<script>window.close();</script></body></html>';
6
6
  const STALE_PAGE = '<html><body><p>This sign-in link is from an earlier attempt. ' +
7
7
  'You can close this tab.</p></body></html>';
@@ -18,6 +18,36 @@ function abortFor(credentialKey, reason) {
18
18
  }
19
19
  return pending.length > 0;
20
20
  }
21
+ export function deliverOAuthCallback(address) {
22
+ const params = callbackParams(address);
23
+ const state = params?.get('state');
24
+ const waiter = state ? pendingWaiter(state) : undefined;
25
+ if (!params || !state || !waiter) {
26
+ return false;
27
+ }
28
+ settle(waiter, callbackSettlement(params, state));
29
+ return true;
30
+ }
31
+ function callbackParams(address) {
32
+ let url;
33
+ try {
34
+ url = new URL(address.trim());
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ const finished = url.searchParams.has('code') || url.searchParams.has('error');
40
+ return url.pathname === OAUTH_CALLBACK_PATH && finished ? url.searchParams : null;
41
+ }
42
+ function pendingWaiter(state) {
43
+ for (const loopback of loopbacks) {
44
+ const waiter = loopback.waiters.get(state);
45
+ if (waiter && waiter.settled === null) {
46
+ return waiter;
47
+ }
48
+ }
49
+ return undefined;
50
+ }
21
51
  export async function openOAuthLoopback(port, target) {
22
52
  if (!Number.isInteger(port) || port < 0 || port > 65535) {
23
53
  throw new CoreError('OAUTH_LOOPBACK_PORT_INVALID', [port]);
@@ -1,36 +1,51 @@
1
1
  import * as z from 'zod';
2
+ import { providerRequest } from './request.js';
2
3
  import { CoreError } from '../errors.js';
3
4
  const RegistrationResponseSchema = z.object({
4
5
  client_id: z.string().min(1)
5
6
  });
6
- export async function registerOAuthClient(config, redirectUri, fetchImpl = globalThis.fetch) {
7
+ export function registerOAuthClient(config, redirectUri, fetchImpl) {
8
+ return register(config, redirectUri, { fetchImpl });
9
+ }
10
+ async function register(config, redirectUri, { fetchImpl = globalThis.fetch, timeoutMs }) {
7
11
  if (!config.registrationEndpoint) {
8
12
  throw new CoreError('OAUTH_REGISTRATION_UNAVAILABLE');
9
13
  }
10
- const response = await fetchImpl(config.registrationEndpoint, {
11
- method: 'POST',
12
- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
13
- body: JSON.stringify({
14
- client_name: 'QV.AC',
15
- redirect_uris: [redirectUri],
16
- grant_types: ['authorization_code', 'refresh_token'],
17
- response_types: ['code'],
18
- token_endpoint_auth_method: 'none',
19
- application_type: 'native'
20
- })
14
+ return await providerRequest({
15
+ fetchImpl,
16
+ url: config.registrationEndpoint,
17
+ init: {
18
+ method: 'POST',
19
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
20
+ body: JSON.stringify({
21
+ client_name: 'QV.AC',
22
+ redirect_uris: [redirectUri],
23
+ grant_types: ['authorization_code', 'refresh_token'],
24
+ response_types: ['code'],
25
+ token_endpoint_auth_method: 'none',
26
+ application_type: 'native'
27
+ })
28
+ },
29
+ timeoutMs,
30
+ timeout: () => new CoreError('OAUTH_REGISTRATION_TIMEOUT'),
31
+ read: async (response) => {
32
+ if (!response.ok) {
33
+ const text = await response.text().catch(() => '');
34
+ throw new CoreError('OAUTH_REGISTRATION_FAILED', [response.status, text]);
35
+ }
36
+ return RegistrationResponseSchema.parse(await response.json()).client_id;
37
+ }
21
38
  });
22
- if (!response.ok) {
23
- const text = await response.text().catch(() => '');
24
- throw new CoreError('OAUTH_REGISTRATION_FAILED', [response.status, text]);
25
- }
26
- return RegistrationResponseSchema.parse(await response.json()).client_id;
27
39
  }
28
40
  export async function resolveDynamicClientId(config, redirectUri, deps, fetchImpl) {
29
41
  const cached = await deps.getClientId?.();
30
42
  if (cached) {
31
43
  return cached;
32
44
  }
33
- const clientId = await registerOAuthClient(config, redirectUri, fetchImpl);
45
+ const clientId = await register(config, redirectUri, {
46
+ fetchImpl,
47
+ timeoutMs: deps.requestTimeoutMs
48
+ });
34
49
  await deps.saveClientId?.(clientId);
35
50
  return clientId;
36
51
  }
@@ -0,0 +1,10 @@
1
+ import type { OAuthFetch } from './types.ts';
2
+ export interface ProviderRequest<T> {
3
+ readonly fetchImpl: OAuthFetch;
4
+ readonly url: string;
5
+ readonly init: RequestInit;
6
+ readonly timeoutMs?: number | undefined;
7
+ readonly timeout: () => Error;
8
+ readonly read: (response: Response) => Promise<T>;
9
+ }
10
+ export declare function providerRequest<T>({ fetchImpl, url, init, timeoutMs, timeout, read }: ProviderRequest<T>): Promise<T>;
@@ -0,0 +1,22 @@
1
+ import { AbortController as BareAbortController } from 'bare-abort-controller';
2
+ const PROVIDER_REQUEST_TIMEOUT_MS = 30_000;
3
+ const AbortController = globalThis.AbortController ?? BareAbortController;
4
+ export async function providerRequest({ fetchImpl, url, init, timeoutMs = PROVIDER_REQUEST_TIMEOUT_MS, timeout, read }) {
5
+ const controller = new AbortController();
6
+ let timer;
7
+ const expired = new Promise((_resolve, reject) => {
8
+ timer = globalThis.setTimeout(() => {
9
+ controller.abort();
10
+ reject(timeout());
11
+ }, timeoutMs);
12
+ });
13
+ try {
14
+ return await Promise.race([
15
+ fetchImpl(url, { ...init, signal: controller.signal }).then(read),
16
+ expired
17
+ ]);
18
+ }
19
+ finally {
20
+ globalThis.clearTimeout(timer);
21
+ }
22
+ }
@@ -1,8 +1,6 @@
1
- import { AbortController as BareAbortController } from 'bare-abort-controller';
2
1
  import * as z from 'zod';
2
+ import { providerRequest } from './request.js';
3
3
  import { CoreError } from '../errors.js';
4
- const TOKEN_REQUEST_TIMEOUT_MS = 30_000;
5
- const AbortController = globalThis.AbortController ?? BareAbortController;
6
4
  const TokenResponseSchema = z.object({
7
5
  access_token: z.string(),
8
6
  token_type: z.string(),
@@ -51,19 +49,23 @@ export async function exchangeCodeWithFetch(config, { clientId, redirectUri, cod
51
49
  Accept: 'application/json'
52
50
  };
53
51
  applyClientSecret(config, body, headers);
54
- const response = await fetchImpl(config.tokenUrl, {
55
- method: 'POST',
56
- headers,
57
- body: body.toString()
58
- });
59
- if (!response.ok) {
60
- const text = await response.text().catch(() => '');
61
- if (config.dynamicRegistration && /invalid_client/i.test(text)) {
62
- await deps.clearClientId?.();
52
+ return await providerRequest({
53
+ fetchImpl,
54
+ url: config.tokenUrl,
55
+ init: { method: 'POST', headers, body: body.toString() },
56
+ timeoutMs: deps.requestTimeoutMs,
57
+ timeout: () => new CoreError('OAUTH_TOKEN_EXCHANGE_TIMEOUT'),
58
+ read: async (response) => {
59
+ if (!response.ok) {
60
+ const text = await response.text().catch(() => '');
61
+ if (config.dynamicRegistration && /invalid_client/i.test(text)) {
62
+ await deps.clearClientId?.();
63
+ }
64
+ throw new CoreError('OAUTH_TOKEN_EXCHANGE_FAILED', [response.status, text]);
65
+ }
66
+ return toTokens(parseTokenResponse(await response.json()));
63
67
  }
64
- throw new CoreError('OAUTH_TOKEN_EXCHANGE_FAILED', [response.status, text]);
65
- }
66
- return toTokens(parseTokenResponse(await response.json()));
68
+ });
67
69
  }
68
70
  export async function refreshOAuthTokensWithFetch(config, refreshToken, fetchImpl) {
69
71
  const body = new URLSearchParams({
@@ -76,24 +78,19 @@ export async function refreshOAuthTokensWithFetch(config, refreshToken, fetchImp
76
78
  Accept: 'application/json'
77
79
  };
78
80
  applyClientSecret(config, body, headers);
79
- const controller = new AbortController();
80
- const timeout = globalThis.setTimeout(() => controller.abort(new CoreError('OAUTH_TOKEN_REFRESH_TIMEOUT')), TOKEN_REQUEST_TIMEOUT_MS);
81
- try {
82
- const response = await fetchImpl(config.tokenUrl, {
83
- method: 'POST',
84
- headers,
85
- body: body.toString(),
86
- signal: controller.signal
87
- });
88
- if (!response.ok) {
89
- const text = await response.text().catch(() => '');
90
- throw new CoreError('OAUTH_TOKEN_REFRESH_FAILED', [response.status, text]);
81
+ return await providerRequest({
82
+ fetchImpl,
83
+ url: config.tokenUrl,
84
+ init: { method: 'POST', headers, body: body.toString() },
85
+ timeout: () => new CoreError('OAUTH_TOKEN_REFRESH_TIMEOUT'),
86
+ read: async (response) => {
87
+ if (!response.ok) {
88
+ const text = await response.text().catch(() => '');
89
+ throw new CoreError('OAUTH_TOKEN_REFRESH_FAILED', [response.status, text]);
90
+ }
91
+ return toTokens(parseTokenResponse(await response.json()), refreshToken);
91
92
  }
92
- return toTokens(parseTokenResponse(await response.json()), refreshToken);
93
- }
94
- finally {
95
- globalThis.clearTimeout(timeout);
96
- }
93
+ });
97
94
  }
98
95
  export function isTokenExpired(record, bufferMs = 60_000) {
99
96
  return typeof record.expiresAt === 'number' && Date.now() + bufferMs >= record.expiresAt;
@@ -27,13 +27,16 @@ interface OAuthProviderConfigBase {
27
27
  readonly dynamicRegistration?: boolean;
28
28
  readonly registrationEndpoint?: string;
29
29
  }
30
+ export type OAuthFlowStage = 'awaiting-callback' | 'exchanging-code';
30
31
  export interface OAuthFlowDeps {
31
32
  readonly openUrl?: (url: string) => Promise<void>;
32
33
  readonly timeoutMs?: number;
34
+ readonly requestTimeoutMs?: number;
33
35
  readonly getClientId?: () => Promise<string | undefined>;
34
36
  readonly saveClientId?: (clientId: string) => Promise<void>;
35
37
  readonly clearClientId?: () => Promise<void>;
36
38
  readonly createRedirect?: OAuthRedirectFactory;
39
+ readonly onStage?: (stage: OAuthFlowStage) => void;
37
40
  }
38
41
  export type PkceOnlyProviderConfig = OAuthProviderConfigBase & {
39
42
  readonly tokenAuth: 'pkce-only';
@@ -1,5 +1,6 @@
1
1
  export { waitForOAuthCallback } from './oauth/browser-connect.ts';
2
2
  export { cancelOAuthFlow, runOAuthFlow } from './oauth/flow.ts';
3
+ export { deliverOAuthCallback } from './oauth/loopback.ts';
3
4
  export { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, oauthRedirectUri, scopedKey, specFromRoute, type OAuthKeySpec, type OAuthRouteLike } from './oauth/keys.ts';
4
5
  export { oauthSpecFor, oauthSpecs } from './oauth/registry.ts';
5
6
  export { createPkce, generatePkceChallenge, type PkceChallenge } from './oauth/pkce.ts';
@@ -8,4 +9,4 @@ export type { OAuthCallbackResult, OAuthRedirect, OAuthRedirectFactory } from '.
8
9
  export { registerOAuthClient, resolveDynamicClientId } from './oauth/register.ts';
9
10
  export { resolveOAuthCredential, type ConfigEngine, type Fetch, type FetchResponse } from './oauth/resolve.ts';
10
11
  export { isTokenExpired, refreshOAuthTokens } from './oauth/token-exchange.ts';
11
- export type { OAuthCredentials, OAuthFlowDeps, OAuthFlowResult, OAuthProvider, OAuthProviderConfig, OAuthTokens } from './oauth/types.ts';
12
+ export type { OAuthCredentials, OAuthFlowDeps, OAuthFlowResult, OAuthFlowStage, OAuthProvider, OAuthProviderConfig, OAuthTokens } from './oauth/types.ts';
@@ -1,5 +1,6 @@
1
1
  export { waitForOAuthCallback } from './oauth/browser-connect.js';
2
2
  export { cancelOAuthFlow, runOAuthFlow } from './oauth/flow.js';
3
+ export { deliverOAuthCallback } from './oauth/loopback.js';
3
4
  export { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, oauthRedirectUri, scopedKey, specFromRoute } from './oauth/keys.js';
4
5
  export { oauthSpecFor, oauthSpecs } from './oauth/registry.js';
5
6
  export { createPkce, generatePkceChallenge } from './oauth/pkce.js';
@@ -4,13 +4,19 @@ export interface ReplayChat {
4
4
  readonly holder: string;
5
5
  readonly chatId: string;
6
6
  }
7
+ export interface SentRun {
8
+ readonly messages: ChatMessage[];
9
+ readonly asked?: string | undefined;
10
+ }
7
11
  export declare class RunReplayStore {
8
12
  private readonly _dir;
9
13
  constructor(dir: string);
10
14
  started(): Promise<boolean>;
11
15
  start(): Promise<void>;
12
- load({ holder, chatId }: ReplayChat): Promise<Map<string, ChatMessage[]>>;
13
- save({ holder, chatId }: ReplayChat, runId: string, messages: ChatMessage[]): Promise<void>;
16
+ load(chat: ReplayChat): Promise<Map<string, ChatMessage[]>>;
17
+ loadAsked(chat: ReplayChat): Promise<Map<string, string>>;
18
+ save({ holder, chatId }: ReplayChat, runId: string, { messages, asked }: SentRun): Promise<void>;
19
+ private _records;
14
20
  forget(chatId: string, holder?: string): Promise<void>;
15
21
  clear(holder: string): Promise<void>;
16
22
  private _chatDir;
@@ -19,30 +19,48 @@ export class RunReplayStore {
19
19
  async start() {
20
20
  await fs.promises.mkdir(this._dir, { recursive: true });
21
21
  }
22
- async load({ holder, chatId }) {
23
- const chatDir = this._chatDir(holder, chatId);
22
+ async load(chat) {
24
23
  const runs = new Map();
24
+ for (const record of await this._records(chat)) {
25
+ if (Array.isArray(record.messages)) {
26
+ runs.set(record.runId, record.messages.filter(isChatMessage));
27
+ }
28
+ }
29
+ return runs;
30
+ }
31
+ async loadAsked(chat) {
32
+ const asked = new Map();
33
+ for (const record of await this._records(chat)) {
34
+ if (typeof record.asked === 'string') {
35
+ asked.set(record.runId, record.asked);
36
+ }
37
+ }
38
+ return asked;
39
+ }
40
+ async save({ holder, chatId }, runId, { messages, asked }) {
41
+ const chatDir = this._chatDir(holder, chatId);
42
+ await fs.promises.mkdir(chatDir, { recursive: true });
43
+ await fs.promises.writeFile(join(chatDir, `${safeName(runId)}.json`), JSON.stringify({ runId, messages, asked }));
44
+ }
45
+ async _records({ holder, chatId }) {
46
+ const chatDir = this._chatDir(holder, chatId);
25
47
  let names;
26
48
  try {
27
49
  names = await fs.promises.readdir(chatDir);
28
50
  }
29
51
  catch {
30
- return runs;
52
+ return [];
31
53
  }
54
+ const records = [];
32
55
  for (const name of names) {
33
56
  if (!name.endsWith('.json'))
34
57
  continue;
35
58
  const parsed = JSON.parse(await fs.promises.readFile(join(chatDir, name), 'utf8'));
36
- if (isRecord(parsed) && typeof parsed.runId === 'string' && Array.isArray(parsed.messages)) {
37
- runs.set(parsed.runId, parsed.messages.filter(isChatMessage));
59
+ if (isRecord(parsed) && typeof parsed.runId === 'string') {
60
+ records.push({ runId: parsed.runId, messages: parsed.messages, asked: parsed.asked });
38
61
  }
39
62
  }
40
- return runs;
41
- }
42
- async save({ holder, chatId }, runId, messages) {
43
- const chatDir = this._chatDir(holder, chatId);
44
- await fs.promises.mkdir(chatDir, { recursive: true });
45
- await fs.promises.writeFile(join(chatDir, `${safeName(runId)}.json`), JSON.stringify({ runId, messages }));
63
+ return records;
46
64
  }
47
65
  async forget(chatId, holder) {
48
66
  const holders = holder === undefined ? await this._holders() : [holder];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qvac/core",
3
- "version": "0.10.4",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Peer-to-peer AI across your devices",
6
6
  "engines": {
@@ -241,9 +241,9 @@
241
241
  },
242
242
  "dependencies": {
243
243
  "@qvac/error": "^0.2.0",
244
- "@qvac/harness": "^0.8.11",
244
+ "@qvac/harness": "^0.8.13",
245
245
  "@qvac/logging": "^0.2.0",
246
- "@qvac/skills": "^0.1.16",
246
+ "@qvac/skills": "^0.1.18",
247
247
  "asenion": "^0.1.0",
248
248
  "autobee": "^2.11.8",
249
249
  "b4a": "^1.9.0",
@@ -364,7 +364,8 @@
364
364
  "hyperdb": "^6.9.0",
365
365
  "hypercore": "^11.37.0",
366
366
  "hyperbee2": "^2.18.0",
367
- "tar": "^7.5.22"
367
+ "tar": "^7.5.22",
368
+ "bare-tls": "^3.1.13"
368
369
  },
369
370
  "publishConfig": {
370
371
  "access": "public"