@agentproto/corpus-cli 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  export { N as NodeFsAdapter, a as NodeFsAdapterOptions, O as OsIdentityAdapter, b as OsIdentityAdapterOptions } from '../os-identity.adapter-CLBmnRoD.js';
2
- import { FetcherPort, FetchedSource, PrSourcePort, PrQuery, PrDoc, DistillPort, DistillInput, DistilledItem, SinkPort, SinkItem, SinkPushResult } from '@agentproto/corpus';
2
+ import { FetcherPort, FetchedSource, PrSourcePort, PrQuery, PrDoc, DistillPort, DistillInput, DistilledItem, DistillBatchPort, SinkPort, SinkItem, SinkPushResult } from '@agentproto/corpus';
3
3
  export { buildDistillPrompt, parseItems } from '@agentproto/corpus';
4
+ import { BatchDriver, BatchStore, BatchStatus } from '@agentproto/batch';
4
5
  import { z } from 'zod';
5
6
 
6
7
  /**
@@ -494,6 +495,11 @@ interface DistillUsage {
494
495
  readonly label: string;
495
496
  readonly startedAt: string;
496
497
  readonly endedAt: string;
498
+ /** "batch" halves the cost estimate — a provider batch API call, billed at
499
+ * 50% of the standard token price. Absent/"standard" → full price. */
500
+ readonly billing?: "standard" | "batch";
501
+ /** Prompt-cache hit tokens, when the provider reports them. */
502
+ readonly cacheReadInputTokens?: number;
497
503
  }
498
504
 
