opencrowd 0.5.3 → 0.6.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 (2) hide show
  1. package/bundle/opencrowd.js +497 -219
  2. package/package.json +1 -1
@@ -15548,7 +15548,7 @@ var init_commands = __esm({
15548
15548
  });
15549
15549
 
15550
15550
  // ../../packages/protocol/dist/events.js
15551
- var eventBase, runScoped, turnField, WorkerReadyEventSchema, CommandAcceptedEventSchema, CommandRejectionReasonSchema, CommandRejectedEventSchema, RunStateEventSchema, AssistantDeltaEventSchema, AssistantMessageEventSchema, ToolStartedEventSchema, ToolStatusSchema, ToolFinishedEventSchema, ArtifactCreatedEventSchema, UsageUpdatedEventSchema, ApprovalRequestSchema, ApprovalRequiredEventSchema, FundingRequiredEventSchema, DelegationProblemSchema, DelegationRequiredEventSchema, PaymentUnknownEventSchema, CheckpointReasonSchema, CheckpointCompletedEventSchema, RunFinishedEventSchema, RuntimeErrorEventSchema, UserMessageEventSchema, EVENT_TYPES, EventTypeSchema, EventSchema;
15551
+ var eventBase, runScoped, turnField, WorkerReadyEventSchema, CommandAcceptedEventSchema, CommandRejectionReasonSchema, CommandRejectedEventSchema, RunStateEventSchema, AssistantDeltaEventSchema, AssistantMessageEventSchema, ToolStartedEventSchema, ToolStatusSchema, ToolFinishedEventSchema, ModelStartedEventSchema, ModelFinishedEventSchema, ArtifactCreatedEventSchema, UsageUpdatedEventSchema, ApprovalRequestSchema, ApprovalRequiredEventSchema, FundingRequiredEventSchema, DelegationProblemSchema, DelegationRequiredEventSchema, PaymentUnknownEventSchema, CheckpointReasonSchema, CheckpointCompletedEventSchema, RunFinishedEventSchema, RuntimeErrorEventSchema, UserMessageEventSchema, EVENT_TYPES, EventTypeSchema, EventSchema;
15552
15552
  var init_events = __esm({
15553
15553
  "../../packages/protocol/dist/events.js"() {
15554
15554
  "use strict";
@@ -15667,6 +15667,22 @@ var init_events = __esm({
15667
15667
  ...turnField
15668
15668
  })
15669
15669
  });
15670
+ ModelStartedEventSchema = external_exports.looseObject({
15671
+ ...runScoped,
15672
+ type: external_exports.literal("model.started"),
15673
+ payload: external_exports.looseObject({ callId: IdSchema, model: external_exports.string(), ...turnField })
15674
+ });
15675
+ ModelFinishedEventSchema = external_exports.looseObject({
15676
+ ...runScoped,
15677
+ type: external_exports.literal("model.finished"),
15678
+ payload: external_exports.looseObject({
15679
+ callId: IdSchema,
15680
+ model: external_exports.string(),
15681
+ status: ToolStatusSchema,
15682
+ durationMs: external_exports.number().nonnegative(),
15683
+ ...turnField
15684
+ })
15685
+ });
15670
15686
  ArtifactCreatedEventSchema = external_exports.looseObject({
15671
15687
  ...runScoped,
15672
15688
  type: external_exports.literal("artifact.created"),
@@ -15805,6 +15821,8 @@ var init_events = __esm({
15805
15821
  "assistant.delta",
15806
15822
  "assistant.message",
15807
15823
  "user.message",
15824
+ "model.started",
15825
+ "model.finished",
15808
15826
  "tool.started",
15809
15827
  "tool.finished",
15810
15828
  "artifact.created",
@@ -15826,6 +15844,8 @@ var init_events = __esm({
15826
15844
  RunStateEventSchema,
15827
15845
  AssistantDeltaEventSchema,
15828
15846
  AssistantMessageEventSchema,
15847
+ ModelStartedEventSchema,
15848
+ ModelFinishedEventSchema,
15829
15849
  ToolStartedEventSchema,
15830
15850
  ToolFinishedEventSchema,
15831
15851
  ArtifactCreatedEventSchema,
@@ -15875,6 +15895,48 @@ var init_redact = __esm({
15875
15895
  }
15876
15896
  });
15877
15897
 
15898
+ // ../../packages/protocol/dist/telemetry.js
15899
+ function scrubText(text) {
15900
+ return text.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, "[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi, "Bearer [REDACTED]").replace(/\b(?:sk-[A-Za-z0-9_-]{16,}|ph[csx]_[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b/g, "[REDACTED]").replace(/\b((?:[A-Z_]*(?:SECRET|PASSWORD|API_KEY|PRIVATE_KEY|ACCESS_TOKEN)[A-Z_]*|authorization|cookie|signature|x-amz-signature)\s*[=:]\s*)[^\s&,;]+/gi, "$1[REDACTED]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g, "$1[REDACTED]@");
15901
+ }
15902
+ function captureDetail(input2, maxBytes = 96 * 1024) {
15903
+ let redacted = false;
15904
+ const clean3 = (value2, depth = 0) => {
15905
+ if (depth > 30)
15906
+ return "[depth limit]";
15907
+ if (typeof value2 === "string") {
15908
+ const s3 = scrubText(value2);
15909
+ redacted ||= s3 !== value2;
15910
+ return s3;
15911
+ }
15912
+ if (Array.isArray(value2))
15913
+ return value2.map((v) => clean3(v, depth + 1));
15914
+ if (value2 && typeof value2 === "object") {
15915
+ return Object.fromEntries(Object.entries(value2).map(([key, v]) => {
15916
+ if (isSensitiveKey(key) || /^(signature|privatekey|seedphrase|mnemonic)$/i.test(key)) {
15917
+ redacted = true;
15918
+ return [key, "[REDACTED]"];
15919
+ }
15920
+ return [key, clean3(v, depth + 1)];
15921
+ }));
15922
+ }
15923
+ return typeof value2 === "bigint" ? value2.toString() : value2 ?? null;
15924
+ };
15925
+ const value = clean3(input2), json3 = JSON.stringify(value), bytes = new TextEncoder().encode(json3).length;
15926
+ return {
15927
+ value: bytes > maxBytes ? { preview: json3.slice(0, Math.floor(maxBytes / 6)) } : value,
15928
+ redacted,
15929
+ truncated: bytes > maxBytes,
15930
+ bytes
15931
+ };
15932
+ }
15933
+ var init_telemetry = __esm({
15934
+ "../../packages/protocol/dist/telemetry.js"() {
15935
+ "use strict";
15936
+ init_redact();
15937
+ }
15938
+ });
15939
+
15878
15940
  // ../../packages/protocol/dist/seq.js
15879
15941
  var init_seq = __esm({
15880
15942
  "../../packages/protocol/dist/seq.js"() {
@@ -16062,6 +16124,7 @@ var init_dist = __esm({
16062
16124
  init_commands();
16063
16125
  init_events();
16064
16126
  init_redact();
16127
+ init_telemetry();
16065
16128
  init_seq();
16066
16129
  init_codec();
16067
16130
  init_context();
@@ -16348,7 +16411,7 @@ function normalizeConfig(value) {
16348
16411
  const proxyDefaults = providerDefaults(raw["openrouter-x402-proxy"] ?? raw.x402, DEFAULT_CONFIG["openrouter-x402-proxy"]);
16349
16412
  const mcpServers = recordValue(raw.mcpServers);
16350
16413
  const servers = { ...DEFAULT_CONFIG.mcpServers, ...mcpServers };
16351
- if (servers.crowdcode?.command === "npx" && JSON.stringify(servers.crowdcode.args) === JSON.stringify(["--yes", "crowdcode-mcp@0.5"])) {
16414
+ if (servers.crowdcode?.command === "npx" && ["0.5", "0.5.2", "0.5.3"].some((version6) => JSON.stringify(servers.crowdcode.args) === JSON.stringify(["--yes", `crowdcode-mcp@${version6}`]))) {
16352
16415
  servers.crowdcode = { ...servers.crowdcode, args: [...DEFAULT_CONFIG.mcpServers.crowdcode.args] };
16353
16416
  }
16354
16417
  return {
@@ -16398,7 +16461,7 @@ var init_config = __esm({
16398
16461
  configVersion: 3,
16399
16462
  mcpServers: {
16400
16463
  agentcash: { command: "npx", args: ["--yes", "agentcash@0.17"] },
16401
- crowdcode: { command: "npx", args: ["--yes", "crowdcode-mcp@0.5.2"] }
16464
+ crowdcode: { command: "npx", args: ["--yes", "crowdcode-mcp@0.6.0"] }
16402
16465
  },
16403
16466
  // GAIA provider benchmark (2026-08-25): same-model BlockRun matched the
16404
16467
  // current route's accuracy and completed the sample 6.7x faster. The
@@ -33475,10 +33538,36 @@ function normalizeEvidence(raw) {
33475
33538
  score: numberValue3(record3.score),
33476
33539
  nEff: numberValue3(record3.n_eff ?? record3.nEff),
33477
33540
  unproven: typeof record3.unproven === "boolean" ? record3.unproven : void 0,
33478
- summary: typeof record3.summary === "string" ? record3.summary : void 0,
33541
+ summary: summarizeEvidence(record3),
33479
33542
  raw
33480
33543
  };
33481
33544
  }
33545
+ function summarizeEvidence(record3) {
33546
+ const summary = record3.summary;
33547
+ const lines = [];
33548
+ if (typeof summary === "string" && summary)
33549
+ lines.push(summary);
33550
+ else if (summary && typeof summary === "object" && !Array.isArray(summary)) {
33551
+ const digest = summary;
33552
+ for (const key of ["failure_modes", "strengths", "caveats"]) {
33553
+ const items = digest[key];
33554
+ if (Array.isArray(items))
33555
+ lines.push(...items.filter((item) => typeof item === "string").slice(0, 2));
33556
+ }
33557
+ }
33558
+ if (Array.isArray(record3.recent_reviews)) {
33559
+ for (const value of record3.recent_reviews.slice(0, 5)) {
33560
+ if (!value || typeof value !== "object")
33561
+ continue;
33562
+ const review = value;
33563
+ if (typeof review.reason !== "string" || !review.reason)
33564
+ continue;
33565
+ const payment = review.payment_verified === true ? "payment verified" : "payment not verified";
33566
+ lines.push(`Reviewer report (${payment}, ${review.rating}/5): ${review.reason.slice(0, 600)}`);
33567
+ }
33568
+ }
33569
+ return lines.length ? lines.join(" ") : void 0;
33570
+ }
33482
33571
  function numberValue3(value) {
33483
33572
  if (typeof value === "number" && Number.isFinite(value)) {
33484
33573
  return value;
@@ -33497,6 +33586,9 @@ var init_crowdcode = __esm({
33497
33586
  constructor(connection) {
33498
33587
  this.connection = connection;
33499
33588
  }
33589
+ async manage(name, args) {
33590
+ return this.connection.call(name, args);
33591
+ }
33500
33592
  async getServiceScore(query) {
33501
33593
  const result = await this.connection.call("get_service_score", {
33502
33594
  ...query.apiEndpoint ? { api_endpoint: query.apiEndpoint } : {},
@@ -33513,14 +33605,64 @@ var init_crowdcode = __esm({
33513
33605
  const result = await this.connection.call("review_service", {
33514
33606
  rating: review.rating,
33515
33607
  reason: review.reason,
33516
- payment_reference: review.paymentReference,
33608
+ ...review.paymentReference !== void 0 ? { payment_reference: review.paymentReference } : {},
33609
+ ...review.reviewNonce ? { review_nonce: review.reviewNonce } : {},
33517
33610
  ...review.apiEndpoint ? { api_endpoint: review.apiEndpoint } : {},
33518
33611
  ...review.paymentProvider ? { payment_provider: review.paymentProvider } : {},
33519
33612
  ...review.paymentProof ? { payment_proof: review.paymentProof } : {},
33520
33613
  ...review.paymentTargetRef ? { payment_target_ref: review.paymentTargetRef } : {},
33521
33614
  ...review.taskContext ? { task_context: review.taskContext } : {}
33522
33615
  });
33523
- return { ok: result.ok, error: result.error, raw: result.data };
33616
+ const payload = result.data && typeof result.data === "object" ? result.data : {};
33617
+ const accepted = result.ok && payload.accepted === true;
33618
+ return { ok: accepted, error: accepted ? void 0 : result.error ?? String(payload.reason ?? "CrowdCode did not accept the review"), raw: result.data };
33619
+ }
33620
+ };
33621
+ }
33622
+ });
33623
+
33624
+ // ../../packages/economy/dist/crowdcode-preferences.js
33625
+ import { mkdir as mkdir8, readFile as readFile8, rename as rename2, writeFile as writeFile4 } from "node:fs/promises";
33626
+ import { dirname as dirname7, join as join9 } from "node:path";
33627
+ import { randomUUID as randomUUID4 } from "node:crypto";
33628
+ var CrowdCodePreferences;
33629
+ var init_crowdcode_preferences = __esm({
33630
+ "../../packages/economy/dist/crowdcode-preferences.js"() {
33631
+ "use strict";
33632
+ CrowdCodePreferences = class {
33633
+ session;
33634
+ constructor(session) {
33635
+ this.session = session;
33636
+ }
33637
+ path(scope) {
33638
+ return join9(scope === "session" ? this.session.sessionDir : this.session.workspaceRoot, "crowdcode-preferences.json");
33639
+ }
33640
+ async read(scope) {
33641
+ try {
33642
+ const value = JSON.parse(await readFile8(this.path(scope), "utf8"));
33643
+ return typeof value.enabled === "boolean" ? value.enabled : void 0;
33644
+ } catch (error53) {
33645
+ if (error53.code === "ENOENT")
33646
+ return void 0;
33647
+ throw error53;
33648
+ }
33649
+ }
33650
+ async status() {
33651
+ const default_enabled = await this.read("default") ?? true;
33652
+ const session_enabled = await this.read("session");
33653
+ return { enabled: session_enabled ?? default_enabled, default_enabled, scope: session_enabled === void 0 ? "default" : "session" };
33654
+ }
33655
+ async write(scope, enabled) {
33656
+ const path3 = this.path(scope), temporary = `${path3}.${randomUUID4()}.tmp`;
33657
+ await mkdir8(dirname7(path3), { recursive: true });
33658
+ await writeFile4(temporary, JSON.stringify({ enabled }) + "\n", { mode: 384 });
33659
+ await rename2(temporary, path3);
33660
+ }
33661
+ async set(enabled, scope) {
33662
+ await this.write(scope, enabled);
33663
+ if (scope === "default")
33664
+ await this.write("session");
33665
+ return this.status();
33524
33666
  }
33525
33667
  };
33526
33668
  }
@@ -33557,14 +33699,14 @@ var init_media = __esm({
33557
33699
  });
33558
33700
 
33559
33701
  // ../../packages/economy/dist/purchases.js
33560
- import { appendFile as appendFile3, mkdir as mkdir8, readFile as readFile8 } from "node:fs/promises";
33561
- import { dirname as dirname7, join as join9 } from "node:path";
33562
- import { randomUUID as randomUUID4 } from "node:crypto";
33702
+ import { appendFile as appendFile3, mkdir as mkdir9, readFile as readFile9 } from "node:fs/promises";
33703
+ import { dirname as dirname8, join as join10 } from "node:path";
33704
+ import { randomUUID as randomUUID5 } from "node:crypto";
33563
33705
  function purchasesPath(session) {
33564
- return join9(session.sessionDir, "purchases.jsonl");
33706
+ return join10(session.sessionDir, "purchases.jsonl");
33565
33707
  }
33566
33708
  function newPurchaseId() {
33567
- return `pur_${randomUUID4().slice(0, 12)}`;
33709
+ return `pur_${randomUUID5().slice(0, 12)}`;
33568
33710
  }
33569
33711
  async function appendPurchase(session, record3) {
33570
33712
  await appendPurchaseEvent(session, { type: "purchase", record: record3 });
@@ -33580,16 +33722,20 @@ async function recordReviewSubmitted(session, purchaseId, rating) {
33580
33722
  async function recordReviewFailed(session, purchaseId) {
33581
33723
  await appendPurchaseEvent(session, { type: "review_failed", purchase_id: purchaseId, attempted_at: (/* @__PURE__ */ new Date()).toISOString() });
33582
33724
  }
33725
+ async function skipPendingReviews(session) {
33726
+ for (const state of await pendingRequiredReviews(session))
33727
+ await appendPurchaseEvent(session, { type: "review_skipped", purchase_id: state.record.purchase_id });
33728
+ }
33583
33729
  async function appendPurchaseEvent(session, event) {
33584
33730
  const path3 = purchasesPath(session);
33585
- await mkdir8(dirname7(path3), { recursive: true });
33731
+ await mkdir9(dirname8(path3), { recursive: true });
33586
33732
  await appendFile3(path3, `${JSON.stringify(event)}
33587
33733
  `, "utf8");
33588
33734
  }
33589
33735
  async function listPurchases(session) {
33590
33736
  let text;
33591
33737
  try {
33592
- text = await readFile8(purchasesPath(session), "utf8");
33738
+ text = await readFile9(purchasesPath(session), "utf8");
33593
33739
  } catch (error53) {
33594
33740
  if (error53.code === "ENOENT") {
33595
33741
  return [];
@@ -33612,6 +33758,10 @@ async function listPurchases(session) {
33612
33758
  record: event.record,
33613
33759
  reviewStatus: event.record.review_required ? "pending" : "not_required"
33614
33760
  });
33761
+ } else if (event.type === "review_skipped") {
33762
+ const state = states.get(event.purchase_id);
33763
+ if (state)
33764
+ state.reviewStatus = "not_required";
33615
33765
  } else if (event.type === "review_failed") {
33616
33766
  const state = states.get(event.purchase_id);
33617
33767
  if (state)
@@ -33654,6 +33804,8 @@ var init_purchases = __esm({
33654
33804
  });
33655
33805
 
33656
33806
  // ../../packages/economy/dist/gateway.js
33807
+ import { readFile as readFile10, writeFile as writeFile5 } from "node:fs/promises";
33808
+ import { join as join11 } from "node:path";
33657
33809
  function inspectionKey(endpoint, method) {
33658
33810
  return `${method} ${endpoint}`;
33659
33811
  }
@@ -33714,11 +33866,17 @@ var GATEWAY_TOOL_NAMES, EconomyGateway, GATEWAY_TOOL_DEFINITIONS;
33714
33866
  var init_gateway = __esm({
33715
33867
  "../../packages/economy/dist/gateway.js"() {
33716
33868
  "use strict";
33869
+ init_crowdcode_preferences();
33717
33870
  init_media();
33718
33871
  init_dist2();
33719
33872
  init_approvals();
33720
33873
  init_purchases();
33721
33874
  GATEWAY_TOOL_NAMES = [
33875
+ "crowdcode_status",
33876
+ "set_crowdcode_enabled",
33877
+ "request_service",
33878
+ "list_my_reviews",
33879
+ "delete_my_review",
33722
33880
  "read_service",
33723
33881
  "get_wallet_status",
33724
33882
  "find_paid_service",
@@ -33729,10 +33887,36 @@ var init_gateway = __esm({
33729
33887
  ];
33730
33888
  EconomyGateway = class {
33731
33889
  options;
33732
- inspections = /* @__PURE__ */ new Map();
33890
+ /**
33891
+ * Inspections are keyed by endpoint+method and persisted under the session so
33892
+ * a run resumed on a fresh gateway instance (funds pause, worker restart) still
33893
+ * honours the inspect-before-call rule instead of failing its first call.
33894
+ */
33895
+ inspections;
33733
33896
  constructor(options) {
33734
33897
  this.options = options;
33735
33898
  }
33899
+ get inspectionsPath() {
33900
+ return join11(this.options.session.sessionDir, "inspections.json");
33901
+ }
33902
+ async loadInspections() {
33903
+ if (this.inspections)
33904
+ return this.inspections;
33905
+ const map3 = /* @__PURE__ */ new Map();
33906
+ try {
33907
+ const stored = JSON.parse(await readFile10(this.inspectionsPath, "utf8"));
33908
+ for (const [key, value] of Object.entries(stored))
33909
+ map3.set(key, value);
33910
+ } catch {
33911
+ }
33912
+ this.inspections = map3;
33913
+ return map3;
33914
+ }
33915
+ async rememberInspection(key, inspection) {
33916
+ const map3 = await this.loadInspections();
33917
+ map3.set(key, inspection);
33918
+ await writeFile5(this.inspectionsPath, JSON.stringify(Object.fromEntries(map3)), "utf8");
33919
+ }
33736
33920
  definitions() {
33737
33921
  return GATEWAY_TOOL_DEFINITIONS;
33738
33922
  }
@@ -33741,11 +33925,17 @@ var init_gateway = __esm({
33741
33925
  }
33742
33926
  /** True while a confirmed paid purchase still needs its required review. */
33743
33927
  async hasPendingRequiredReviews() {
33744
- return (await pendingRequiredReviews(this.options.session)).length > 0;
33928
+ return await this.crowdcodeEnabled() && (await pendingRequiredReviews(this.options.session)).length > 0;
33745
33929
  }
33746
33930
  async execute(name, args, operationId) {
33747
33931
  try {
33748
33932
  switch (name) {
33933
+ case "crowdcode_status":
33934
+ case "set_crowdcode_enabled":
33935
+ case "request_service":
33936
+ case "list_my_reviews":
33937
+ case "delete_my_review":
33938
+ return await this.manageCrowdCode(name, args);
33749
33939
  case "get_wallet_status":
33750
33940
  return await this.getWalletStatus();
33751
33941
  case "find_paid_service":
@@ -33769,6 +33959,38 @@ var init_gateway = __esm({
33769
33959
  return { ok: false, error: error53.message };
33770
33960
  }
33771
33961
  }
33962
+ async crowdcodeEnabled() {
33963
+ if (!this.options.hostedSpending && !this.options.crowdcode.manage)
33964
+ return true;
33965
+ const status = await this.manageCrowdCode("crowdcode_status", {});
33966
+ if (!status.ok)
33967
+ throw new Error(status.error ?? "CrowdCode preferences unavailable");
33968
+ return status.data?.enabled === true;
33969
+ }
33970
+ async manageCrowdCode(name, args) {
33971
+ if (name === "set_crowdcode_enabled") {
33972
+ if (typeof args.enabled !== "boolean" || args.scope !== void 0 && args.scope !== "session" && args.scope !== "default")
33973
+ return { ok: false, error: "Provide enabled (boolean) and scope (session or default)" };
33974
+ }
33975
+ if (this.options.hostedSpending && (name === "crowdcode_status" || name === "set_crowdcode_enabled")) {
33976
+ const preferences = new CrowdCodePreferences(this.options.session);
33977
+ const data = name === "crowdcode_status" ? await preferences.status() : await preferences.set(args.enabled, args.scope ?? "session");
33978
+ if (name === "set_crowdcode_enabled" && args.enabled === false)
33979
+ await skipPendingReviews(this.options.session);
33980
+ return { ok: true, data };
33981
+ }
33982
+ if (name === "request_service" && !await this.crowdcodeEnabled())
33983
+ return { ok: false, error: "CrowdCode is off. Turn it on to submit service requests." };
33984
+ if (!this.options.crowdcode.manage)
33985
+ return { ok: false, error: "CrowdCode management is unavailable" };
33986
+ const result = await this.options.crowdcode.manage(name, args);
33987
+ if (result.ok && name === "set_crowdcode_enabled" && args.enabled === false)
33988
+ await skipPendingReviews(this.options.session);
33989
+ return result;
33990
+ }
33991
+ async serviceEvidence(endpoint) {
33992
+ return await this.crowdcodeEnabled() ? this.options.crowdcode.getServiceScore({ apiEndpoint: endpoint }) : { ok: true, unproven: true, summary: "CrowdCode is off; reputation checks and submissions are disabled." };
33993
+ }
33772
33994
  async getWalletStatus() {
33773
33995
  const result = await this.options.agentcash.getBalance();
33774
33996
  if (!result.ok) {
@@ -33803,10 +34025,10 @@ var init_gateway = __esm({
33803
34025
  if (!schema.ok) {
33804
34026
  return { ok: false, error: schema.error };
33805
34027
  }
33806
- const evidence = await this.options.crowdcode.getServiceScore({ apiEndpoint: endpoint });
34028
+ const evidence = await this.serviceEvidence(endpoint);
33807
34029
  const rail = railFromSchema(schema.data);
33808
34030
  const priceCeilingCents = priceCeilingFromSchema(schema.data);
33809
- this.inspections.set(inspectionKey(endpoint, method), {
34031
+ await this.rememberInspection(inspectionKey(endpoint, method), {
33810
34032
  endpoint,
33811
34033
  method,
33812
34034
  rail,
@@ -33840,7 +34062,7 @@ var init_gateway = __esm({
33840
34062
  error: "external-service purchases are disabled (approval mode `off`). Local tools and LLM inference remain available; switch with /approval ask|auto."
33841
34063
  };
33842
34064
  }
33843
- const pending = await pendingRequiredReviews(session);
34065
+ const pending = await this.crowdcodeEnabled() ? await pendingRequiredReviews(session) : [];
33844
34066
  if (pending.length > 0) {
33845
34067
  return {
33846
34068
  ok: false,
@@ -33852,7 +34074,7 @@ var init_gateway = __esm({
33852
34074
  return { ok: false, error: "call_paid_service requires `url`" };
33853
34075
  }
33854
34076
  const method = (stringArg(args.method) ?? "POST").toUpperCase();
33855
- const inspection = this.inspections.get(inspectionKey(endpoint, method));
34077
+ const inspection = (await this.loadInspections()).get(inspectionKey(endpoint, method));
33856
34078
  if (!inspection) {
33857
34079
  return { ok: false, error: `inspect_paid_service must run for ${method} ${endpoint} before call_paid_service` };
33858
34080
  }
@@ -33879,7 +34101,7 @@ var init_gateway = __esm({
33879
34101
  if (quotedCostCents === void 0) {
33880
34102
  return { ok: false, error: "no price ceiling: pass `max_cost_cents` (the inspection did not report a price)" };
33881
34103
  }
33882
- const evidence = await this.options.crowdcode.getServiceScore({ apiEndpoint: endpoint });
34104
+ const evidence = await this.serviceEvidence(endpoint);
33883
34105
  if (!evidence.ok) {
33884
34106
  return {
33885
34107
  ok: false,
@@ -33938,7 +34160,7 @@ var init_gateway = __esm({
33938
34160
  artifact_path: artifact?.path,
33939
34161
  // Confirmed paid successes AND paid failures require reviews; free,
33940
34162
  // SIWX, and unknown outcomes create no paid receipt to review.
33941
- review_required: paid && supportedRail,
34163
+ review_required: paid && supportedRail && await this.crowdcodeEnabled(),
33942
34164
  evidence: result.payment,
33943
34165
  notes: result.ambiguous ? `${result.ambiguityReason ?? "ambiguous"}: payment state unknown; never auto-retried` : result.error
33944
34166
  };
@@ -33983,6 +34205,7 @@ var init_gateway = __esm({
33983
34205
  charged_cost_cents: record3.charged_cost_cents,
33984
34206
  artifact_path: artifact?.path,
33985
34207
  review_required: record3.review_required,
34208
+ review_available: true,
33986
34209
  data: result.data,
33987
34210
  ...result.ok ? {} : { error: result.error }
33988
34211
  },
@@ -34053,6 +34276,8 @@ var init_gateway = __esm({
34053
34276
  return void 0;
34054
34277
  }
34055
34278
  async reviewPaidService(args) {
34279
+ if (!await this.crowdcodeEnabled())
34280
+ return { ok: false, error: "CrowdCode is off; review submission is disabled." };
34056
34281
  const purchaseId = stringArg(args.purchase_id);
34057
34282
  const rating = intArg(args.rating);
34058
34283
  const reason = stringArg(args.reason);
@@ -34070,27 +34295,16 @@ var init_gateway = __esm({
34070
34295
  if (state.reviewStatus === "submitted") {
34071
34296
  return { ok: false, error: `purchase ${purchaseId} is already reviewed` };
34072
34297
  }
34073
- if (state.reviewStatus === "not_required") {
34074
- if (state.record.outcome === "paid_success" || state.record.outcome === "paid_failure") {
34075
- return {
34076
- ok: false,
34077
- error: `purchase ${purchaseId} was recorded as ${state.record.outcome} without a verifiable settlement reference; this legacy receipt cannot be submitted to CrowdCode automatically`
34078
- };
34079
- }
34080
- return { ok: false, error: `purchase ${purchaseId} has no paid receipt to review (outcome: ${state.record.outcome})` };
34081
- }
34082
34298
  const evidence = state.record.evidence;
34083
- if (!evidence?.reference) {
34084
- return { ok: false, error: `purchase ${purchaseId} has no settlement reference; it cannot be reviewed` };
34085
- }
34086
34299
  const result = await this.options.crowdcode.reviewService({
34087
34300
  rating,
34088
34301
  reason,
34089
- paymentReference: evidence.reference,
34302
+ paymentReference: evidence?.reference,
34303
+ reviewNonce: evidence?.reference ? void 0 : state.record.purchase_id,
34090
34304
  apiEndpoint: state.record.endpoint,
34091
- paymentProvider: state.record.rail === "mppx" ? "mppx" : "x402",
34092
- paymentProof: evidence.proof,
34093
- paymentTargetRef: evidence.payTo,
34305
+ paymentProvider: evidence?.reference ? state.record.rail === "mppx" ? "mppx" : "x402" : void 0,
34306
+ paymentProof: evidence?.proof,
34307
+ paymentTargetRef: evidence?.reference ? evidence.payTo : void 0,
34094
34308
  taskContext: stringArg(args.task_context)
34095
34309
  });
34096
34310
  if (!result.ok) {
@@ -34145,6 +34359,11 @@ var init_gateway = __esm({
34145
34359
  }
34146
34360
  };
34147
34361
  GATEWAY_TOOL_DEFINITIONS = [
34362
+ { name: "crowdcode_status", description: "Check whether CrowdCode is enabled for this session and by default.", parameters: { type: "object", properties: {}, additionalProperties: false } },
34363
+ { name: "set_crowdcode_enabled", description: "Handle 'CrowdCode on/off'. Disable reputation checks, automatic reviews and requests. Default scope is this session; scope default also sets the agent default for future sessions. Listing and deleting your reviews remain available while off. Does not change spending permissions.", parameters: { type: "object", properties: { enabled: { type: "boolean" }, scope: { type: "string", enum: ["session", "default"] } }, required: ["enabled"], additionalProperties: false } },
34364
+ { name: "request_service", description: "Before finishing a real task, record a concrete service worth paying for that would fix an observed failure, poor result, excessive cost or detour. State exact input, paid deliverable, acceptance criteria, actual obstacle and why paying is worthwhile. No purchase or spending authority is required. Skip generic Python/runtime wishes, web search that worked well, and gaps without a sellable remedy. Submit distinct gaps once; submit nothing if everything worked well and cheaply. Exclude private data and secrets.", parameters: { type: "object", properties: { service_description: { type: "string", maxLength: 8e3 }, task_context: { type: "string", maxLength: 4e3 } }, required: ["service_description"], additionalProperties: false } },
34365
+ { name: "list_my_reviews", description: "List this agent's own submitted reviews with IDs for selective deletion; works while CrowdCode is off. Paginate with next_before_id.", parameters: { type: "object", properties: { before_id: { type: "integer", minimum: 0 }, limit: { type: "integer", minimum: 1, maximum: 100 } }, additionalProperties: false } },
34366
+ { name: "delete_my_review", description: "Delete one of this agent's reviews when the user asks, using its ID from list_my_reviews. Works while CrowdCode is off. Never delete unrelated reviews.", parameters: { type: "object", properties: { review_id: { type: "integer", minimum: 1 } }, required: ["review_id"], additionalProperties: false } },
34148
34367
  {
34149
34368
  name: "read_service",
34150
34369
  description: "Read a service URL without payment, authenticating with the wallet when required (SIWX). Use this to poll a paid generation job until complete; never resubmit a pending job. Download returned media URLs with run_shell.",
@@ -34199,7 +34418,7 @@ var init_gateway = __esm({
34199
34418
  },
34200
34419
  {
34201
34420
  name: "review_paid_service",
34202
- description: "Submit the required CrowdCode review for one stored purchase using its receipt evidence. Required after every confirmed paid call \u2014 success or failure; a broken paid call IS the review (rate 1-2 with the failure as the reason).",
34421
+ description: "Review a stored service interaction, paid or unpaid, using the same CrowdCode review flow. Payment evidence is attached when available; otherwise payment is marked unverified. Required after confirmed paid calls, optional for unpaid outcomes. Describe observed results and distinguish provider faults from caller errors, insufficient funds, and uncertain failures.",
34203
34422
  parameters: {
34204
34423
  type: "object",
34205
34424
  properties: {
@@ -34433,7 +34652,7 @@ async function sharedEconomyRuntime(log) {
34433
34652
  agentcash: new McpAgentCashAdapter(agentcashConnection),
34434
34653
  crowdcode: new McpCrowdCodeAdapter(crowdcodeConnection),
34435
34654
  instructions: () => [agentcashConnection, crowdcodeConnection].map((connection) => connection.instructions()).filter((text) => Boolean(text)).map((text, index2) => `Instructions from the ${index2 === 0 ? "agentcash" : "crowdcode"} vendor:
34436
- ${text.slice(0, 2400)}`),
34655
+ ${text.slice(0, 16e3)}`),
34437
34656
  close: async () => {
34438
34657
  await Promise.all([agentcashConnection.close(), crowdcodeConnection.close()]);
34439
34658
  shared = void 0;
@@ -34499,7 +34718,7 @@ var init_dist4 = __esm({
34499
34718
 
34500
34719
  // ../../packages/agent-runtime/dist/context.js
34501
34720
  import { createHash as createHash3 } from "node:crypto";
34502
- import { relative as relative3, join as join10 } from "node:path";
34721
+ import { relative as relative3, join as join12 } from "node:path";
34503
34722
  async function completeWithContext(session, messages, options) {
34504
34723
  for (; ; ) {
34505
34724
  options.signal?.throwIfAborted();
@@ -34557,13 +34776,13 @@ async function compactContext(session, messages, options) {
34557
34776
  return { tokensBefore, tokensAfter: tokensBefore };
34558
34777
  const raw = messages.map((message) => JSON.stringify(message)).join("\n") + "\n";
34559
34778
  const digest = createHash3("sha256").update(raw).digest("hex");
34560
- const dir = await containedPath(session.sessionDir, join10("context", digest));
34561
- const path3 = join10(dir, "transcript.jsonl");
34779
+ const dir = await containedPath(session.sessionDir, join12("context", digest));
34780
+ const path3 = join12(dir, "transcript.jsonl");
34562
34781
  await atomicWrite(path3, raw);
34563
34782
  const archivePath = relative3(session.workspaceRoot, path3).split("\\").join("/");
34564
34783
  const ref = (index2) => `${relative3(session.workspaceRoot, dir).split("\\").join("/")}/message-${index2 + 1}.txt`;
34565
34784
  const externalize = async (message, index2) => {
34566
- await atomicWrite(join10(dir, `message-${index2 + 1}.txt`), messages[index2].content);
34785
+ await atomicWrite(join12(dir, `message-${index2 + 1}.txt`), messages[index2].content);
34567
34786
  return `[Full ${message.role} message saved verbatim to ${ref(index2)}. Use rg/grep and sed/head/tail to read relevant portions before proceeding; do not load the entire file.]`;
34568
34787
  };
34569
34788
  const list = messages.map((m, index2) => ({ message: structuredClone(m), index: index2 })).filter(({ message }) => !message.contextArchive);
@@ -34625,11 +34844,11 @@ var init_context2 = __esm({
34625
34844
  });
34626
34845
 
34627
34846
  // ../../packages/agent-runtime/dist/knowledge.js
34628
- import { access, cp, mkdir as mkdir9, readFile as readFile9, writeFile as writeFile4 } from "node:fs/promises";
34629
- import { dirname as dirname8, join as join11, resolve as resolve4 } from "node:path";
34847
+ import { access, cp, mkdir as mkdir10, readFile as readFile11, writeFile as writeFile6 } from "node:fs/promises";
34848
+ import { dirname as dirname9, join as join13, resolve as resolve4 } from "node:path";
34630
34849
  import { fileURLToPath } from "node:url";
34631
34850
  function bundledKnowledgeDir() {
34632
- return resolve4(dirname8(fileURLToPath(import.meta.url)), "..", "knowledge");
34851
+ return resolve4(dirname9(fileURLToPath(import.meta.url)), "..", "knowledge");
34633
34852
  }
34634
34853
  function knowledgeDisabledByEnv() {
34635
34854
  const value = process.env.OPENCROWD_KNOWLEDGE_DIR?.trim().toLowerCase();
@@ -34645,7 +34864,7 @@ async function resolveKnowledgeDir(options = {}) {
34645
34864
  }
34646
34865
  const bundled = bundledKnowledgeDir();
34647
34866
  try {
34648
- await access(join11(bundled, "L0.md"));
34867
+ await access(join13(bundled, "L0.md"));
34649
34868
  return bundled;
34650
34869
  } catch {
34651
34870
  return void 0;
@@ -34658,20 +34877,20 @@ async function loadKnowledgeTree(session, options = {}) {
34658
34877
  }
34659
34878
  let l0;
34660
34879
  try {
34661
- l0 = (await readFile9(join11(dir, "L0.md"), "utf8")).trim();
34880
+ l0 = (await readFile11(join13(dir, "L0.md"), "utf8")).trim();
34662
34881
  } catch {
34663
34882
  return void 0;
34664
34883
  }
34665
34884
  const version6 = await readVersion(dir, l0);
34666
- const target = join11(session.artifactsDir, "knowledge");
34885
+ const target = join13(session.artifactsDir, "knowledge");
34667
34886
  if (await currentVersion(target) !== version6) {
34668
- await mkdir9(session.artifactsDir, { recursive: true });
34887
+ await mkdir10(session.artifactsDir, { recursive: true });
34669
34888
  await cp(dir, target, {
34670
34889
  recursive: true,
34671
34890
  force: true,
34672
34891
  filter: (source) => !source.endsWith("proposal.raw.txt")
34673
34892
  });
34674
- await writeFile4(join11(target, VERSION_FILE), `${version6}
34893
+ await writeFile6(join13(target, VERSION_FILE), `${version6}
34675
34894
  `, "utf8");
34676
34895
  }
34677
34896
  if (session.knowledge?.version !== version6 || session.knowledge?.source !== dir) {
@@ -34689,7 +34908,7 @@ function renderCapabilityIndex(l0) {
34689
34908
  }
34690
34909
  async function readVersion(dir, l0) {
34691
34910
  try {
34692
- const meta4 = JSON.parse(await readFile9(join11(dir, "meta.json"), "utf8"));
34911
+ const meta4 = JSON.parse(await readFile11(join13(dir, "meta.json"), "utf8"));
34693
34912
  if (typeof meta4.content_hash === "string" && meta4.content_hash) {
34694
34913
  return meta4.id ? `${meta4.id}@${meta4.content_hash}` : meta4.content_hash;
34695
34914
  }
@@ -34700,7 +34919,7 @@ async function readVersion(dir, l0) {
34700
34919
  }
34701
34920
  async function currentVersion(target) {
34702
34921
  try {
34703
- return (await readFile9(join11(target, VERSION_FILE), "utf8")).trim();
34922
+ return (await readFile11(join13(target, VERSION_FILE), "utf8")).trim();
34704
34923
  } catch {
34705
34924
  return void 0;
34706
34925
  }
@@ -35326,7 +35545,7 @@ function alphabet(letters) {
35326
35545
  };
35327
35546
  }
35328
35547
  // @__NO_SIDE_EFFECTS__
35329
- function join12(separator = "") {
35548
+ function join14(separator = "") {
35330
35549
  astr("join", separator);
35331
35550
  return {
35332
35551
  encode: (from16) => {
@@ -35406,7 +35625,7 @@ function radix(num2) {
35406
35625
  var genBase58, base58;
35407
35626
  var init_esm = __esm({
35408
35627
  "../../node_modules/@scure/base/lib/esm/index.js"() {
35409
- genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join12(""));
35628
+ genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join14(""));
35410
35629
  base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
35411
35630
  }
35412
35631
  });
@@ -79823,6 +80042,8 @@ var init_llm_runtime = __esm({
79823
80042
 
79824
80043
  // ../../packages/agent-runtime/dist/economy-tools.js
79825
80044
  function economyTools(economy, options = {}) {
80045
+ let reflected = false;
80046
+ const supportsReflection = economy.definitions().some((tool) => tool.name === "request_service");
79826
80047
  return {
79827
80048
  definitions: economy.definitions().filter((tool) => !options.hidden?.has(tool.name)),
79828
80049
  execute: async (name, args, operationId) => {
@@ -79830,7 +80051,17 @@ function economyTools(economy, options = {}) {
79830
80051
  await economy.execute("inspect_paid_service", { url: args.url, method: args.method, sample_body: args.body });
79831
80052
  return economy.execute(name, args, operationId);
79832
80053
  },
79833
- completionGate: async () => !await economy.hasPendingRequiredReviews() ? void 0 : "a paid purchase still needs its required review; submit it with review_paid_service"
80054
+ completionGate: async () => {
80055
+ const pending = await economy.hasPendingRequiredReviews();
80056
+ const review = pending ? "A paid purchase still needs its required review; submit it with review_paid_service." : "";
80057
+ if (reflected || !supportsReflection)
80058
+ return review || void 0;
80059
+ reflected = true;
80060
+ const status = await economy.execute("crowdcode_status", {});
80061
+ if (!status.ok || !status.data?.enabled)
80062
+ return review || void 0;
80063
+ return [review, "Before your final answer, reflect once: What concrete services would have been worth paying for to solve this task? For each observed failure, poor result, excessive cost or avoidable detour with a reusable paid remedy, call request_service. Specify exact inputs, the paid deliverable, acceptance criteria, the actual use case and why paying would help. A prior purchase or spending permission is not required. Do not invent budgets. Skip generic local computation, ordinary agent mistakes without a sellable remedy, and services such as web search that already worked well. If everything worked well and cheaply, submit nothing. Then finish the user's task."].filter(Boolean).join(" ");
80064
+ }
79834
80065
  };
79835
80066
  }
79836
80067
  var init_economy_tools = __esm({
@@ -79841,9 +80072,9 @@ var init_economy_tools = __esm({
79841
80072
  });
79842
80073
 
79843
80074
  // ../../packages/agent-runtime/dist/runtime.js
79844
- import { readFile as readFile10, rm as rm2 } from "node:fs/promises";
79845
- import { join as join17 } from "node:path";
79846
- import { randomUUID as randomUUID5 } from "node:crypto";
80075
+ import { readFile as readFile12, rm as rm2 } from "node:fs/promises";
80076
+ import { join as join19 } from "node:path";
80077
+ import { randomUUID as randomUUID6 } from "node:crypto";
79847
80078
  function createOpenCrowdRuntime(options) {
79848
80079
  const storage = options.storage ?? localRuntimeStorage;
79849
80080
  async function prepare(session, runOptions) {
@@ -79870,10 +80101,10 @@ function createOpenCrowdRuntime(options) {
79870
80101
  };
79871
80102
  }
79872
80103
  async function execute2(session, task, runOptions = {}) {
79873
- const path3 = join17(session.sessionDir, "query-checkpoint.json");
80104
+ const path3 = join19(session.sessionDir, "query-checkpoint.json");
79874
80105
  let persisted;
79875
80106
  try {
79876
- persisted = JSON.parse(await readFile10(path3, "utf8"));
80107
+ persisted = JSON.parse(await readFile12(path3, "utf8"));
79877
80108
  } catch (error53) {
79878
80109
  if (error53.code !== "ENOENT")
79879
80110
  throw error53;
@@ -79881,7 +80112,7 @@ function createOpenCrowdRuntime(options) {
79881
80112
  const resuming = task === "" && !!persisted;
79882
80113
  if (persisted && !resuming)
79883
80114
  throw new Error("A query is unfinished. Resume it or decline its pending approval before starting another query.");
79884
- const saved = resuming ? persisted : { id: runOptions.runId ?? randomUUID5(), task };
80115
+ const saved = resuming ? persisted : { id: runOptions.runId ?? randomUUID6(), task };
79885
80116
  await beginQuery(session, saved.id);
79886
80117
  const checkpoint = async (value) => {
79887
80118
  saved.checkpoint = value;
@@ -80113,8 +80344,8 @@ var init_hosted_provider = __esm({
80113
80344
  });
80114
80345
 
80115
80346
  // ../../packages/agent-runtime/dist/hosted-economy.js
80116
- import { randomUUID as randomUUID6, createHash as createHash4 } from "node:crypto";
80117
- import { join as join18 } from "node:path";
80347
+ import { randomUUID as randomUUID7, createHash as createHash4 } from "node:crypto";
80348
+ import { join as join20 } from "node:path";
80118
80349
  function createHostedEconomy(options) {
80119
80350
  const fetcher = options.fetcher ?? fetch;
80120
80351
  const socket = { socketPath: options.socketPath, runId: options.runId, sessionId: options.sessionId };
@@ -80127,7 +80358,7 @@ function createHostedEconomy(options) {
80127
80358
  hostedSpending: true,
80128
80359
  minServiceScore: 2,
80129
80360
  // Hosted rules live with the agent's session, never in a user config dir.
80130
- approvalRulesPath: join18(options.session.sessionDir, "approval-rules.json")
80361
+ approvalRulesPath: join20(options.session.sessionDir, "approval-rules.json")
80131
80362
  });
80132
80363
  }
80133
80364
  function hostedDynamicTools(economy) {
@@ -80156,20 +80387,6 @@ function parseListedService(raw) {
80156
80387
  num_reviews: numberValue6(row.num_reviews ?? service.num_reviews)
80157
80388
  };
80158
80389
  }
80159
- function summarizeEvidence(body) {
80160
- const summary = objectValue4(body.summary);
80161
- const lines = [...stringList(summary?.strengths), ...stringList(summary?.caveats)];
80162
- if (lines.length) {
80163
- return lines.slice(0, 4).join(" ");
80164
- }
80165
- return stringValue5(body.summary);
80166
- }
80167
- function stringList(value) {
80168
- if (typeof value === "string") {
80169
- return value ? [value] : [];
80170
- }
80171
- return Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.length > 0) : [];
80172
- }
80173
80390
  function endpointKey(url3) {
80174
80391
  try {
80175
80392
  const parsed = new URL(url3);
@@ -80331,7 +80548,7 @@ var init_hosted_economy = __esm({
80331
80548
  const method = request2.method.toUpperCase();
80332
80549
  const body = request2.body === void 0 ? void 0 : typeof request2.body === "string" ? request2.body : JSON.stringify(request2.body);
80333
80550
  const hash5 = request2.operationId ? createHash4("sha256").update(`${this.socket.runId}:${request2.operationId}`).digest("hex") : void 0;
80334
- const purchaseId = hash5 ? `${hash5.slice(0, 8)}-${hash5.slice(8, 12)}-4${hash5.slice(13, 16)}-8${hash5.slice(17, 20)}-${hash5.slice(20, 32)}` : randomUUID6();
80551
+ const purchaseId = hash5 ? `${hash5.slice(0, 8)}-${hash5.slice(8, 12)}-4${hash5.slice(13, 16)}-8${hash5.slice(17, 20)}-${hash5.slice(20, 32)}` : randomUUID7();
80335
80552
  let reply;
80336
80553
  try {
80337
80554
  reply = await postHostedTool(this.socket, "economy.pay", {
@@ -80418,6 +80635,9 @@ var init_hosted_economy = __esm({
80418
80635
  HostedCrowdCodeAdapter = class {
80419
80636
  directory;
80420
80637
  socket;
80638
+ async manage(name, args) {
80639
+ return postHostedTool(this.socket, "economy.crowdcode", { name, ...args });
80640
+ }
80421
80641
  constructor(directory, socket) {
80422
80642
  this.directory = directory;
80423
80643
  this.socket = socket;
@@ -80461,9 +80681,10 @@ var init_hosted_economy = __esm({
80461
80681
  try {
80462
80682
  const reply = await postHostedTool(this.socket, "economy.review", {
80463
80683
  api_endpoint: review.apiEndpoint,
80464
- payment_provider: "x402",
80684
+ payment_provider: review.paymentProvider,
80465
80685
  payment_target_ref: review.paymentTargetRef,
80466
80686
  payment_reference: review.paymentReference,
80687
+ review_nonce: review.reviewNonce,
80467
80688
  rating: review.rating,
80468
80689
  reason: review.reason,
80469
80690
  task_context: review.taskContext
@@ -80478,9 +80699,9 @@ var init_hosted_economy = __esm({
80478
80699
  });
80479
80700
 
80480
80701
  // ../../packages/agent-runtime/dist/worker.js
80481
- import { readFile as readFile11, mkdir as mkdir10 } from "node:fs/promises";
80482
- import { join as join19 } from "node:path";
80483
- import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
80702
+ import { readFile as readFile13, mkdir as mkdir11 } from "node:fs/promises";
80703
+ import { join as join21 } from "node:path";
80704
+ import { createHash as createHash5, randomUUID as randomUUID8 } from "node:crypto";
80484
80705
  function isWaiting(outcome) {
80485
80706
  return ["waiting_for_approval", "waiting_for_funds", "waiting_for_delegation", "payment_unknown"].includes(outcome);
80486
80707
  }
@@ -80507,6 +80728,7 @@ var RuntimePause, MachineWorker;
80507
80728
  var init_worker = __esm({
80508
80729
  "../../packages/agent-runtime/dist/worker.js"() {
80509
80730
  "use strict";
80731
+ init_dist();
80510
80732
  init_dist2();
80511
80733
  init_dist2();
80512
80734
  init_dist();
@@ -80535,13 +80757,13 @@ var init_worker = __esm({
80535
80757
  constructor(options) {
80536
80758
  this.options = options;
80537
80759
  this.paths = resolveAgentPaths({ agentHome: options.agentHome });
80538
- this.statePath = join19(this.paths.metadata, "worker.json");
80760
+ this.statePath = join21(this.paths.metadata, "worker.json");
80539
80761
  }
80540
80762
  async initialize() {
80541
80763
  await containedPath(this.paths.home, "metadata/worker.json");
80542
- await mkdir10(this.paths.metadata, { recursive: true });
80764
+ await mkdir11(this.paths.metadata, { recursive: true });
80543
80765
  try {
80544
- this.state = JSON.parse(await readFile11(this.statePath, "utf8"));
80766
+ this.state = JSON.parse(await readFile13(this.statePath, "utf8"));
80545
80767
  if (this.state.version !== 1 || !Number.isSafeInteger(this.state.seq) || !this.state.commands || !this.state.runs) {
80546
80768
  throw new Error("worker checkpoint version or shape is invalid");
80547
80769
  }
@@ -80568,7 +80790,7 @@ var init_worker = __esm({
80568
80790
  await this.mutate(() => {
80569
80791
  line = encodeEvent({
80570
80792
  protocolVersion: 1,
80571
- id: this.options.id?.() ?? randomUUID7(),
80793
+ id: this.options.id?.() ?? randomUUID8(),
80572
80794
  seq: ++this.state.seq,
80573
80795
  emittedAt: (this.options.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
80574
80796
  type,
@@ -80677,9 +80899,9 @@ var init_worker = __esm({
80677
80899
  } else if (!run) {
80678
80900
  run = {
80679
80901
  start: command,
80680
- sessionId: command.payload.session.sessionId ?? randomUUID7(),
80902
+ sessionId: command.payload.session.sessionId ?? randomUUID8(),
80681
80903
  commandId: command.id,
80682
- checkpointId: randomUUID7(),
80904
+ checkpointId: randomUUID8(),
80683
80905
  tools: /* @__PURE__ */ Object.create(null)
80684
80906
  };
80685
80907
  }
@@ -80728,7 +80950,7 @@ var init_worker = __esm({
80728
80950
  const dynamicTools = economy ? hostedDynamicTools(economy) : void 0;
80729
80951
  const record3 = async (name, args, invoke) => {
80730
80952
  const call2 = run.checkpoint?.response?.toolCalls.find((c) => c.name === name && !run.checkpoint?.completedTools[c.id]);
80731
- const id = `${run.checkpoint?.turn ?? 0}:${call2?.id ?? randomUUID7()}`;
80953
+ const id = `${run.checkpoint?.turn ?? 0}:${call2?.id ?? randomUUID8()}`;
80732
80954
  const digest = createHash5("sha256").update(JSON.stringify({ name, args })).digest("hex");
80733
80955
  const saved = run.tools[id];
80734
80956
  if (saved && saved.digest !== digest)
@@ -80742,7 +80964,8 @@ var init_worker = __esm({
80742
80964
  await this.mutate(() => {
80743
80965
  run.tools[id] = { digest };
80744
80966
  });
80745
- await this.emit("tool.started", { toolCallId: id, toolName: name, input: summarizeToolInput(name, args) }, runId, run.commandId);
80967
+ await this.emit("tool.started", { toolCallId: id, toolName: name, input: summarizeToolInput(name, args), details: captureDetail({ input: args }), turn: run.checkpoint?.turn ?? 0 }, runId, run.commandId);
80968
+ const started = Date.now();
80746
80969
  let output3;
80747
80970
  try {
80748
80971
  if (saved?.approvalPending && name === "call_paid_service" && economy)
@@ -80753,6 +80976,15 @@ var init_worker = __esm({
80753
80976
  await this.mutate(() => {
80754
80977
  run.tools[id].approvalPending = true;
80755
80978
  });
80979
+ await this.emit("tool.finished", {
80980
+ toolCallId: id,
80981
+ toolName: name,
80982
+ status: error53 instanceof RuntimePause ? "blocked" : signal.aborted ? "cancelled" : "error",
80983
+ durationMs: Date.now() - started,
80984
+ turn: run.checkpoint?.turn ?? 0,
80985
+ error: scrubText(error53 instanceof Error ? error53.message : String(error53)),
80986
+ details: captureDetail({ error: error53 instanceof Error ? { name: error53.name, message: error53.message, stack: error53.stack } : String(error53) })
80987
+ }, runId, run.commandId);
80756
80988
  throw error53;
80757
80989
  }
80758
80990
  await this.mutate(() => {
@@ -80762,7 +80994,10 @@ var init_worker = __esm({
80762
80994
  toolCallId: id,
80763
80995
  toolName: name,
80764
80996
  status: output3.ok ? "ok" : "error",
80765
- error: output3.error
80997
+ error: output3.error ? scrubText(output3.error) : void 0,
80998
+ durationMs: Date.now() - started,
80999
+ turn: run.checkpoint?.turn ?? 0,
81000
+ details: captureDetail({ output: output3 })
80766
81001
  }, runId, run.commandId);
80767
81002
  if (name === "save_file" && output3.ok)
80768
81003
  await this.emit("artifact.created", {
@@ -80772,6 +81007,42 @@ var init_worker = __esm({
80772
81007
  }, runId, run.commandId);
80773
81008
  return output3;
80774
81009
  };
81010
+ const baseProvider = this.options.provider(run.start, session, dynamicTools?.definitions ?? []);
81011
+ const provider = {
81012
+ complete: async (messages, context) => {
81013
+ const callId = randomUUID8(), started = Date.now(), turn = run.checkpoint?.turn ?? 0;
81014
+ await this.emit("model.started", {
81015
+ callId,
81016
+ model: run.start.payload.modelPolicy.model ?? "demo",
81017
+ turn,
81018
+ details: captureDetail({ input: messages })
81019
+ }, runId, run.commandId);
81020
+ try {
81021
+ const result2 = await baseProvider.complete(messages, context);
81022
+ await this.emit("model.finished", {
81023
+ callId,
81024
+ model: run.start.payload.modelPolicy.model ?? "demo",
81025
+ turn,
81026
+ status: "ok",
81027
+ durationMs: Date.now() - started,
81028
+ usage: result2.usage,
81029
+ details: captureDetail({ output: result2 })
81030
+ }, runId, run.commandId);
81031
+ return result2;
81032
+ } catch (error53) {
81033
+ await this.emit("model.finished", {
81034
+ callId,
81035
+ model: run.start.payload.modelPolicy.model ?? "demo",
81036
+ turn,
81037
+ status: error53 instanceof RuntimePause ? "blocked" : signal.aborted ? "cancelled" : "error",
81038
+ durationMs: Date.now() - started,
81039
+ error: scrubText(error53 instanceof Error ? error53.message : String(error53)),
81040
+ details: captureDetail({ error: error53 instanceof Error ? { name: error53.name, message: error53.message, stack: error53.stack } : String(error53) })
81041
+ }, runId, run.commandId);
81042
+ throw error53;
81043
+ }
81044
+ }
81045
+ };
80775
81046
  const acknowledgedMessages = /* @__PURE__ */ new Set();
80776
81047
  const result = await runAgentTaskDetailed(session, run.start.payload.prompt, {
80777
81048
  inbox: {
@@ -80794,7 +81065,7 @@ var init_worker = __esm({
80794
81065
  maxTurns: run.start.payload.maxTurns,
80795
81066
  contextWindowTokens: run.start.payload.modelPolicy.contextWindowTokens,
80796
81067
  maxOutputTokens: run.start.payload.modelPolicy.maxOutputTokens,
80797
- provider: this.options.provider(run.start, session, dynamicTools?.definitions ?? []),
81068
+ provider,
80798
81069
  history: run.checkpoint ? void 0 : await this.history(session),
80799
81070
  ...dynamicTools ? {
80800
81071
  dynamicTools: { definitions: dynamicTools.definitions, execute: (name, args) => record3(name, args, () => dynamicTools.execute(name, args, `${run.checkpoint?.turn ?? 0}:${run.checkpoint?.response?.toolCalls.find((c) => c.name === name && !run.checkpoint?.completedTools[c.id])?.id}`)) },
@@ -80804,14 +81075,14 @@ var init_worker = __esm({
80804
81075
  onCheckpoint: async (checkpoint) => {
80805
81076
  await this.mutate(() => {
80806
81077
  run.checkpoint = checkpoint;
80807
- run.checkpointId = randomUUID7();
81078
+ run.checkpointId = randomUUID8();
80808
81079
  });
80809
- await atomicWrite(join19(session.sessionDir, "messages.jsonl"), checkpoint.messages.filter((m) => m.role !== "system").map((message) => JSON.stringify({ type: "message", timestamp: (/* @__PURE__ */ new Date()).toISOString(), message }) + "\n").join(""));
81080
+ await atomicWrite(join21(session.sessionDir, "messages.jsonl"), checkpoint.messages.filter((m) => m.role !== "system").map((message) => JSON.stringify({ type: "message", timestamp: (/* @__PURE__ */ new Date()).toISOString(), message }) + "\n").join(""));
80810
81081
  },
80811
81082
  onMessage: async (message) => {
80812
81083
  if (message.role === "assistant" && message.content)
80813
81084
  await this.emit("assistant.message", {
80814
- messageId: randomUUID7(),
81085
+ messageId: randomUUID8(),
80815
81086
  content: message.content
80816
81087
  }, runId, run.commandId);
80817
81088
  },
@@ -80819,6 +81090,13 @@ var init_worker = __esm({
80819
81090
  });
80820
81091
  await this.finish(runId, run, result.outcome === "stopped" ? "user_stopped" : result.outcome, String(result.summary.final_message ?? ""));
80821
81092
  } catch (error53) {
81093
+ if (!(error53 instanceof RuntimePause) && !signal.aborted)
81094
+ await this.emit("runtime.error", {
81095
+ code: "run_exception",
81096
+ message: scrubText(error53 instanceof Error ? error53.message : String(error53)),
81097
+ fatal: false,
81098
+ details: captureDetail({ error: error53 instanceof Error ? { name: error53.name, message: error53.message, stack: error53.stack } : String(error53) })
81099
+ }, runId, run.commandId);
80822
81100
  if (signal.aborted)
80823
81101
  await this.finish(runId, run, "cancelled", "Run cancelled");
80824
81102
  else if (error53 instanceof RuntimePause) {
@@ -80843,7 +81121,7 @@ var init_worker = __esm({
80843
81121
  }
80844
81122
  async history(session) {
80845
81123
  try {
80846
- return (await readFile11(join19(session.sessionDir, "messages.jsonl"), "utf8")).split("\n").filter(Boolean).map((line) => JSON.parse(line).message).filter(Boolean);
81124
+ return (await readFile13(join21(session.sessionDir, "messages.jsonl"), "utf8")).split("\n").filter(Boolean).map((line) => JSON.parse(line).message).filter(Boolean);
80847
81125
  } catch (error53) {
80848
81126
  if (error53.code === "ENOENT")
80849
81127
  return [];
@@ -80854,7 +81132,7 @@ var init_worker = __esm({
80854
81132
  await this.mutate(() => {
80855
81133
  run.outcome = outcome;
80856
81134
  run.summary = summary;
80857
- run.checkpointId = randomUUID7();
81135
+ run.checkpointId = randomUUID8();
80858
81136
  if (!isWaiting(outcome) && this.state.activeRunId === runId)
80859
81137
  this.state.activeRunId = void 0;
80860
81138
  });
@@ -80881,7 +81159,7 @@ var init_worker = __esm({
80881
81159
  });
80882
81160
 
80883
81161
  // ../../packages/agent-runtime/dist/inbox.js
80884
- import { readFile as readFile12 } from "node:fs/promises";
81162
+ import { readFile as readFile14 } from "node:fs/promises";
80885
81163
  var FileSteeringInbox;
80886
81164
  var init_inbox = __esm({
80887
81165
  "../../packages/agent-runtime/dist/inbox.js"() {
@@ -80895,7 +81173,7 @@ var init_inbox = __esm({
80895
81173
  }
80896
81174
  async read() {
80897
81175
  try {
80898
- return JSON.parse(await readFile12(this.path, "utf8"));
81176
+ return JSON.parse(await readFile14(this.path, "utf8"));
80899
81177
  } catch (e6) {
80900
81178
  if (e6.code === "ENOENT")
80901
81179
  return [];
@@ -80923,8 +81201,8 @@ var init_inbox = __esm({
80923
81201
 
80924
81202
  // ../../packages/agent-runtime/dist/index.js
80925
81203
  import { createHash as createHash6 } from "node:crypto";
80926
- import { appendFile as appendFile4, mkdir as mkdir11, readFile as readFile13 } from "node:fs/promises";
80927
- import { join as join20 } from "node:path";
81204
+ import { appendFile as appendFile4, mkdir as mkdir12, readFile as readFile15 } from "node:fs/promises";
81205
+ import { join as join22 } from "node:path";
80928
81206
  function lastUserMessageIndex(messages) {
80929
81207
  for (let index2 = messages.length - 1; index2 >= 0; index2 -= 1) {
80930
81208
  if (messages[index2].role === "user") {
@@ -81115,7 +81393,7 @@ async function runAgentTaskDetailed(session, task, options = {}) {
81115
81393
  "Before repeatedly fighting the local environment, decide whether the task needs external capability such as hosting, persistent infrastructure, remote compute, specialized APIs, live data, or access the user's device does not have."
81116
81394
  ];
81117
81395
  if (options.dynamicTools) {
81118
- systemPromptParts.push("When the local computer is not the right environment, or after one clear local capability failure, buy external capability: find_paid_service to discover, inspect_paid_service to see the exact schema/price/reputation, call_paid_service to execute through the enforced purchase lifecycle, and review_paid_service for the required review after every confirmed paid call (success or failure).", ...options.hosted ? ["Discover services through AgentCash search and provider catalogs. You can use new services without prior CrowdCode reviews. Only x402 USDC on Base is payable, within the user's configured limits; over-limit quotes request approval. Use read_service for authenticated job polling and never resubmit a pending generation job."] : [], capabilityIndex ?? DEFAULT_CAPABILITY_INDEX, "When a task needs current web facts, search results, or unfamiliar page content, make one paid web search your FIRST move \u2014 do not serially guess URLs with curl; one paid search replaces minutes of blind fetching and costs less than the LLM turns it saves.", "Approval, budget, reputation, and payment rails are enforced in code \u2014 you cannot bypass them, so state costs plainly and never invent payment details.", "Each tool result includes the budget before and after that tool call. Never ask for wallet private keys or secrets.", ...options.promptSections ?? []);
81396
+ systemPromptParts.push("When the local computer is not the right environment, or after one clear local capability failure, buy external capability: find_paid_service to discover, inspect_paid_service to see the exact schema/price/reputation, call_paid_service to execute through the enforced purchase lifecycle, and review_paid_service for the required review after every confirmed paid call (success or failure). The same review tool accepts unpaid experiences; review relevant free results or failed attempts without inventing payment evidence. Distinguish provider faults from local errors and uncertain failures.", ...options.hosted ? ["Discover services through AgentCash search and provider catalogs. You can use new services without prior CrowdCode reviews. Only x402 USDC on Base is payable, within the user's configured limits; over-limit quotes request approval. Use read_service for authenticated job polling and never resubmit a pending generation job."] : [], capabilityIndex ?? DEFAULT_CAPABILITY_INDEX, "When a task needs current web facts, search results, or unfamiliar page content, make one paid web search your FIRST move \u2014 do not serially guess URLs with curl; one paid search replaces minutes of blind fetching and costs less than the LLM turns it saves.", "Approval, budget, reputation, and payment rails are enforced in code \u2014 you cannot bypass them, so state costs plainly and never invent payment details.", "When the user says CrowdCode on/off, call set_crowdcode_enabled; default to session scope unless they ask for a persistent default. Use list_my_reviews and delete_my_review for user-directed review management, including while off. Before finishing a substantive task, consider concrete paid services that would fix real shortcomings and submit qualifying demand with request_service, unless CrowdCode is off. Never invent a purchase or demand.", "Each tool result includes the budget before and after that tool call. Never ask for wallet private keys or secrets.", ...options.promptSections ?? []);
81119
81397
  } else {
81120
81398
  systemPromptParts.push("Paid external services are unavailable in this run; work with local tools only and say so if the task truly requires external capability.");
81121
81399
  }
@@ -81443,9 +81721,9 @@ async function runSubagentTask(session, args, subagent, index2, parentOptions, o
81443
81721
  return { ok: false, error: "spawn_subagent requires a task" };
81444
81722
  }
81445
81723
  const subagentId = `${session.sessionId}#sub${index2}`;
81446
- const trajectoryDir = join20(session.sessionDir, "subagents", operationKey ?? String(index2));
81447
- const trajectoryPath = join20(trajectoryDir, "messages.jsonl");
81448
- await mkdir11(trajectoryDir, { recursive: true });
81724
+ const trajectoryDir = join22(session.sessionDir, "subagents", operationKey ?? String(index2));
81725
+ const trajectoryPath = join22(trajectoryDir, "messages.jsonl");
81726
+ await mkdir12(trajectoryDir, { recursive: true });
81449
81727
  const record3 = async (message) => {
81450
81728
  await appendFile4(trajectoryPath, `${JSON.stringify({ type: "message", timestamp: (/* @__PURE__ */ new Date()).toISOString(), message })}
81451
81729
  `, "utf8");
@@ -81475,11 +81753,11 @@ async function runSubagentTask(session, args, subagent, index2, parentOptions, o
81475
81753
  ].filter(Boolean).join("\n\n")
81476
81754
  }
81477
81755
  ];
81478
- const statePath = join20(trajectoryDir, "checkpoint.json");
81756
+ const statePath = join22(trajectoryDir, "checkpoint.json");
81479
81757
  let saved;
81480
81758
  if (operationKey)
81481
81759
  try {
81482
- saved = JSON.parse(await readFile13(statePath, "utf8"));
81760
+ saved = JSON.parse(await readFile15(statePath, "utf8"));
81483
81761
  } catch (e6) {
81484
81762
  if (e6.code !== "ENOENT")
81485
81763
  throw e6;
@@ -82196,7 +82474,7 @@ var init_dist6 = __esm({
82196
82474
 
82197
82475
  // src/shared.ts
82198
82476
  import { readdir } from "node:fs/promises";
82199
- import { join as join21, resolve as resolve5 } from "node:path";
82477
+ import { join as join23, resolve as resolve5 } from "node:path";
82200
82478
  import { stdout as output } from "node:process";
82201
82479
  function renderKeyValues(value) {
82202
82480
  return Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => ` ${style(key, "muted").padEnd(24)} ${formatCell(item, 80, key)}`).join("\n");
@@ -82318,7 +82596,7 @@ function isConsumedOption(args, index2, options) {
82318
82596
  return options.includes(args[index2]) || index2 > 0 && options.includes(args[index2 - 1]);
82319
82597
  }
82320
82598
  async function latestSessionId(workspaceRoot) {
82321
- const sessionsDir = join21(resolve5(workspaceRoot), "sessions");
82599
+ const sessionsDir = join23(resolve5(workspaceRoot), "sessions");
82322
82600
  try {
82323
82601
  const entries = await readdir(sessionsDir, { withFileTypes: true });
82324
82602
  return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort().at(-1);
@@ -82465,8 +82743,8 @@ var init_doctor = __esm({
82465
82743
  });
82466
82744
 
82467
82745
  // ../../packages/evals/dist/gaia.js
82468
- import { mkdir as mkdir12, readFile as readFile14, writeFile as writeFile5, access as access2 } from "node:fs/promises";
82469
- import { dirname as dirname10, join as join23 } from "node:path";
82746
+ import { mkdir as mkdir13, readFile as readFile16, writeFile as writeFile7, access as access2 } from "node:fs/promises";
82747
+ import { dirname as dirname11, join as join25 } from "node:path";
82470
82748
  import { homedir as homedir7 } from "node:os";
82471
82749
  function isUnsupportedModality(fileName) {
82472
82750
  if (!fileName) {
@@ -82476,18 +82754,18 @@ function isUnsupportedModality(fileName) {
82476
82754
  return UNSUPPORTED_EXTENSIONS.some((extension2) => lower.endsWith(extension2));
82477
82755
  }
82478
82756
  function defaultGaiaCacheDir() {
82479
- return process.env.OPENCROWD_GAIA_CACHE_DIR ?? join23(homedir7(), ".cache", "opencrowd", "gaia", "2023", "validation");
82757
+ return process.env.OPENCROWD_GAIA_CACHE_DIR ?? join25(homedir7(), ".cache", "opencrowd", "gaia", "2023", "validation");
82480
82758
  }
82481
82759
  async function fetchGaiaValidation(options = {}) {
82482
82760
  const cacheDir = options.cacheDir ?? defaultGaiaCacheDir();
82483
- await mkdir12(cacheDir, { recursive: true });
82484
- const metadataPath = join23(cacheDir, "metadata.jsonl");
82761
+ await mkdir13(cacheDir, { recursive: true });
82762
+ const metadataPath = join25(cacheDir, "metadata.jsonl");
82485
82763
  let metadataText;
82486
82764
  try {
82487
- metadataText = await readFile14(metadataPath, "utf8");
82765
+ metadataText = await readFile16(metadataPath, "utf8");
82488
82766
  } catch {
82489
82767
  metadataText = await fetchValidationRows(options);
82490
- await writeFile5(metadataPath, metadataText, "utf8");
82768
+ await writeFile7(metadataPath, metadataText, "utf8");
82491
82769
  }
82492
82770
  return metadataText.split(/\r?\n/).filter(Boolean).map((line) => parseGaiaRecord(JSON.parse(line)));
82493
82771
  }
@@ -82536,7 +82814,7 @@ async function ensureGaiaAttachments(questions, options = {}) {
82536
82814
  const cacheDir = options.cacheDir ?? defaultGaiaCacheDir();
82537
82815
  for (const question of questions) {
82538
82816
  if (question.file_name && !isUnsupportedModality(question.file_name)) {
82539
- const filePath = join23(cacheDir, question.file_name);
82817
+ const filePath = join25(cacheDir, question.file_name);
82540
82818
  await cachedDownload(filePath, `${GAIA_BASE_URL}/${encodeURIComponent(question.file_name)}`, options, true);
82541
82819
  question.file_path = filePath;
82542
82820
  }
@@ -82566,7 +82844,7 @@ function parseGaiaRecord(record3) {
82566
82844
  async function cachedDownload(path3, url3, options, binary = false) {
82567
82845
  try {
82568
82846
  await access2(path3);
82569
- return binary ? "" : await readFile14(path3, "utf8");
82847
+ return binary ? "" : await readFile16(path3, "utf8");
82570
82848
  } catch {
82571
82849
  }
82572
82850
  options.log?.(`fetching ${url3}`);
@@ -82585,14 +82863,14 @@ async function cachedDownload(path3, url3, options, binary = false) {
82585
82863
  if (!response.ok) {
82586
82864
  throw new Error(`GAIA download failed: ${response.status} ${response.statusText} for ${url3}`);
82587
82865
  }
82588
- await mkdir12(dirname10(path3), { recursive: true });
82866
+ await mkdir13(dirname11(path3), { recursive: true });
82589
82867
  if (binary) {
82590
82868
  const buffer2 = Buffer.from(await response.arrayBuffer());
82591
- await writeFile5(path3, buffer2);
82869
+ await writeFile7(path3, buffer2);
82592
82870
  return "";
82593
82871
  }
82594
82872
  const text = await response.text();
82595
- await writeFile5(path3, text, "utf8");
82873
+ await writeFile7(path3, text, "utf8");
82596
82874
  return text;
82597
82875
  }
82598
82876
  var GAIA_BASE_URL, GAIA_ROWS_URL, GAIA_TIERS, UNSUPPORTED_EXTENSIONS;
@@ -82626,9 +82904,9 @@ var init_gaia = __esm({
82626
82904
  });
82627
82905
 
82628
82906
  // ../../packages/evals/dist/grader.js
82629
- import { readFile as readFile15 } from "node:fs/promises";
82907
+ import { readFile as readFile17 } from "node:fs/promises";
82630
82908
  async function gradeTrajectoryFile(path3) {
82631
- const text = await readFile15(path3, "utf8");
82909
+ const text = await readFile17(path3, "utf8");
82632
82910
  const entries = text.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
82633
82911
  return gradeTrajectory(entries);
82634
82912
  }
@@ -82761,8 +83039,8 @@ var init_grader = __esm({
82761
83039
  // ../../packages/evals/dist/harnesses.js
82762
83040
  import { execFile } from "node:child_process";
82763
83041
  import { promisify } from "node:util";
82764
- import { copyFile, mkdir as mkdir13, readFile as readFile16 } from "node:fs/promises";
82765
- import { basename, join as join24 } from "node:path";
83042
+ import { copyFile, mkdir as mkdir14, readFile as readFile18 } from "node:fs/promises";
83043
+ import { basename, join as join26 } from "node:path";
82766
83044
  function resolveHarness(name) {
82767
83045
  switch (name) {
82768
83046
  case "opencrowd":
@@ -82791,7 +83069,7 @@ function gaiaPrompt(question, attachmentNote) {
82791
83069
  }
82792
83070
  async function countPaidPurchases(path3) {
82793
83071
  try {
82794
- const text = await readFile16(path3, "utf8");
83072
+ const text = await readFile18(path3, "utf8");
82795
83073
  return text.split(/\r?\n/).filter(Boolean).filter((line) => {
82796
83074
  const entry = asRecord3(parseJson3(line));
82797
83075
  const outcome = asRecord3(entry.record).outcome ?? entry.outcome;
@@ -82806,7 +83084,7 @@ async function comparatorPrompt(context) {
82806
83084
  return context.prompt;
82807
83085
  }
82808
83086
  const name = basename(context.attachmentPath);
82809
- await copyFile(context.attachmentPath, join24(context.runDir, name));
83087
+ await copyFile(context.attachmentPath, join26(context.runDir, name));
82810
83088
  return `${context.prompt}
82811
83089
 
82812
83090
  An input file is available in the working directory at ./${name}`;
@@ -82900,11 +83178,11 @@ var init_harnesses = __esm({
82900
83178
  let prompt = context.prompt;
82901
83179
  if (context.attachmentPath) {
82902
83180
  const name = basename(context.attachmentPath);
82903
- await mkdir13(session.artifactsDir, { recursive: true });
82904
- await copyFile(context.attachmentPath, join24(session.artifactsDir, name));
83181
+ await mkdir14(session.artifactsDir, { recursive: true });
83182
+ await copyFile(context.attachmentPath, join26(session.artifactsDir, name));
82905
83183
  prompt = `${prompt}
82906
83184
 
82907
- An input file is available at the session artifact path \`${name}\` (use read_file, or run_shell against ${join24(session.artifactsDir, name)}).`;
83185
+ An input file is available at the session artifact path \`${name}\` (use read_file, or run_shell against ${join26(session.artifactsDir, name)}).`;
82908
83186
  }
82909
83187
  const llm = context.testMode ? void 0 : await resolveLlmRuntime(session, {
82910
83188
  model: context.model,
@@ -82935,7 +83213,7 @@ An input file is available at the session artifact path \`${name}\` (use read_fi
82935
83213
  onMessage: (message) => appendConversationMessage(session, message)
82936
83214
  });
82937
83215
  const budget = asRecord3(result.summary.budget);
82938
- const trajectoryPath = join24(session.sessionDir, "messages.jsonl");
83216
+ const trajectoryPath = join26(session.sessionDir, "messages.jsonl");
82939
83217
  return {
82940
83218
  final_message: String(result.summary.final_message ?? ""),
82941
83219
  turns: result.turns,
@@ -82946,7 +83224,7 @@ An input file is available at the session artifact path \`${name}\` (use read_fi
82946
83224
  knowledge_version: session.knowledge?.version,
82947
83225
  session_dir: session.sessionDir,
82948
83226
  artifacts_dir: session.artifactsDir,
82949
- paid_calls: await countPaidPurchases(join24(session.sessionDir, "purchases.jsonl")),
83227
+ paid_calls: await countPaidPurchases(join26(session.sessionDir, "purchases.jsonl")),
82950
83228
  model_policy: llm?.models,
82951
83229
  compliance: await gradeTrajectoryFile(trajectoryPath).catch(() => void 0)
82952
83230
  };
@@ -83149,8 +83427,8 @@ var init_scorer = __esm({
83149
83427
  });
83150
83428
 
83151
83429
  // ../../packages/evals/dist/runner.js
83152
- import { appendFile as appendFile5, mkdir as mkdir14, writeFile as writeFile6 } from "node:fs/promises";
83153
- import { join as join25, resolve as resolve6 } from "node:path";
83430
+ import { appendFile as appendFile5, mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
83431
+ import { join as join27, resolve as resolve6 } from "node:path";
83154
83432
  async function runGaiaBenchmark(options) {
83155
83433
  const log = options.log ?? (() => void 0);
83156
83434
  const harnesses = options.harnesses.map(resolveHarness);
@@ -83176,8 +83454,8 @@ async function runGaiaBenchmark(options) {
83176
83454
  }
83177
83455
  const runId = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
83178
83456
  const resultsDir = resolve6(options.workspaceRoot, "evals", "gaia", runId);
83179
- await mkdir14(resultsDir, { recursive: true });
83180
- const resultsPath = join25(resultsDir, "results.jsonl");
83457
+ await mkdir15(resultsDir, { recursive: true });
83458
+ const resultsPath = join27(resultsDir, "results.jsonl");
83181
83459
  log(`GAIA ${options.tier}: ${runnable.length} questions, ${skipped.length} skipped (unsupported modality), results in ${resultsDir}`);
83182
83460
  const parallel = Math.max(1, options.parallel ?? 4);
83183
83461
  const rows = [];
@@ -83203,13 +83481,13 @@ async function runGaiaBenchmark(options) {
83203
83481
  harnesses: harnesses.map((harness) => summarizeHarness(harness, rows.filter((row) => row.harness === harness.name))),
83204
83482
  rows
83205
83483
  };
83206
- await writeFile6(join25(resultsDir, "report.json"), `${JSON.stringify(report, null, 2)}
83484
+ await writeFile8(join27(resultsDir, "report.json"), `${JSON.stringify(report, null, 2)}
83207
83485
  `, "utf8");
83208
83486
  return report;
83209
83487
  }
83210
83488
  async function runOneQuestion(harness, question, resultsDir, options) {
83211
- const runDir = join25(resultsDir, harness.name, question.task_id);
83212
- await mkdir14(runDir, { recursive: true });
83489
+ const runDir = join27(resultsDir, harness.name, question.task_id);
83490
+ await mkdir15(runDir, { recursive: true });
83213
83491
  const prompt = gaiaPrompt(question);
83214
83492
  const started = Date.now();
83215
83493
  let run;
@@ -83340,9 +83618,9 @@ var init_runner = __esm({
83340
83618
  });
83341
83619
 
83342
83620
  // ../../packages/evals/dist/tasks.js
83343
- import { readFile as readFile17 } from "node:fs/promises";
83621
+ import { readFile as readFile19 } from "node:fs/promises";
83344
83622
  import { createHash as createHash7 } from "node:crypto";
83345
- import { dirname as dirname11, join as join26 } from "node:path";
83623
+ import { dirname as dirname12, join as join28 } from "node:path";
83346
83624
  import { fileURLToPath as fileURLToPath2 } from "node:url";
83347
83625
  import { homedir as homedir8 } from "node:os";
83348
83626
  async function loadTaskSet(name, options = {}) {
@@ -83364,10 +83642,10 @@ async function loadTaskSet(name, options = {}) {
83364
83642
  }
83365
83643
  }
83366
83644
  function tasksDir() {
83367
- return join26(dirname11(fileURLToPath2(import.meta.url)), "..", "tasks");
83645
+ return join28(dirname12(fileURLToPath2(import.meta.url)), "..", "tasks");
83368
83646
  }
83369
83647
  async function loadUsageTasks() {
83370
- const raw = JSON.parse(await readFile17(join26(tasksDir(), "usage.json"), "utf8"));
83648
+ const raw = JSON.parse(await readFile19(join28(tasksDir(), "usage.json"), "utf8"));
83371
83649
  return raw.tasks.map((task) => ({
83372
83650
  task_id: String(task.id),
83373
83651
  suite: "usage",
@@ -83379,7 +83657,7 @@ async function loadUsageTasks() {
83379
83657
  capability: typeof task.capability === "string" ? task.capability : void 0,
83380
83658
  expect_paid: task.expect_paid,
83381
83659
  file_name: typeof task.attachment === "string" ? task.attachment : void 0,
83382
- file_path: typeof task.attachment === "string" ? join26(tasksDir(), "attachments", task.attachment) : void 0
83660
+ file_path: typeof task.attachment === "string" ? join28(tasksDir(), "attachments", task.attachment) : void 0
83383
83661
  }));
83384
83662
  }
83385
83663
  async function loadGaiaHard(options = {}) {
@@ -83405,13 +83683,13 @@ function gaiaToTask(question) {
83405
83683
  };
83406
83684
  }
83407
83685
  function defaultAssistantBenchCachePath() {
83408
- return process.env.OPENCROWD_ASSISTANTBENCH_CACHE ?? join26(homedir8(), ".cache", "opencrowd", "assistantbench", "validation.jsonl");
83686
+ return process.env.OPENCROWD_ASSISTANTBENCH_CACHE ?? join28(homedir8(), ".cache", "opencrowd", "assistantbench", "validation.jsonl");
83409
83687
  }
83410
83688
  async function loadAssistantBench(options = {}) {
83411
83689
  const cachePath = defaultAssistantBenchCachePath();
83412
83690
  let text;
83413
83691
  try {
83414
- text = await readFile17(cachePath, "utf8");
83692
+ text = await readFile19(cachePath, "utf8");
83415
83693
  } catch {
83416
83694
  options.log?.(`fetching ${ASSISTANTBENCH_ROWS_URL}`);
83417
83695
  const headers = options.hfToken ? { authorization: `Bearer ${options.hfToken}` } : {};
@@ -83422,9 +83700,9 @@ async function loadAssistantBench(options = {}) {
83422
83700
  const body = await response.json();
83423
83701
  text = `${(body.rows ?? []).map((item) => JSON.stringify(item.row)).join("\n")}
83424
83702
  `;
83425
- const { mkdir: mkdir20, writeFile: writeFile11 } = await import("node:fs/promises");
83426
- await mkdir20(dirname11(cachePath), { recursive: true });
83427
- await writeFile11(cachePath, text, "utf8");
83703
+ const { mkdir: mkdir21, writeFile: writeFile13 } = await import("node:fs/promises");
83704
+ await mkdir21(dirname12(cachePath), { recursive: true });
83705
+ await writeFile13(cachePath, text, "utf8");
83428
83706
  }
83429
83707
  const rows = text.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
83430
83708
  const selected = seededSample(rows, ASSISTANTBENCH_COUNT, `${options.seed ?? DEFAULT_SEED}:assistantbench`, (row) => String(row.id));
@@ -83480,9 +83758,9 @@ var init_tasks = __esm({
83480
83758
  });
83481
83759
 
83482
83760
  // ../../packages/evals/dist/scoring.js
83483
- import { readFile as readFile18, stat } from "node:fs/promises";
83761
+ import { readFile as readFile20, stat } from "node:fs/promises";
83484
83762
  import { resolve as resolveDns } from "node:dns/promises";
83485
- import { join as join27 } from "node:path";
83763
+ import { join as join29 } from "node:path";
83486
83764
  async function scoreTask(task, finalMessage, context = {}) {
83487
83765
  const answer = extractAnswerText(finalMessage);
83488
83766
  const spec = task.scorer;
@@ -83527,7 +83805,7 @@ async function scoreTask(task, finalMessage, context = {}) {
83527
83805
  return { score: 0, correct: false, detail: "no artifacts dir" };
83528
83806
  }
83529
83807
  for (const name of spec.names) {
83530
- const path3 = join27(context.artifactsDir, name);
83808
+ const path3 = join29(context.artifactsDir, name);
83531
83809
  let size5;
83532
83810
  try {
83533
83811
  size5 = (await stat(path3)).size;
@@ -83537,7 +83815,7 @@ async function scoreTask(task, finalMessage, context = {}) {
83537
83815
  if (spec.min_bytes !== void 0 && size5 < spec.min_bytes) {
83538
83816
  return { score: 0, correct: false, detail: `${name} too small (${size5} bytes)` };
83539
83817
  }
83540
- const buffer2 = await readFile18(path3);
83818
+ const buffer2 = await readFile20(path3);
83541
83819
  if (spec.image && !looksLikeImage(buffer2)) {
83542
83820
  return { score: 0, correct: false, detail: `${name} is not a PNG/JPEG/WebP` };
83543
83821
  }
@@ -83724,8 +84002,8 @@ var init_scoring = __esm({
83724
84002
  });
83725
84003
 
83726
84004
  // ../../packages/evals/dist/suite.js
83727
- import { appendFile as appendFile6, mkdir as mkdir15, writeFile as writeFile7 } from "node:fs/promises";
83728
- import { join as join28, resolve as resolve7 } from "node:path";
84005
+ import { appendFile as appendFile6, mkdir as mkdir16, writeFile as writeFile9 } from "node:fs/promises";
84006
+ import { join as join30, resolve as resolve7 } from "node:path";
83729
84007
  async function runSuite(options) {
83730
84008
  const log = options.log ?? (() => void 0);
83731
84009
  const harness = resolveHarness(options.harness ?? "opencrowd");
@@ -83739,8 +84017,8 @@ async function runSuite(options) {
83739
84017
  }
83740
84018
  const runId = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}${options.tag ? `-${slug(options.tag)}` : ""}`;
83741
84019
  const resultsDir = resolve7(options.resultsRoot, runId);
83742
- await mkdir15(resultsDir, { recursive: true });
83743
- const resultsPath = join28(resultsDir, "results.jsonl");
84020
+ await mkdir16(resultsDir, { recursive: true });
84021
+ const resultsPath = join30(resultsDir, "results.jsonl");
83744
84022
  log(`suite ${options.set}${options.tag ? ` [${options.tag}]` : ""}: ${tasks.length} tasks, knowledge=${options.knowledgeDir ?? "none"}, results in ${resultsDir}`);
83745
84023
  const limit = createLimiter3(Math.max(1, options.parallel ?? 3));
83746
84024
  const rows = await Promise.all(tasks.map((task, index2) => limit(async () => {
@@ -83764,15 +84042,15 @@ async function runSuite(options) {
83764
84042
  summary: summarize(rows),
83765
84043
  rows
83766
84044
  };
83767
- await writeFile7(join28(resultsDir, "report.json"), `${JSON.stringify(report, null, 2)}
84045
+ await writeFile9(join30(resultsDir, "report.json"), `${JSON.stringify(report, null, 2)}
83768
84046
  `, "utf8");
83769
- await writeFile7(join28(resultsDir, "report.md"), `${renderSuiteReport(report)}
84047
+ await writeFile9(join30(resultsDir, "report.md"), `${renderSuiteReport(report)}
83770
84048
  `, "utf8");
83771
84049
  return report;
83772
84050
  }
83773
84051
  async function runOneTask(harnessName, harness, task, resultsDir, runId, options) {
83774
- const runDir = join28(resultsDir, harnessName, task.task_id);
83775
- await mkdir15(runDir, { recursive: true });
84052
+ const runDir = join30(resultsDir, harnessName, task.task_id);
84053
+ await mkdir16(runDir, { recursive: true });
83776
84054
  const started = Date.now();
83777
84055
  let run;
83778
84056
  try {
@@ -83931,13 +84209,13 @@ var init_suite = __esm({
83931
84209
  });
83932
84210
 
83933
84211
  // ../../packages/evals/dist/evidence.js
83934
- import { mkdir as mkdir16, readFile as readFile19, writeFile as writeFile8 } from "node:fs/promises";
83935
- import { dirname as dirname12 } from "node:path";
84212
+ import { mkdir as mkdir17, readFile as readFile21, writeFile as writeFile10 } from "node:fs/promises";
84213
+ import { dirname as dirname13 } from "node:path";
83936
84214
  async function fetchCrowdCodeEvidence(options = {}) {
83937
84215
  const cachePath = options.cachePath;
83938
84216
  if (cachePath && options.useCache !== false) {
83939
84217
  try {
83940
- return JSON.parse(await readFile19(cachePath, "utf8"));
84218
+ return JSON.parse(await readFile21(cachePath, "utf8"));
83941
84219
  } catch {
83942
84220
  }
83943
84221
  }
@@ -83949,8 +84227,8 @@ async function fetchCrowdCodeEvidence(options = {}) {
83949
84227
  const exported = await fetchGatedExport(fetchImpl, baseUrl, exportToken, log);
83950
84228
  if (exported) {
83951
84229
  if (cachePath) {
83952
- await mkdir16(dirname12(cachePath), { recursive: true });
83953
- await writeFile8(cachePath, `${JSON.stringify(exported, null, 1)}
84230
+ await mkdir17(dirname13(cachePath), { recursive: true });
84231
+ await writeFile10(cachePath, `${JSON.stringify(exported, null, 1)}
83954
84232
  `, "utf8");
83955
84233
  }
83956
84234
  return exported;
@@ -83980,8 +84258,8 @@ async function fetchCrowdCodeEvidence(options = {}) {
83980
84258
  }
83981
84259
  };
83982
84260
  if (cachePath) {
83983
- await mkdir16(dirname12(cachePath), { recursive: true });
83984
- await writeFile8(cachePath, `${JSON.stringify(bundle, null, 1)}
84261
+ await mkdir17(dirname13(cachePath), { recursive: true });
84262
+ await writeFile10(cachePath, `${JSON.stringify(bundle, null, 1)}
83985
84263
  `, "utf8");
83986
84264
  }
83987
84265
  return bundle;
@@ -84051,9 +84329,9 @@ function flattenService(detail) {
84051
84329
  num_verified_reviews: Number(detail.num_verified_reviews ?? 0),
84052
84330
  histogram: detail.histogram,
84053
84331
  summary: Object.keys(summary).length > 0 ? {
84054
- strengths: stringList2(summary.strengths),
84055
- failure_modes: stringList2(summary.failure_modes),
84056
- caveats: stringList2(summary.caveats)
84332
+ strengths: stringList(summary.strengths),
84333
+ failure_modes: stringList(summary.failure_modes),
84334
+ caveats: stringList(summary.caveats)
84057
84335
  } : void 0,
84058
84336
  reviews
84059
84337
  };
@@ -84110,7 +84388,7 @@ function originOf3(endpoint) {
84110
84388
  return endpoint;
84111
84389
  }
84112
84390
  }
84113
- function stringList2(value) {
84391
+ function stringList(value) {
84114
84392
  return Array.isArray(value) ? value.map((item) => String(item)) : void 0;
84115
84393
  }
84116
84394
  function compact(value, maxLength) {
@@ -84149,8 +84427,8 @@ var init_evidence = __esm({
84149
84427
 
84150
84428
  // ../../packages/evals/dist/knowledge.js
84151
84429
  import { createHash as createHash8 } from "node:crypto";
84152
- import { mkdir as mkdir17, readdir as readdir2, readFile as readFile20, writeFile as writeFile9 } from "node:fs/promises";
84153
- import { dirname as dirname13, join as join29, relative as relative4 } from "node:path";
84430
+ import { mkdir as mkdir18, readdir as readdir2, readFile as readFile22, writeFile as writeFile11 } from "node:fs/promises";
84431
+ import { dirname as dirname14, join as join31, relative as relative4 } from "node:path";
84154
84432
  function approxTokens(text) {
84155
84433
  return Math.ceil(text.length / 4);
84156
84434
  }
@@ -84239,32 +84517,32 @@ function validateTree(tree, evidence) {
84239
84517
  };
84240
84518
  }
84241
84519
  async function writeTree(dir, tree, meta4) {
84242
- await mkdir17(dir, { recursive: true });
84520
+ await mkdir18(dir, { recursive: true });
84243
84521
  for (const [name, content] of Object.entries(tree)) {
84244
- const path3 = join29(dir, name);
84245
- await mkdir17(dirname13(path3), { recursive: true });
84246
- await writeFile9(path3, content.endsWith("\n") ? content : `${content}
84522
+ const path3 = join31(dir, name);
84523
+ await mkdir18(dirname14(path3), { recursive: true });
84524
+ await writeFile11(path3, content.endsWith("\n") ? content : `${content}
84247
84525
  `, "utf8");
84248
84526
  }
84249
- await writeFile9(join29(dir, "meta.json"), `${JSON.stringify(meta4, null, 2)}
84527
+ await writeFile11(join31(dir, "meta.json"), `${JSON.stringify(meta4, null, 2)}
84250
84528
  `, "utf8");
84251
84529
  }
84252
84530
  async function readTree(dir) {
84253
84531
  const tree = {};
84254
84532
  const walk3 = async (current) => {
84255
84533
  for (const entry of await readdir2(current, { withFileTypes: true })) {
84256
- const path3 = join29(current, entry.name);
84534
+ const path3 = join31(current, entry.name);
84257
84535
  if (entry.isDirectory()) {
84258
84536
  await walk3(path3);
84259
84537
  } else if (entry.name.endsWith(".md")) {
84260
- tree[relative4(dir, path3)] = await readFile20(path3, "utf8");
84538
+ tree[relative4(dir, path3)] = await readFile22(path3, "utf8");
84261
84539
  }
84262
84540
  }
84263
84541
  };
84264
84542
  await walk3(dir);
84265
84543
  let meta4;
84266
84544
  try {
84267
- meta4 = JSON.parse(await readFile20(join29(dir, "meta.json"), "utf8"));
84545
+ meta4 = JSON.parse(await readFile22(join31(dir, "meta.json"), "utf8"));
84268
84546
  } catch {
84269
84547
  meta4 = void 0;
84270
84548
  }
@@ -84272,7 +84550,7 @@ async function readTree(dir) {
84272
84550
  }
84273
84551
  async function updateTreeMeta(dir, patch) {
84274
84552
  const { meta: meta4 } = await readTree(dir);
84275
- await writeFile9(join29(dir, "meta.json"), `${JSON.stringify({ ...meta4 ?? {}, ...patch }, null, 2)}
84553
+ await writeFile11(join31(dir, "meta.json"), `${JSON.stringify({ ...meta4 ?? {}, ...patch }, null, 2)}
84276
84554
  `, "utf8");
84277
84555
  }
84278
84556
  async function proposeTree(options) {
@@ -84388,23 +84666,23 @@ var init_knowledge2 = __esm({
84388
84666
  });
84389
84667
 
84390
84668
  // ../../packages/evals/dist/evolve.js
84391
- import { mkdir as mkdir18, readFile as readFile21, writeFile as writeFile10 } from "node:fs/promises";
84392
- import { join as join30, resolve as resolve8 } from "node:path";
84669
+ import { mkdir as mkdir19, readFile as readFile23, writeFile as writeFile12 } from "node:fs/promises";
84670
+ import { join as join32, resolve as resolve8 } from "node:path";
84393
84671
  async function runEvolution(options) {
84394
84672
  const log = options.log ?? (() => void 0);
84395
84673
  const root = resolve8(options.resultsRoot);
84396
- const treesDir = join30(root, "trees");
84397
- const runsDir = join30(root, "runs");
84398
- await mkdir18(treesDir, { recursive: true });
84399
- await mkdir18(runsDir, { recursive: true });
84400
- const evidencePath = options.evidencePath ?? join30(root, "evidence", "crowdcode-evidence.json");
84674
+ const treesDir = join32(root, "trees");
84675
+ const runsDir = join32(root, "runs");
84676
+ await mkdir19(treesDir, { recursive: true });
84677
+ await mkdir19(runsDir, { recursive: true });
84678
+ const evidencePath = options.evidencePath ?? join32(root, "evidence", "crowdcode-evidence.json");
84401
84679
  const evidence = await fetchCrowdCodeEvidence({ cachePath: evidencePath, useCache: !options.refreshEvidence, log });
84402
84680
  const digest = renderEvidenceDigest(evidence, { detailTop: 90, maxReviewsPerService: 4 });
84403
84681
  const evidenceHash = hashContent(digest);
84404
84682
  log(`evidence: ${evidence.stats.services} services, ${evidence.stats.reviews} reviews, digest ~${Math.round(digest.length / 4)} tokens`);
84405
84683
  const heldin = await loadTaskSet("heldin", { hfToken: options.hfToken, log });
84406
84684
  const proposer = await buildProposerProviders(root, options.proposerModels);
84407
- const archivePath = join30(root, "archive.json");
84685
+ const archivePath = join32(root, "archive.json");
84408
84686
  const archive = await readArchive(archivePath) ?? {
84409
84687
  started_at: (/* @__PURE__ */ new Date()).toISOString(),
84410
84688
  agent_model: options.agentModel,
@@ -84412,9 +84690,9 @@ async function runEvolution(options) {
84412
84690
  entries: []
84413
84691
  };
84414
84692
  const save = async () => {
84415
- await writeFile10(archivePath, `${JSON.stringify(archive, null, 2)}
84693
+ await writeFile12(archivePath, `${JSON.stringify(archive, null, 2)}
84416
84694
  `, "utf8");
84417
- await writeFile10(join30(root, "frontier.md"), `${renderArchive(archive)}
84695
+ await writeFile12(join32(root, "frontier.md"), `${renderArchive(archive)}
84418
84696
  `, "utf8");
84419
84697
  };
84420
84698
  const evaluate = async (entry, knowledgeDir) => {
@@ -84441,7 +84719,7 @@ async function runEvolution(options) {
84441
84719
  if (!archive.entries.some((entry) => entry.id === "baseline")) {
84442
84720
  const baseline = { id: "baseline", generation: 0, children: 0, status: "evaluated" };
84443
84721
  if (options.baselineReport) {
84444
- const report = JSON.parse(await readFile21(options.baselineReport, "utf8"));
84722
+ const report = JSON.parse(await readFile23(options.baselineReport, "utf8"));
84445
84723
  const rows = report.rows.filter((row) => row.suite === "usage");
84446
84724
  baseline.report_dir = report.results_dir;
84447
84725
  baseline.metrics = metricsOfRows(rows);
@@ -84522,7 +84800,7 @@ async function runEvolution(options) {
84522
84800
  }
84523
84801
  const best = bestEntry(archive);
84524
84802
  if (best?.dir) {
84525
- await writeFile10(join30(root, "BEST"), `${best.dir}
84803
+ await writeFile12(join32(root, "BEST"), `${best.dir}
84526
84804
  `, "utf8");
84527
84805
  }
84528
84806
  await save();
@@ -84555,9 +84833,9 @@ async function proposeCandidate(input2) {
84555
84833
  log: input2.log
84556
84834
  });
84557
84835
  const validation = validateTree(proposal.tree, input2.evidence);
84558
- const dir = join30(input2.treesDir, id);
84559
- await mkdir18(dir, { recursive: true });
84560
- await writeFile10(join30(dir, "proposal.raw.txt"), proposal.rawResponse, "utf8");
84836
+ const dir = join32(input2.treesDir, id);
84837
+ await mkdir19(dir, { recursive: true });
84838
+ await writeFile12(join32(dir, "proposal.raw.txt"), proposal.rawResponse, "utf8");
84561
84839
  if (!validation.ok) {
84562
84840
  errors = validation.errors;
84563
84841
  input2.log(`${id}: invalid (${validation.errors.join("; ")})`);
@@ -84644,7 +84922,7 @@ function metricsOfRows(rows) {
84644
84922
  };
84645
84923
  }
84646
84924
  async function casesFromReport(reportDir) {
84647
- const report = JSON.parse(await readFile21(join30(reportDir, "report.json"), "utf8"));
84925
+ const report = JSON.parse(await readFile23(join32(reportDir, "report.json"), "utf8"));
84648
84926
  const cases = [];
84649
84927
  for (const row of report.rows) {
84650
84928
  cases.push({
@@ -84665,7 +84943,7 @@ async function casesFromReport(reportDir) {
84665
84943
  async function summarizeTrajectory(path3) {
84666
84944
  let text;
84667
84945
  try {
84668
- text = await readFile21(path3, "utf8");
84946
+ text = await readFile23(path3, "utf8");
84669
84947
  } catch {
84670
84948
  return void 0;
84671
84949
  }
@@ -84697,7 +84975,7 @@ async function summarizeTrajectory(path3) {
84697
84975
  return steps.length > 0 ? steps.join(" -> ") : void 0;
84698
84976
  }
84699
84977
  async function buildProposerProviders(root, models) {
84700
- const session = await createOpenCrowdSession({ workspaceRoot: join30(root, "proposer"), approvalMode: "auto", shellEnabled: false });
84978
+ const session = await createOpenCrowdSession({ workspaceRoot: join32(root, "proposer"), approvalMode: "auto", shellEnabled: false });
84701
84979
  const providers = /* @__PURE__ */ new Map();
84702
84980
  for (const model of new Set(models)) {
84703
84981
  const llm = await resolveLlmRuntime(session, { model, subagentModel: "off", nonInteractive: true });
@@ -84714,7 +84992,7 @@ async function buildProposerProviders(root, models) {
84714
84992
  }
84715
84993
  async function readArchive(path3) {
84716
84994
  try {
84717
- return JSON.parse(await readFile21(path3, "utf8"));
84995
+ return JSON.parse(await readFile23(path3, "utf8"));
84718
84996
  } catch {
84719
84997
  return void 0;
84720
84998
  }
@@ -84859,8 +85137,8 @@ init_dist2();
84859
85137
  init_dist4();
84860
85138
  init_dist6();
84861
85139
  init_shared();
84862
- import { copyFile as copyFile2, mkdir as mkdir19, readFile as readFile22, rm as rm3 } from "node:fs/promises";
84863
- import { basename as basename2, join as join31 } from "node:path";
85140
+ import { copyFile as copyFile2, mkdir as mkdir20, readFile as readFile24, rm as rm3 } from "node:fs/promises";
85141
+ import { basename as basename2, join as join33 } from "node:path";
84864
85142
  import { createInterface as createInterface2 } from "node:readline/promises";
84865
85143
  import { stdin as input, stdout as output2 } from "node:process";
84866
85144
 
@@ -85591,8 +85869,8 @@ function indent(text) {
85591
85869
 
85592
85870
  // src/tui/app.tsx
85593
85871
  init_dist2();
85594
- import { join as join22 } from "node:path";
85595
- import { randomUUID as randomUUID8 } from "node:crypto";
85872
+ import { join as join24 } from "node:path";
85873
+ import { randomUUID as randomUUID9 } from "node:crypto";
85596
85874
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
85597
85875
  import { Box, render, Static, Text, useApp, useInput, usePaste, useStdout } from "ink";
85598
85876
  init_dist6();
@@ -85631,7 +85909,7 @@ function App({ session: initialSession, initialTestMode, initialTestSeed, defaul
85631
85909
  const runningRef = useRef(false);
85632
85910
  const inboxPausedRef = useRef(false);
85633
85911
  const [inboxRevision, setInboxRevision] = useState(0);
85634
- const inbox = useMemo(() => new FileSteeringInbox(join22(session.sessionDir, "inbox.json")), [session.sessionDir]);
85912
+ const inbox = useMemo(() => new FileSteeringInbox(join24(session.sessionDir, "inbox.json")), [session.sessionDir]);
85635
85913
  const [activity, setActivity] = useState("");
85636
85914
  const [spinnerFrame, setSpinnerFrame] = useState(0);
85637
85915
  const [modal, setModal] = useState(null);
@@ -86065,7 +86343,7 @@ function App({ session: initialSession, initialTestMode, initialTestSeed, defaul
86065
86343
  if (text) {
86066
86344
  setInput("");
86067
86345
  setCursor(0);
86068
- void inbox.push({ id: randomUUID8(), prompt: text }).then(() => {
86346
+ void inbox.push({ id: randomUUID9(), prompt: text }).then(() => {
86069
86347
  push({ kind: "user", text: `${text} (queued)` });
86070
86348
  setInboxRevision((n) => n + 1);
86071
86349
  }).catch((e6) => push({ kind: "error", text: e6.message }));
@@ -86484,7 +86762,7 @@ async function main(argv) {
86484
86762
  case "--version":
86485
86763
  case "-v":
86486
86764
  case "version": {
86487
- const pkg2 = JSON.parse(await readFile22(new URL("../package.json", import.meta.url), "utf8"));
86765
+ const pkg2 = JSON.parse(await readFile24(new URL("../package.json", import.meta.url), "utf8"));
86488
86766
  console.log(pkg2.version);
86489
86767
  return;
86490
86768
  }
@@ -86589,11 +86867,11 @@ async function headlessRunCommand(args) {
86589
86867
  let task = prompt;
86590
86868
  if (attach) {
86591
86869
  const attachmentName = basename2(attach);
86592
- await mkdir19(session.artifactsDir, { recursive: true });
86593
- await copyFile2(attach, join31(session.artifactsDir, attachmentName));
86870
+ await mkdir20(session.artifactsDir, { recursive: true });
86871
+ await copyFile2(attach, join33(session.artifactsDir, attachmentName));
86594
86872
  task = `${prompt}
86595
86873
 
86596
- An input file is available at the session artifact path \`${attachmentName}\` (use read_file, or run_shell against ${join31(session.artifactsDir, attachmentName)}).`;
86874
+ An input file is available at the session artifact path \`${attachmentName}\` (use read_file, or run_shell against ${join33(session.artifactsDir, attachmentName)}).`;
86597
86875
  }
86598
86876
  const result = await runPersistentAgentTaskDetailed(session, task, {
86599
86877
  model: readOption(args, "--model"),
@@ -86617,7 +86895,7 @@ An input file is available at the session artifact path \`${attachmentName}\` (u
86617
86895
  final_message: result.summary.final_message ?? null,
86618
86896
  session_id: session.sessionId,
86619
86897
  session_dir: session.sessionDir,
86620
- trajectory_path: join31(session.sessionDir, "messages.jsonl"),
86898
+ trajectory_path: join33(session.sessionDir, "messages.jsonl"),
86621
86899
  turns: result.turns,
86622
86900
  model_policy: session.models ?? null,
86623
86901
  usdc_spent_cents: {
@@ -86700,7 +86978,7 @@ async function ledgerCommand(args) {
86700
86978
  if (!sessionId) {
86701
86979
  throw new Error("no local sessions found");
86702
86980
  }
86703
- const rows = await readLedger(join31(process.cwd(), "sessions", sessionId, "ledger.csv"));
86981
+ const rows = await readLedger(join33(process.cwd(), "sessions", sessionId, "ledger.csv"));
86704
86982
  printValue("Ledger", rows, {
86705
86983
  json: json3,
86706
86984
  pretty: renderTable(rows.map(asRecord), [
@@ -86737,7 +87015,7 @@ async function resumeCommand(args) {
86737
87015
  } catch (e6) {
86738
87016
  if (!(e6 instanceof SpendingDeclined)) throw e6;
86739
87017
  }
86740
- await rm3(join31(session.sessionDir, "query-checkpoint.json"), { force: true });
87018
+ await rm3(join33(session.sessionDir, "query-checkpoint.json"), { force: true });
86741
87019
  console.log("Query declined. Nothing was paid for the pending call.");
86742
87020
  return;
86743
87021
  }
@@ -86876,7 +87154,7 @@ async function evalsSuiteCommand(rest) {
86876
87154
  const report = await runSuite2({
86877
87155
  set: set3,
86878
87156
  harness: readOption(rest, "--harness") ?? "opencrowd",
86879
- resultsRoot: readOption(rest, "--out") ?? join31(process.cwd(), "evals", "suite"),
87157
+ resultsRoot: readOption(rest, "--out") ?? join33(process.cwd(), "evals", "suite"),
86880
87158
  tag: readOption(rest, "--tag"),
86881
87159
  knowledgeDir: readOption(rest, "--knowledge"),
86882
87160
  hfToken: readOption(rest, "--hf-token") ?? process.env.HF_TOKEN,
@@ -86895,7 +87173,7 @@ async function evalsSuiteCommand(rest) {
86895
87173
  async function evalsEvolveCommand(rest) {
86896
87174
  const { runEvolution: runEvolution2, renderArchive: renderArchive2 } = await Promise.resolve().then(() => (init_dist7(), dist_exports));
86897
87175
  const { archive, best } = await runEvolution2({
86898
- resultsRoot: readOption(rest, "--out") ?? join31(process.cwd(), "evals", "evolve"),
87176
+ resultsRoot: readOption(rest, "--out") ?? join33(process.cwd(), "evals", "evolve"),
86899
87177
  evidencePath: readOption(rest, "--evidence"),
86900
87178
  refreshEvidence: rest.includes("--refresh-evidence"),
86901
87179
  generations: Number(readOption(rest, "--generations") ?? 2),