@arbidocs/react 0.4.9 → 0.4.10
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.
- package/README.md +9 -0
- package/dist/artifacts/index.cjs +153 -19
- package/dist/artifacts/index.cjs.map +1 -1
- package/dist/artifacts/index.d.cts +120 -8
- package/dist/artifacts/index.d.ts +120 -8
- package/dist/artifacts/index.js +128 -19
- package/dist/artifacts/index.js.map +1 -1
- package/dist/{chunk-TA3IZP7I.cjs → chunk-K5TOB34Q.cjs} +3 -3
- package/dist/{chunk-TA3IZP7I.cjs.map → chunk-K5TOB34Q.cjs.map} +1 -1
- package/dist/{chunk-E7UO2JSR.cjs → chunk-KKSSTNJK.cjs} +110 -2
- package/dist/chunk-KKSSTNJK.cjs.map +1 -0
- package/dist/{chunk-RTULVZOS.js → chunk-NVMQLJI4.js} +3 -3
- package/dist/{chunk-RTULVZOS.js.map → chunk-NVMQLJI4.js.map} +1 -1
- package/dist/{chunk-R5SR7R6W.js → chunk-UV5ZEUNV.js} +105 -3
- package/dist/chunk-UV5ZEUNV.js.map +1 -0
- package/dist/index.cjs +394 -370
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +9 -9
- package/dist/stored-markdown-DMwFzWhc.d.cts +75 -0
- package/dist/stored-markdown-DMwFzWhc.d.ts +75 -0
- package/dist/ui/index.cjs +147 -147
- package/dist/ui/index.js +2 -2
- package/package.json +3 -3
- package/dist/chunk-E7UO2JSR.cjs.map +0 -1
- package/dist/chunk-R5SR7R6W.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { useArbi } from './chunk-J4MX2W4H.js';
|
|
2
|
+
import { normalizeCitationMarkup } from './chunk-TGGQGFS3.js';
|
|
2
3
|
import { useMemo } from 'react';
|
|
3
4
|
import { useQuery, useMutation, useQueryClient, useQueries } from '@tanstack/react-query';
|
|
4
5
|
|
|
@@ -297,6 +298,107 @@ function useUserUsageToday(options) {
|
|
|
297
298
|
});
|
|
298
299
|
}
|
|
299
300
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
301
|
+
// src/ai/stored-markdown.ts
|
|
302
|
+
var FENCE = /^\s*(```|~~~)/;
|
|
303
|
+
function mapOutsideFences(text, fn) {
|
|
304
|
+
let inFence = false;
|
|
305
|
+
return text.split("\n").map((line) => {
|
|
306
|
+
if (FENCE.test(line)) {
|
|
307
|
+
inFence = !inFence;
|
|
308
|
+
return line;
|
|
309
|
+
}
|
|
310
|
+
return inFence ? line : fn(line);
|
|
311
|
+
}).join("\n");
|
|
312
|
+
}
|
|
313
|
+
var ESCAPED_PUNCTUATION = /\\([\\`*_{}[\]()#+\-.!|>~<])/g;
|
|
314
|
+
var ESCAPED_EMPHASIS = /\\([*_])/g;
|
|
315
|
+
var INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\1(?!`)/g;
|
|
316
|
+
function unescapeMarkdown(text) {
|
|
317
|
+
if (!text.includes("\\")) return text;
|
|
318
|
+
return mapOutsideFences(text, (line) => {
|
|
319
|
+
if (!line.includes("\\")) return line;
|
|
320
|
+
let out = "";
|
|
321
|
+
let last = 0;
|
|
322
|
+
for (const span of line.matchAll(INLINE_CODE)) {
|
|
323
|
+
const at = span.index ?? 0;
|
|
324
|
+
out += line.slice(last, at).replace(ESCAPED_PUNCTUATION, "$1") + span[0].replace(ESCAPED_EMPHASIS, "$1");
|
|
325
|
+
last = at + span[0].length;
|
|
326
|
+
}
|
|
327
|
+
return out + line.slice(last).replace(ESCAPED_PUNCTUATION, "$1");
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function repairParsedTitle(text) {
|
|
331
|
+
const lines = text.split("\n");
|
|
332
|
+
const first = lines.findIndex((l) => l.trim());
|
|
333
|
+
if (first < 0) return text;
|
|
334
|
+
const doubled = /^#{1,6}\s+(#{1,6}\s+\S.*)$/.exec(lines[first]);
|
|
335
|
+
if (doubled) {
|
|
336
|
+
lines[first] = doubled[1];
|
|
337
|
+
return lines.join("\n");
|
|
338
|
+
}
|
|
339
|
+
if (/^\s*```\s*$/.test(lines[first]) && /^#{1,6}\s+\S/.test(lines[first + 1] ?? "")) {
|
|
340
|
+
if (/^\s*```\s*$/.test(lines[first + 2] ?? "")) lines.splice(first + 2, 1);
|
|
341
|
+
else return text;
|
|
342
|
+
lines.splice(first, 1);
|
|
343
|
+
return lines.join("\n");
|
|
344
|
+
}
|
|
345
|
+
return text;
|
|
346
|
+
}
|
|
347
|
+
var SOURCE_NOTE = /[ \t]*(?:\*+\(\s*Sources?\s*:[^)\n]*\)\*+|\(\s*\*{0,2}\s*Sources?\s*:[^)\n]*\))/gi;
|
|
348
|
+
var CITE_LINK = /\[([^\]\n]+)\]\(#cite-[\w-]+\)/g;
|
|
349
|
+
function balanceBold(line) {
|
|
350
|
+
if (/^\s*\*\*#{1,6}\s/.test(line)) return line.replace(/\*\*/g, "").trim();
|
|
351
|
+
if ((line.match(/\*\*/g)?.length ?? 0) % 2 === 0) return line;
|
|
352
|
+
if (/^#{1,6}\s/.test(line)) return line.replace(/\*\*/g, "");
|
|
353
|
+
return line.replace(/\*\*\s*$/, "").replace(/^(\s*(?:[-*]\s+)?)\*\*(?=\s)/, "$1");
|
|
354
|
+
}
|
|
355
|
+
function unwrapCitationLinks(text) {
|
|
356
|
+
const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ""));
|
|
357
|
+
return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {
|
|
358
|
+
const unlinked = line.includes("](#cite-") ? line.replace(CITE_LINK, "$1") : line;
|
|
359
|
+
return unlinked === line ? line : balanceBold(unlinked);
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
var HEADING = /^#{1,6}\s/;
|
|
363
|
+
var BOLD_LINE = /^\*\*[^*#].*[^*]\*\*$/;
|
|
364
|
+
var TITLE_SEARCH_LINES = 15;
|
|
365
|
+
var MAX_PREAMBLE_CHARS = 1200;
|
|
366
|
+
var NARRATION = /\b(?:I|I'll|I’ll|I've|I’ve|I'm|I’m|I will|I have|I now|I am)\b|\b(?:let me|here is|here's|here’s|below is|per the instructions|as requested|based on (?:the|your)|the workspace (?:contains|has|does)|no (?:relevant )?documents? (?:were|was) found)\b/i;
|
|
367
|
+
var STRUCTURED = /^\s*(?:[-*+>|]|\d{1,9}[.)]\s|#{1,6}\s|```|~~~)/m;
|
|
368
|
+
function stripAgentPreamble(text) {
|
|
369
|
+
const lines = text.split("\n");
|
|
370
|
+
let start = lines.findIndex((l) => HEADING.test(l));
|
|
371
|
+
if (start < 0)
|
|
372
|
+
start = lines.slice(0, TITLE_SEARCH_LINES).findIndex((l) => BOLD_LINE.test(l.trim()));
|
|
373
|
+
if (start <= 0) return text;
|
|
374
|
+
const before = lines.slice(0, start).join("\n").trim();
|
|
375
|
+
if (!before) return lines.slice(start).join("\n");
|
|
376
|
+
const prose = before.replace(/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/gm, "").trim();
|
|
377
|
+
if (prose.length > MAX_PREAMBLE_CHARS || STRUCTURED.test(prose) || !NARRATION.test(prose)) {
|
|
378
|
+
return text;
|
|
379
|
+
}
|
|
380
|
+
return lines.slice(start).join("\n");
|
|
381
|
+
}
|
|
382
|
+
function promoteBoldTitle(text) {
|
|
383
|
+
const lines = text.split("\n");
|
|
384
|
+
const first = lines.findIndex((l) => l.trim());
|
|
385
|
+
if (first < 0) return text;
|
|
386
|
+
const title = lines[first].trim();
|
|
387
|
+
if (!/^\*\*[^*#]/.test(title) || title.length >= 160 || !/\*\*$/.test(title)) return text;
|
|
388
|
+
lines[first] = `# ${title.replace(/\*\*/g, "").trim()}`;
|
|
389
|
+
return lines.join("\n");
|
|
390
|
+
}
|
|
391
|
+
function cleanHeadings(text) {
|
|
392
|
+
return mapOutsideFences(
|
|
393
|
+
text,
|
|
394
|
+
(line) => /^\s*#{1,6}\s/.test(line) ? line.replace(/\*\*/g, "").trim() : line
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
function cleanDraftMarkdown(raw) {
|
|
398
|
+
const stripped = stripAgentPreamble(unwrapCitationLinks(raw));
|
|
399
|
+
return cleanHeadings(promoteBoldTitle(stripped)).replace(/\n{3,}/g, "\n\n").trim();
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export { DEFAULT_USD_PER_CREDIT, arbiQueryKeys, cleanDraftMarkdown, creditsToUsd, formatCredits, isUsageMetered, promoteBoldTitle, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks, useActivity, useAgents, useAssistantQuery, useConfigs, useConversationThreads, useConversations, useDeleteAgents, useDocuments, useFacts, useHealth, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSessions, useTags, useTasks, useThumbnails, useUserUsageToday, useWorkspaces };
|
|
403
|
+
//# sourceMappingURL=chunk-UV5ZEUNV.js.map
|
|
404
|
+
//# sourceMappingURL=chunk-UV5ZEUNV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/credits.ts","../src/hooks.ts","../src/ai/stored-markdown.ts"],"names":[],"mappings":";;;;;;AAWO,IAAM,sBAAA,GAAyB;AAU/B,SAAS,aAAA,CAAc,OAAA,EAAiB,OAAA,GAAgC,EAAC,EAAW;AACzF,EAAA,MAAM,EAAE,IAAA,GAAO,IAAA,EAAM,MAAA,GAAS,SAAQ,GAAI,OAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,KAAK,KAAA,CAAM,MAAA,CAAO,SAAS,OAAO,CAAA,GAAI,UAAU,CAAC,CAAA;AAC/D,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,cAAA,CAAe,MAAM,CAAA;AAC1C,EAAA,OAAO,IAAA,GAAO,GAAG,MAAM,CAAA,CAAA,EAAI,UAAU,CAAA,GAAI,QAAA,GAAW,SAAS,CAAA,CAAA,GAAK,MAAA;AACpE;AAGO,SAAS,YAAA,CACd,OAAA,EACA,YAAA,GAAuB,sBAAA,EACf;AAC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GAAG,OAAO,IAAA;AACtB,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAK,CAAA,CAAE,IAAA,EAAK;AAChC,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAK,CAAA,IAAK,KAAA,CAAM,MAAA,IAAU,GAAA,IAAO,CAAC,OAAA,CAAQ,IAAA,CAAK,KAAK,GAAG,OAAO,IAAA;AACrF,EAAA,KAAA,CAAM,KAAK,IAAI,CAAA,EAAA,EAAK,KAAA,CAAM,QAAQ,OAAA,EAAS,EAAE,CAAA,CAAE,IAAA,EAAM,CAAA,CAAA;AACrD,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB;AAGA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,gBAAA;AAAA,IAAiB,IAAA;AAAA,IAAM,CAAC,IAAA,KAC7B,cAAA,CAAe,IAAA,CAAK,IAAI,CAAA,GAAI,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,EAAE,CAAA,CAAE,IAAA,EAAK,GAAI;AAAA,GACjE;AACF;AAOO,SAAS,mBAAmB,GAAA,EAAqB;AACtD,EAAA,MAAM,QAAA,GAAW,kBAAA,CAAmB,mBAAA,CAAoB,GAAG,CAAC,CAAA;AAC5D,EAAA,OAAO,aAAA,CAAc,iBAAiB,QAAQ,CAAC,EAC5C,OAAA,CAAQ,SAAA,EAAW,MAAM,CAAA,CACzB,IAAA,EAAK;AACV","file":"chunk-UV5ZEUNV.js","sourcesContent":["/**\n * Credits: the unit the ARBI backend reports AI usage in.\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered USD\n * spend into whole credits at the API boundary: 1 credit = `CREDITS_TO_AI_USD`, which is $0.01 on\n * a default deployment. The fields are still named `spend` / `total_spend` in the schema, but they\n * hold CREDITS, never dollars. Label them as credits; use {@link creditsToUsd} only when a\n * dollar figure is genuinely wanted, with the deployment's own rate.\n */\n\n/** Dollars per credit on a default deployment (`CREDITS_TO_AI_USD`). */\nexport const DEFAULT_USD_PER_CREDIT = 0.01\n\nexport interface FormatCreditsOptions {\n /** Append the unit (\"12 credits\"). Default true; pass false inside a column headed \"Credits\". */\n unit?: boolean\n /** BCP 47 locale for the digit grouping. Default `en-US`. */\n locale?: string\n}\n\n/** \"1,234 credits\" / \"1 credit\". The backend reports whole credits; this rounds away float dust. */\nexport function formatCredits(credits: number, options: FormatCreditsOptions = {}): string {\n const { unit = true, locale = 'en-US' } = options\n const whole = Math.round(Number.isFinite(credits) ? credits : 0)\n const digits = whole.toLocaleString(locale)\n return unit ? `${digits} ${whole === 1 ? 'credit' : 'credits'}` : digits\n}\n\n/** The dollar value of an amount of credits. `usdPerCredit` defaults to {@link DEFAULT_USD_PER_CREDIT}. */\nexport function creditsToUsd(\n credits: number,\n usdPerCredit: number = DEFAULT_USD_PER_CREDIT\n): number {\n return credits * usdPerCredit\n}\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A project on the `dev` plan belongs to a deployment with\n * billing switched off: the backend only records AI usage per project when billing is enabled, so\n * an all-zero response there means \"not metered\", not \"nothing happened\". Show a note instead of\n * silent zeros.\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useMemo } from 'react'\nimport { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'\nimport type {\n SSEStreamResult,\n SSEStreamStartData,\n ResponseOutputItemDoneEvent,\n ArtifactEvent,\n UserMessageEvent,\n MessageMetadataPayload,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './credits'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\nexport const arbiQueryKeys = {\n workspaces: () => ['arbi', 'workspaces'] as const,\n documents: (workspaceId: string) => ['arbi', 'documents', workspaceId] as const,\n conversations: (workspaceId: string) => ['arbi', 'conversations', workspaceId] as const,\n conversationThreads: (workspaceId: string, conversationId: string) =>\n ['arbi', 'conversations', workspaceId, 'threads', conversationId] as const,\n tags: (workspaceId: string) => ['arbi', 'tags', workspaceId] as const,\n thumbnails: (docIds: string[]) => ['arbi', 'thumbnails', [...docIds].sort().join(',')] as const,\n parsedDoc: (docId: string, stage: string) => ['arbi', 'parsedDoc', docId, stage] as const,\n agents: () => ['arbi', 'agents'] as const,\n sessions: () => ['arbi', 'sessions'] as const,\n health: () => ['arbi', 'health'] as const,\n tasks: () => ['arbi', 'tasks'] as const,\n facts: (workspaceId: string) => ['arbi', 'facts', workspaceId] as const,\n configs: () => ['arbi', 'configs'] as const,\n activity: () => ['arbi', 'activity'] as const,\n projects: () => ['arbi', 'projects'] as const,\n projectUsage: (projectExtId: string, monthsBack: number) =>\n ['arbi', 'projectUsage', projectExtId, monthsBack] as const,\n projectInvoices: (projectExtId: string) => ['arbi', 'projectInvoices', projectExtId] as const,\n userUsageToday: () => ['arbi', 'userUsageToday'] as const,\n contacts: () => ['arbi', 'contacts'] as const,\n skills: () => ['arbi', 'skills'] as const,\n taskRuns: (taskId: string) => ['arbi', 'taskRuns', taskId] as const,\n /** An agent's pinned config; `undefined` = the library default config. */\n agentConfig: (agentExtId?: string) => ['arbi', 'agentConfig', agentExtId ?? 'default'] as const,\n agentWorkspaces: (agentExtId: string) => ['arbi', 'agentWorkspaces', agentExtId] as const,\n models: () => ['arbi', 'models'] as const,\n /** The signed-in user's own profile (name, picture, email). */\n profile: () => ['arbi', 'profile'] as const,\n /** The signed-in user's settings record (notification preferences, flags). */\n userSettings: () => ['arbi', 'userSettings'] as const,\n}\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** List documents in a workspace. */\nexport function useDocuments(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documents(workspaceId ?? ''),\n queryFn: () => arbi.documents.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/** List conversations in a workspace. */\nexport function useConversations(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.conversations.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included).\n * Always refetched on mount: a conversation that was open before may have new turns.\n */\nexport function useConversationThreads(\n workspaceId: string | undefined,\n conversationId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? '', conversationId ?? ''),\n queryFn: () => arbi.conversations.getThreads(conversationId as string),\n enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,\n gcTime: 0,\n })\n}\n\n/** List tags in a workspace. */\nexport function useTags(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tags(workspaceId ?? ''),\n queryFn: () => arbi.tags.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages.\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () =>\n arbi.documents.getParsedContent(docId as string, stage) as unknown as Promise<ParsedDocument>,\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/** Send a streaming query to the RAG assistant. Returns a mutation. */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n\n return useMutation<\n SSEStreamResult,\n Error,\n {\n question: string\n docIds: string[]\n previousResponseId?: string | null\n model?: string\n onToken?: (content: string) => void\n /** Aborts the request and the stream; the mutation then rejects with an `AbortError`. */\n signal?: AbortSignal\n onStreamStart?: (data: SSEStreamStartData) => void\n onUserMessage?: (data: UserMessageEvent) => void\n onMetadata?: (data: MessageMetadataPayload) => void\n onOutputItemDone?: (data: ResponseOutputItemDoneEvent) => void\n onArtifact?: (data: ArtifactEvent) => void\n onError?: (message: string) => void\n onComplete?: () => void\n }\n >({\n mutationFn: ({ question, ...options }) => arbi.assistant.query(question, options),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * Delete agents. Returns a mutation. Refreshes the agent list and the task list (a deleted\n * agent's tasks go with it), and drops the deleted agents' own config and workspace queries.\n */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n const qc = useQueryClient()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n onSuccess: (_result, { agentExtIds }) => {\n for (const id of agentExtIds) {\n qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) })\n qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) })\n }\n return Promise.all([\n qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.tasks() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() }),\n ])\n },\n })\n}\n\n/** List active sessions. */\nexport function useSessions(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.sessions(),\n queryFn: () => arbi.sessions.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n// ── Scheduled tasks ──────────────────────────────────────────────────────────\n\n/** List the caller's scheduled agent tasks. */\nexport function useTasks(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tasks(),\n queryFn: () => arbi.tasks.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Workspace notes ──────────────────────────────────────────────────────────\n\n/** List the open workspace's facts. */\nexport function useFacts(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; pinnedOnly?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.facts(workspaceId ?? ''),\n queryFn: () => arbi.facts.list({ pinnedOnly: options?.pinnedOnly }),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configs(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are CREDITS, not dollars (see `formatCredits`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** Credits used that day (not dollars). */\n credits: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** Credits used by this model group (not dollars). */\n credits: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in CREDITS (1 credit = $0.01 by default), not dollars. */\n totalCredits: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most credits first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalCredits = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalCredits += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n credits: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.credits += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n credits: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.credits += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalCredits,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.credits - a.credits || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/** Today's deployment-wide credit use for the current user (`credits_used`, in credits). */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n","/**\n * Helpers for markdown that is STORED (an agent's draft saved as an artifact, then read back from\n * the backend's parse). Pure and SDK-free; they sit next to `normalizeCitationMarkup`, which they\n * build on.\n *\n * Two directions:\n *\n * - Going in (`cleanDraftMarkdown` = `unwrapCitationLinks` + `stripAgentPreamble` +\n * `promoteBoldTitle`): a streamed draft carries citation links, `(*Source: ...*)` notes and\n * sometimes narration before the document. A stored letter should hold only the letter.\n * - Coming out (`unescapeMarkdown`): the backend's parse of a stored `.md` returns the text with\n * markdown punctuation backslash-escaped (`**Fees.**` comes back as `\\*\\*Fees\\.\\*\\*`).\n */\n\nimport { normalizeCitationMarkup } from './normalize-citations'\n\nconst FENCE = /^\\s*(```|~~~)/\n\n/** Run `fn` on every line outside a fenced code block. */\nfunction mapOutsideFences(text: string, fn: (line: string) => string): string {\n let inFence = false\n return text\n .split('\\n')\n .map((line) => {\n if (FENCE.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : fn(line)\n })\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Coming out: undo the parser's escaping\n// ---------------------------------------------------------------------------------------------\n\n/** A backslash followed by markdown punctuation: the only thing the parser's escaping produces. */\nconst ESCAPED_PUNCTUATION = /\\\\([\\\\`*_{}[\\]()#+\\-.!|>~<])/g\n/** The only escapes the parser puts inside an inline code span. */\nconst ESCAPED_EMPHASIS = /\\\\([*_])/g\nconst INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\\1(?!`)/g\n\n/**\n * Undo the backend's escaping of a markdown artifact: `\\*\\*Scope\\.\\*\\*` becomes `**Scope.**`.\n *\n * THE RULE. Apply this ONLY to text of an artifact that was stored from markdown (an agent draft\n * or an edited version, always uploaded as `.md`): for those the parser escapes every markdown\n * punctuation character, including the backslash itself, so removing one level of escaping is the\n * exact inverse (an author's literal `\\*` is stored as `\\\\\\*` and comes back as `\\*`). Do not\n * apply it to a PDF or Word parse, where a backslash is just a character.\n *\n * Details:\n * - Only a backslash followed by markdown punctuation (``\\ ` * _ { } [ ] ( ) # + - . ! | > ~ <``)\n * is removed; `\\n`, `C:\\temp` and a trailing backslash are left alone.\n * - Pairs are read left to right, so `\\\\*` is an escaped backslash followed by a bare `*`.\n * - Fenced code blocks are never touched (the parser does not escape inside them).\n * - Inline code spans: the parser DOES escape `*` and `_` there (`` `a*b` `` comes back as\n * `` `a\\*b` ``), so only `\\*` and `\\_` are undone inside a span; any other backslash in code\n * (`` `re\\.x` ``) is a literal and stays.\n */\nexport function unescapeMarkdown(text: string): string {\n if (!text.includes('\\\\')) return text\n return mapOutsideFences(text, (line) => {\n if (!line.includes('\\\\')) return line\n let out = ''\n let last = 0\n for (const span of line.matchAll(INLINE_CODE)) {\n const at = span.index ?? 0\n out +=\n line.slice(last, at).replace(ESCAPED_PUNCTUATION, '$1') +\n span[0].replace(ESCAPED_EMPHASIS, '$1')\n last = at + span[0].length\n }\n return out + line.slice(last).replace(ESCAPED_PUNCTUATION, '$1')\n })\n}\n\n/**\n * The parser also mangles the TITLE of a stored markdown document (seen on a real backend): the\n * first heading comes back doubled (`## # Title`) or alone inside a code fence\n * (a fence, `# Title`, a fence). Both are repaired, on the first non-blank line only, so a code\n * block or heading later in the text is never touched. Like `unescapeMarkdown`, apply it only to\n * artifacts stored from markdown.\n */\nexport function repairParsedTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const doubled = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/.exec(lines[first])\n if (doubled) {\n lines[first] = doubled[1]\n return lines.join('\\n')\n }\n if (/^\\s*```\\s*$/.test(lines[first]) && /^#{1,6}\\s+\\S/.test(lines[first + 1] ?? '')) {\n if (/^\\s*```\\s*$/.test(lines[first + 2] ?? '')) lines.splice(first + 2, 1)\n else return text\n lines.splice(first, 1)\n return lines.join('\\n')\n }\n return text\n}\n\n// ---------------------------------------------------------------------------------------------\n// Going in: clean a streamed draft before it is stored\n// ---------------------------------------------------------------------------------------------\n\n/** `(*Source: Terms.pdf*)`, `(Sources: a, b)` and the italic form `*(Source: ...)*`. */\nconst SOURCE_NOTE =\n /[ \\t]*(?:\\*+\\(\\s*Sources?\\s*:[^)\\n]*\\)\\*+|\\(\\s*\\*{0,2}\\s*Sources?\\s*:[^)\\n]*\\))/gi\nconst CITE_LINK = /\\[([^\\]\\n]+)\\]\\(#cite-[\\w-]+\\)/g\n\n/** A line whose `**` do not pair up (one half was wrapped into a link) loses the stray marks. */\nfunction balanceBold(line: string): string {\n // A bold-wrapped heading (`**# Title**`) is just a heading.\n if (/^\\s*\\*\\*#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '').trim()\n if ((line.match(/\\*\\*/g)?.length ?? 0) % 2 === 0) return line\n if (/^#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '')\n return line.replace(/\\*\\*\\s*$/, '').replace(/^(\\s*(?:[-*]\\s+)?)\\*\\*(?=\\s)/, '$1')\n}\n\n/**\n * Text for storage from text that carries citations: `normalizeCitationMarkup` first (it hoists\n * list, heading and bold tokens out of the link so unwrapping cannot orphan half of a `**` pair),\n * then `[text](#cite-N)` becomes `text`, `(*Source: ...*)` notes are dropped, and a bold or\n * heading marker that lost its partner is repaired. Fenced code is left alone.\n */\nexport function unwrapCitationLinks(text: string): string {\n const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ''))\n return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {\n const unlinked = line.includes('](#cite-') ? line.replace(CITE_LINK, '$1') : line\n return unlinked === line ? line : balanceBold(unlinked)\n })\n}\n\nconst HEADING = /^#{1,6}\\s/\n/** A whole-line bold title: `**Client Engagement Letter**`. */\nconst BOLD_LINE = /^\\*\\*[^*#].*[^*]\\*\\*$/\n/** How far down a bold line may sit and still be the document's title. */\nconst TITLE_SEARCH_LINES = 15\nconst MAX_PREAMBLE_CHARS = 1200\n\n/** First person, an announcement of the task or a pointer at the instructions: an agent talking. */\nconst NARRATION =\n /\\b(?:I|I'll|I’ll|I've|I’ve|I'm|I’m|I will|I have|I now|I am)\\b|\\b(?:let me|here is|here's|here’s|below is|per the instructions|as requested|based on (?:the|your)|the workspace (?:contains|has|does)|no (?:relevant )?documents? (?:were|was) found)\\b/i\n\n/** Structure a covering note would not have: lists, tables, quotes, code, headings. */\nconst STRUCTURED = /^\\s*(?:[-*+>|]|\\d{1,9}[.)]\\s|#{1,6}\\s|```|~~~)/m\n\n/**\n * Cut what an agent wrote BEFORE the document, when it is narration.\n *\n * HEURISTIC (conservative, so a document is never trimmed by mistake). The document is taken to\n * start at the first `#` heading, or, when there is none, at the first whole-line bold title within\n * the first 15 lines. The text before it is removed only when ALL of these hold:\n * 1. it is short (at most 1200 characters);\n * 2. it is plain prose: no list, table, quote, code or heading;\n * 3. it reads like the agent talking: first person (\"I'll draft ...\"), \"Here is ...\", \"Per the\n * instructions\", \"Based on the ...\" and the like.\n * A document that opens with a dateline, an address or any text that does not trip rule 3 is kept\n * whole. A horizontal rule left at the end of the cut text is dropped with it.\n */\nexport function stripAgentPreamble(text: string): string {\n const lines = text.split('\\n')\n let start = lines.findIndex((l) => HEADING.test(l))\n if (start < 0)\n start = lines.slice(0, TITLE_SEARCH_LINES).findIndex((l) => BOLD_LINE.test(l.trim()))\n if (start <= 0) return text\n const before = lines.slice(0, start).join('\\n').trim()\n if (!before) return lines.slice(start).join('\\n')\n const prose = before.replace(/^\\s*(?:-{3,}|\\*{3,}|_{3,})\\s*$/gm, '').trim()\n if (prose.length > MAX_PREAMBLE_CHARS || STRUCTURED.test(prose) || !NARRATION.test(prose)) {\n return text\n }\n return lines.slice(start).join('\\n')\n}\n\n/**\n * Make the document's title a real heading: a first line that is a bold title (`**Letter**`, even\n * with stray inner `**`) becomes `# Letter`. A document that already opens with a heading is left\n * alone.\n */\nexport function promoteBoldTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const title = lines[first].trim()\n if (!/^\\*\\*[^*#]/.test(title) || title.length >= 160 || !/\\*\\*$/.test(title)) return text\n lines[first] = `# ${title.replace(/\\*\\*/g, '').trim()}`\n return lines.join('\\n')\n}\n\n/** Tidy headings only: strip stray bold marks from heading lines (`# **Title**`). */\nfunction cleanHeadings(text: string): string {\n return mapOutsideFences(text, (line) =>\n /^\\s*#{1,6}\\s/.test(line) ? line.replace(/\\*\\*/g, '').trim() : line\n )\n}\n\n/**\n * Everything a streamed draft needs before it is stored as the artifact's first version:\n * `unwrapCitationLinks`, `stripAgentPreamble`, `promoteBoldTitle`, clean headings, collapsed blank\n * runs, trimmed.\n */\nexport function cleanDraftMarkdown(raw: string): string {\n const stripped = stripAgentPreamble(unwrapCitationLinks(raw))\n return cleanHeadings(promoteBoldTitle(stripped))\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n"]}
|