499
505
  /**
@@ -625,6 +631,58 @@ declare class CliAgentDistiller implements DistillPort {
625
631
  distill(input: DistillInput): Promise<readonly DistilledItem[]>;
626
632
  }
627
633
 
634
+ /**
635
+ * BatchDistiller — a DistillPort + DistillBatchPort backed by a provider
636
+ * Batch API (`@agentproto/batch`). Builds one BatchRequest per source (same
637
+ * Messages body + shared prompt as AnthropicDistiller), submits them all in
638
+ * one call, polls to completion, and maps succeeded results back through the
639
+ * shared `parseItems`. `expired`/`errored`/`canceled` items are reported and
640
+ * left undistilled — the existing resume ledger picks them up next run.
641
+ *
642
+ * `distill(input)` (the plain single-item DistillPort method) delegates to
643
+ * `distillMany` with one entry, so a BatchDistiller still satisfies any
644
+ * caller that only knows the non-batch `DistillPort` shape.
645
+ */
646
+
647
+ interface BatchDistillerOptions {
648
+ readonly driver: BatchDriver;
649
+ readonly store: BatchStore;
650
+ /** Default a current Claude model id. */
651
+ readonly model?: string;
652
+ /** Max refined items to extract per source. */
653
+ readonly maxItems?: number;
654
+ /** Output language code (e.g. "fr"). Absent → English (default). */
655
+ readonly lang?: string;
656
+ readonly pollIntervalMs?: number;
657
+ /** Optional sink for per-item token usage (cost + Langfuse export). */
658
+ readonly onUsage?: (usage: DistillUsage) => void;
659
+ /** Optional sink for poll progress (counts per tick). */
660
+ readonly onProgress?: (status: BatchStatus) => void;
661
+ /** Re-attach to a batch already submitted in a prior, interrupted run —
662
+ * skip submit and go straight to poll/collect/write. */
663
+ readonly batchId?: string;
664
+ }
665
+ interface KeyedInput {
666
+ readonly key: string;
667
+ readonly input: DistillInput;
668
+ }
669
+ declare class BatchDistiller implements DistillPort, DistillBatchPort {
670
+ private readonly driver;
671
+ private readonly store;
672
+ private readonly model;
673
+ private readonly maxItems;
674
+ private readonly lang;
675
+ private readonly pollIntervalMs;
676
+ private readonly onUsage;
677
+ private readonly onProgress;
678
+ private readonly batchId;
679
+ constructor(opts: BatchDistillerOptions);
680
+ distill(input: DistillInput): Promise<readonly DistilledItem[]>;
681
+ distillMany(inputs: ReadonlyArray<KeyedInput>): Promise<ReadonlyMap<string, readonly DistilledItem[]>>;
682
+ private resolveHandle;
683
+ private reportUsage;
684
+ }
685
+
628
686
  /**
629
687
  * Minimal streamable-HTTP MCP client (host-agnostic). Used by config-driven
630
688
  * sinks/sources to call ANY MCP server's tools — the corpus never names a
@@ -683,4 +741,4 @@ declare class McpSink implements SinkPort {
683
741
  push(item: SinkItem): Promise<SinkPushResult>;
684
742
  }
685
743
 
686
- export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, GhPrSourceAdapter, type GhPrSourceAdapterOptions, type GhRunner, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, type PdfExtraction, type PdfExtractor, PdfFetcher, type PdfFetcherOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
744
+ export { AnthropicDistiller, type AnthropicDistillerOptions, AssemblyAiStt, type AssemblyAiSttOptions, type AudioDownload, type AudioDownloader, type AudioSplitter, BatchDistiller, type BatchDistillerOptions, BrowserMcpFetcher, type BrowserMcpFetcherOptions, type BrowserMcpLike, CLI_ENGINES, ChunkedStt, type ChunkedSttOptions, CliAgentDistiller, type CliAgentDistillerOptions, type CliEngine, CompositeFetcher, type ConnectMcpHttpOptions, GhPrSourceAdapter, type GhPrSourceAdapterOptions, type GhRunner, HttpReadabilityFetcher, type HttpReadabilityFetcherOptions, type McpClientLike, McpSink, type McpSinkConfig, OpenAiWhisperStt, type OpenAiWhisperSttOptions, type PdfExtraction, type PdfExtractor, PdfFetcher, type PdfFetcherOptions, ScrapeMcpFetcher, type ScrapeMcpFetcherOptions, type SttPort, ThrottleFetcher, type ThrottleFetcherOptions, type Transcript, YtDlpWhisperFetcher, type YtDlpWhisperFetcherOptions, connectMcpHttp };
@@ -10,6 +10,7 @@ import { normalizeLanguageTag, buildDistillPrompt, parseItems } from '@agentprot
10
10
  export { buildDistillPrompt, parseItems } from '@agentproto/corpus';
11
11
  import { getDocumentProxy, extractText as extractText$1, getMeta } from 'unpdf';
12
12
  import { parseClaudeJsonOutput, spawnWithStdin } from '@agentproto/cli-exec';
13
+ import { validateForBatch, pollUntilEnded, collectResults, expiredCustomIds } from '@agentproto/batch';
13
14
 
14
15
  /**
15
16
  * @agentproto/corpus-cli v0.1.0-alpha
@@ -1146,6 +1147,118 @@ var CliAgentDistiller = class {
1146
1147
  return parseItems(text);
1147
1148
  }
1148
1149
  };
1150
+ var BatchDistiller = class {
1151
+ driver;
1152
+ store;
1153
+ model;
1154
+ maxItems;
1155
+ lang;
1156
+ pollIntervalMs;
1157
+ onUsage;
1158
+ onProgress;
1159
+ batchId;
1160
+ constructor(opts) {
1161
+ this.driver = opts.driver;
1162
+ this.store = opts.store;
1163
+ this.model = opts.model ?? "claude-sonnet-5";
1164
+ this.maxItems = opts.maxItems ?? 8;
1165
+ this.lang = opts.lang;
1166
+ this.pollIntervalMs = opts.pollIntervalMs;
1167
+ this.onUsage = opts.onUsage;
1168
+ this.onProgress = opts.onProgress;
1169
+ this.batchId = opts.batchId;
1170
+ }
1171
+ async distill(input) {
1172
+ const key = "single";
1173
+ const results = await this.distillMany([{ key, input }]);
1174
+ return results.get(key) ?? [];
1175
+ }
1176
+ async distillMany(inputs) {
1177
+ const requests = inputs.map(({ key, input }) => ({
1178
+ customId: key,
1179
+ body: {
1180
+ model: this.model,
1181
+ max_tokens: 4096,
1182
+ messages: [
1183
+ { role: "user", content: buildDistillPrompt(input, this.maxItems, { lang: this.lang }) }
1184
+ ]
1185
+ }
1186
+ }));
1187
+ for (const request of requests) validateForBatch(request);
1188
+ const handle = await this.resolveHandle(requests);
1189
+ await pollUntilEnded(this.driver, handle, {
1190
+ ...this.pollIntervalMs !== void 0 ? { intervalMs: this.pollIntervalMs } : {},
1191
+ onTick: (status) => {
1192
+ process.stderr.write(
1193
+ ` batch ${handle.id}: ${status.state} \u2014 processing ${status.counts.processing} \xB7 succeeded ${status.counts.succeeded} \xB7 errored ${status.counts.errored} \xB7 expired ${status.counts.expired}
1194
+ `
1195
+ );
1196
+ this.onProgress?.(status);
1197
+ }
1198
+ });
1199
+ const results = await collectResults(this.driver, handle);
1200
+ await this.store.appendResults(handle.id, Array.from(results.values()));
1201
+ const inputByKey = new Map(inputs.map((entry) => [entry.key, entry.input]));
1202
+ const errored = [];
1203
+ const out = /* @__PURE__ */ new Map();
1204
+ for (const result of results.values()) {
1205
+ if (result.outcome === "succeeded") {
1206
+ this.reportUsage(result, inputByKey);
1207
+ out.set(result.customId, parseItems(extractText3(result)));
1208
+ } else if (result.outcome === "errored") {
1209
+ errored.push(result.customId);
1210
+ }
1211
+ }
1212
+ const expired = expiredCustomIds(results.values());
1213
+ if (expired.length > 0) {
1214
+ process.stderr.write(
1215
+ ` batch ${handle.id}: expired, left undistilled (resubmit next run): ${expired.join(", ")}
1216
+ `
1217
+ );
1218
+ }
1219
+ if (errored.length > 0) {
1220
+ process.stderr.write(
1221
+ ` batch ${handle.id}: errored, left undistilled: ${errored.join(", ")}
1222
+ `
1223
+ );
1224
+ }
1225
+ return out;
1226
+ }
1227
+ async resolveHandle(requests) {
1228
+ if (this.batchId) {
1229
+ const record = await this.store.load(this.batchId);
1230
+ if (!record) throw new Error(`--batch-id ${this.batchId}: no such batch in the store`);
1231
+ return record.handle;
1232
+ }
1233
+ const handle = await this.driver.submit(requests);
1234
+ await this.store.create(handle, requests);
1235
+ process.stderr.write(
1236
+ ` batch id: ${handle.id} \u2014 re-attach with --batch-id ${handle.id} if this run is interrupted
1237
+ `
1238
+ );
1239
+ return handle;
1240
+ }
1241
+ reportUsage(result, inputByKey) {
1242
+ if (!this.onUsage || !result.message) return;
1243
+ const input = inputByKey.get(result.customId);
1244
+ this.onUsage({
1245
+ model: result.message.model,
1246
+ inputTokens: result.message.usage.input_tokens,
1247
+ outputTokens: result.message.usage.output_tokens,
1248
+ label: input?.title ?? result.customId,
1249
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1250
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1251
+ billing: "batch",
1252
+ ...result.message.usage.cache_read_input_tokens !== void 0 ? { cacheReadInputTokens: result.message.usage.cache_read_input_tokens } : {}
1253
+ });
1254
+ }
1255
+ };
1256
+ function extractText3(result) {
1257
+ for (const block of result.message?.content ?? []) {
1258
+ if (block.type === "text" && typeof block.text === "string") return block.text;
1259
+ }
1260
+ return "";
1261
+ }
1149
1262
  var ANSI = new RegExp(String.fromCharCode(27) + "\\[[0-9;]*m", "g");
1150
1263
  function plainTextOutput(stdout) {
1151
1264
  return stdout.replace(ANSI, "");
@@ -1512,6 +1625,6 @@ function msg4(e) {
1512
1625
  return e instanceof Error ? e.message : String(e);
1513
1626
  }
1514
1627
 
1515
- export { AnthropicDistiller, AssemblyAiStt, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, PdfFetcher, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
1628
+ export { AnthropicDistiller, AssemblyAiStt, BatchDistiller, BrowserMcpFetcher, CLI_ENGINES, ChunkedStt, CliAgentDistiller, CompositeFetcher, GhPrSourceAdapter, HttpReadabilityFetcher, McpSink, NodeFsAdapter, OpenAiWhisperStt, OsIdentityAdapter, PdfFetcher, ScrapeMcpFetcher, ThrottleFetcher, YtDlpWhisperFetcher, connectMcpHttp };
1516
1629
  //# sourceMappingURL=index.mjs.map
1517
1630
  //# sourceMappingURL=index.mjs.map