@ancha-labs/cli 0.4.13 → 0.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/ancha.mjs CHANGED
@@ -33885,6 +33885,15 @@ var init_carrier_portal = __esm({
33885
33885
  }
33886
33886
  });
33887
33887
 
33888
+ // packages/core/src/tools/netsuite-money.ts
33889
+ var netsuiteRound;
33890
+ var init_netsuite_money = __esm({
33891
+ "packages/core/src/tools/netsuite-money.ts"() {
33892
+ "use strict";
33893
+ netsuiteRound = (value5) => Math.sign(value5) * Math.round(Number(`${Math.abs(value5).toFixed(10)}e2`)) / 100 || 0;
33894
+ }
33895
+ });
33896
+
33888
33897
  // packages/core/src/tools/netsuite.ts
33889
33898
  function recordNamer(seed43) {
33890
33899
  const symbols = new Map(seed43.currencies.map((c) => [c.id, c.symbol ?? c.name]));
@@ -33948,7 +33957,7 @@ function checkSeed(seed43, report9) {
33948
33957
  }
33949
33958
  function books(seed43, issue6, money18) {
33950
33959
  if (seed43.integration.customerCreditLimitHandlingOverride && !seed43.policy.allowCustomerCreditLimitHandlingOverride) issue6(["integration", "customerCreditLimitHandlingOverride"], "credit handling override requires policy permission");
33951
- const round24 = (v) => Math.sign(v) * Math.round(Number(`${Math.abs(v).toFixed(10)}e2`)) / 100 || 0;
33960
+ const round24 = netsuiteRound;
33952
33961
  const accountById = new Map(seed43.accounts.map((a) => [a.id, a])), itemById = new Map(seed43.items.map((i) => [i.id, i]));
33953
33962
  const itemTotal = (lines3) => round24(lines3.reduce((sum6, line2) => sum6 + round24(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.rate ?? 0)), 0));
33954
33963
  const buyTotal = (lines3) => round24(lines3.reduce((sum6, line2) => sum6 + round24(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.cost ?? itemById.get(line2.item)?.rate ?? 0)), 0));
@@ -34494,6 +34503,7 @@ var init_netsuite = __esm({
34494
34503
  "packages/core/src/tools/netsuite.ts"() {
34495
34504
  "use strict";
34496
34505
  init_zod();
34506
+ init_netsuite_money();
34497
34507
  NETSUITE_ACCOUNT_TYPES = [
34498
34508
  "Bank",
34499
34509
  "AcctRec",
@@ -44464,9 +44474,11 @@ function projectToolCalls(trace) {
44464
44474
  };
44465
44475
  });
44466
44476
  }
44477
+ var isAgentAnswer;
44467
44478
  var init_tool_call_trace = __esm({
44468
44479
  "packages/core/src/tool-call-trace.ts"() {
44469
44480
  "use strict";
44481
+ isAgentAnswer = (entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done";
44470
44482
  }
44471
44483
  });
44472
44484
 
@@ -44556,6 +44568,9 @@ function worldToSceneInput(world5, test3 = {}) {
44556
44568
  pass: test3.pass
44557
44569
  }).filter(([, value5]) => value5 !== void 0));
44558
44570
  }
44571
+ function worldToScene(world5, test3 = {}) {
44572
+ return parseScene(worldToSceneInput(world5, test3));
44573
+ }
44559
44574
  function worldError(issues) {
44560
44575
  return new AnchaError("SCENE_INVALID", issues.map((issue6) => `${issue6.path}: ${issue6.message}`).join("\n"), {
44561
44576
  ...issues.some((issue6) => issue6.hint) && { hint: issues.filter((issue6) => issue6.hint).map((issue6) => issues.length === 1 ? issue6.hint : `${issue6.path}: ${issue6.hint}`).join("\n") }
@@ -45122,6 +45137,7 @@ var init_evals = __esm({
45122
45137
  "packages/core/src/datasets/netsuite-pe/evals.ts"() {
45123
45138
  "use strict";
45124
45139
  init_netsuite();
45140
+ init_netsuite_money();
45125
45141
  DAY = 864e5;
45126
45142
  MONTHS2 = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
45127
45143
  cents3 = (value5) => Math.round(value5 * 100);
@@ -45139,7 +45155,7 @@ var init_evals = __esm({
45139
45155
  money8 = (code5, value5) => `${code5} ${grouped(Math.round(value5))}`;
45140
45156
  byText = (x, y) => x < y ? -1 : x > y ? 1 : 0;
45141
45157
  count2 = (n2, one7, many = `${one7}s`) => `${n2} ${n2 === 1 ? one7 : many}`;
45142
- inBase = (value5, rate) => rate === 1 ? value5 : Math.round(Number((value5 / 100 * rate).toFixed(2)) * 100);
45158
+ inBase = (value5, rate) => rate === 1 ? value5 : Math.round(netsuiteRound(value5 / 100 * rate) * 100);
45143
45159
  companyKey = (name5) => name5.toUpperCase().replace(/&/g, "AND").replace(/[^A-Z0-9]/g, "").replace(/(INC|LLC|CO|CORP|COMPANY|GROUP|PARTNERS|LTD)$/, "");
45144
45160
  KEY_SQL = (column) => `REGEXP_REPLACE(REGEXP_REPLACE(UPPER(REPLACE(${column}, '&', 'AND')), '[^A-Z0-9]', ''), '(INC|LLC|CO|CORP|COMPANY|GROUP|PARTNERS|LTD)$', '')`;
45145
45161
  }
@@ -47020,7 +47036,7 @@ var init_netsuite_pe = __esm({
47020
47036
  init_generate();
47021
47037
  init_names();
47022
47038
  init_evals();
47023
- NETSUITE_PE_VERSION = "1.0.0";
47039
+ NETSUITE_PE_VERSION = "1.0.1";
47024
47040
  NETSUITE_PE_START_TIME = "2026-11-02T14:00:00Z";
47025
47041
  NETSUITE_PE_DATASET = {
47026
47042
  kind: "generated",
@@ -166905,14 +166921,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
166905
166921
  CREATE VIEW ns_q_transactionline AS
166906
166922
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
166907
166923
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
166908
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
166924
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
166909
166925
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
166910
166926
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
166911
166927
  FROM ns_transactions t WHERE t.type <> 'Journal'
166912
166928
  UNION ALL
166913
166929
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
166914
166930
  ${signed("l.quantity", 2)}, l.rate,
166915
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
166931
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
166916
166932
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
166917
166933
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
166918
166934
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool8("l.isclosed")}, l.debit, l.credit,
@@ -167389,6 +167405,19 @@ CREATE VIEW ns_q_mediaitemfolder AS SELECT id, name, parent, description, datecr
167389
167405
  }
167390
167406
  });
167391
167407
 
167408
+ // packages/server/src/twins/netsuite/money.ts
167409
+ function registerRound(db3) {
167410
+ db3.function("ns_round", { deterministic: true }, (value5) => value5 === null || value5 === void 0 ? null : round(Number(value5)));
167411
+ }
167412
+ var round;
167413
+ var init_money = __esm({
167414
+ "packages/server/src/twins/netsuite/money.ts"() {
167415
+ "use strict";
167416
+ init_netsuite_money();
167417
+ round = netsuiteRound;
167418
+ }
167419
+ });
167420
+
167392
167421
  // packages/server/src/twins/netsuite/banking-schema.ts
167393
167422
  var isBanking, read5, list16, BANK_FIELDS, BANK_LINES;
167394
167423
  var init_banking_schema = __esm({
@@ -169972,6 +170001,7 @@ function sql2(ctx) {
169972
170001
  upgradeSchema(db3);
169973
170002
  const registered = { clock: ctx.clock };
169974
170003
  db3.function("ns_today", { deterministic: false }, () => registered.clock.now().toISOString().slice(0, 10));
170004
+ registerRound(db3);
169975
170005
  clocks.set(db3, holder = registered);
169976
170006
  }
169977
170007
  holder.clock = ctx.clock;
@@ -170730,13 +170760,14 @@ function dumpState41(ctx) {
170730
170760
  records: db3.prepare("SELECT type, id, externalid, fields FROM ns_records ORDER BY type, id").all().map((r2) => clean({ type: r2.type, id: r2.id, externalId: r2.externalid, fields: json31(r2.fields) }))
170731
170761
  };
170732
170762
  }
170733
- var RECORD_ROOT, LIST_KINDS, isTx, isItem, isEntity, isList, customerOf, vendorOf, AR, AP, FUNDS, BANK2, TX, TX_CODE, TX_LABEL, ORDERS, sublistsOf, r, w, ref21, HOLD, statusOptions, MONEY, SEGMENTS2, DATED, ENTITY, ITEM_COMMON, LIST_FIELDS, TX_BASE, party2, ADDRESSES, SALE, order4, FIELDS3, LINE_SEGMENTS, ITEM_LINE, LINE_FIELDS, clocks, today, stamp5, round, qty, addDays2, json31, config10, customFields2, entityRow, itemRow, txRow, listRow, periodRow, lineRows, allLines, unpaid, unapplied, applications, listName, termDays2, firstList, accountOfType, accountType, movesStock, nextTranId, statusText, href, selfLink, entityName, accountName, option3, PASSTHROUGH, docOpen, payable, addressBookLines, extraOwner;
170763
+ var RECORD_ROOT, LIST_KINDS, isTx, isItem, isEntity, isList, customerOf, vendorOf, AR, AP, FUNDS, BANK2, TX, TX_CODE, TX_LABEL, ORDERS, sublistsOf, r, w, ref21, HOLD, statusOptions, MONEY, SEGMENTS2, DATED, ENTITY, ITEM_COMMON, LIST_FIELDS, TX_BASE, party2, ADDRESSES, SALE, order4, FIELDS3, LINE_SEGMENTS, ITEM_LINE, LINE_FIELDS, clocks, today, stamp5, qty, addDays2, json31, config10, customFields2, entityRow, itemRow, txRow, listRow, periodRow, lineRows, allLines, unpaid, unapplied, applications, listName, termDays2, firstList, accountOfType, accountType, movesStock, nextTranId, statusText, href, selfLink, entityName, accountName, option3, PASSTHROUGH, docOpen, payable, addressBookLines, extraOwner;
170734
170764
  var init_store5 = __esm({
170735
170765
  "packages/server/src/twins/netsuite/store.ts"() {
170736
170766
  "use strict";
170737
170767
  init_open_items();
170738
170768
  init_netsuite();
170739
170769
  init_schema7();
170770
+ init_money();
170740
170771
  init_banking_schema();
170741
170772
  init_banking();
170742
170773
  init_errors6();
@@ -171057,7 +171088,6 @@ var init_store5 = __esm({
171057
171088
  clocks = /* @__PURE__ */ new WeakMap();
171058
171089
  today = (ctx) => ctx.clock.now().toISOString().slice(0, 10);
171059
171090
  stamp5 = (ctx) => ctx.clock.now().toISOString().replace(/\.\d{3}Z$/, "Z");
171060
- round = (value5) => Math.sign(value5) * Math.round(Number(`${Math.abs(value5).toFixed(10)}e2`)) / 100 || 0;
171061
171091
  qty = (value5) => Math.round(value5 * 1e8) / 1e8;
171062
171092
  addDays2 = (date11, days) => new Date(Date.parse(`${date11}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
171063
171093
  json31 = (text29) => {
@@ -171620,6 +171650,7 @@ function* matches7(re, source, position) {
171620
171650
  }
171621
171651
  }
171622
171652
  function installFunctions(db3, hierarchy) {
171653
+ registerRound(db3);
171623
171654
  const register4 = (name5, fn) => {
171624
171655
  db3.function(`ns_suiteql_${name5}`, { deterministic: true, varargs: true }, fn);
171625
171656
  };
@@ -171898,6 +171929,7 @@ var init_suiteql = __esm({
171898
171929
  "packages/server/src/twins/netsuite/suiteql.ts"() {
171899
171930
  "use strict";
171900
171931
  init_schema7();
171932
+ init_money();
171901
171933
  SuiteqlError = class extends Error {
171902
171934
  gap;
171903
171935
  constructor(message7, gap6 = false) {
@@ -173984,10 +174016,10 @@ function balanceSheet(ctx, p2) {
173984
174016
  }
173985
174017
  function openItems2(ctx, side, to, subsidiary) {
173986
174018
  return sql2(ctx).prepare(`SELECT t.id,t.type,t.tranid,t.trandate,t.duedate,i.entity,t.otherrefnum,
173987
- ROUND(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
174019
+ ns_round(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
173988
174020
  WHERE owner.trandate<=@to AND ((i.role='debt' AND a.doc=i.doc AND a.docline=i.line) OR (i.role='credit' AND a.source=i.doc AND a.sourceline=i.line))),0)
173989
174021
  - CASE WHEN i.role='credit' THEN COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment WHERE owner.trandate<=@to AND a.doc=i.doc AND a.docline=i.line),0) ELSE 0 END)
173990
- * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate),2) AS open
174022
+ * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate)) AS open
173991
174023
  FROM ns_item_original i JOIN ns_transactions t ON t.id=i.doc WHERE i.side=@side AND t.trandate<=@to AND (@subsidiary IS NULL OR i.subsidiary=@subsidiary)
173992
174024
  GROUP BY i.doc,i.entity,i.account ORDER BY t.trandate,t.id,i.account`).all({ to, side: side === "ar" ? "receivable" : "payable", subsidiary: subsidiary ?? null }).filter((row2) => row2.open !== 0);
173993
174025
  }
@@ -174896,7 +174928,7 @@ var init_searches = __esm({
174896
174928
  iso20 = (d) => d.toISOString().slice(0, 10);
174897
174929
  at2 = (y, m, d) => new Date(Date.UTC(y, m, d));
174898
174930
  SUMMARIES = ["group", "count", "sum", "avg", "min", "max"];
174899
- money15 = (value5) => value5 === void 0 ? "" : Number(value5).toFixed(2);
174931
+ money15 = (value5) => value5 === void 0 ? "" : round(Number(value5)).toFixed(2);
174900
174932
  }
174901
174933
  });
174902
174934
 
@@ -215653,6 +215685,11 @@ async function worldFile(cwd, test3, id14) {
215653
215685
  hint: `put the world at ancha/worlds/${id14}.yaml, or generate one: ancha world gen "<the company and the scenario>" --id ${id14}`
215654
215686
  });
215655
215687
  }
215688
+ async function loadWorldFile(cwd, ref22) {
215689
+ const exists7 = (path8) => access3(path8).then(() => true, () => false);
215690
+ const path7 = /\.ya?ml$/.test(ref22) && await exists7(resolve12(cwd, ref22)) ? resolve12(cwd, ref22) : join15(cwd, "ancha", "worlds", `${ref22}.yaml`);
215691
+ return await exists7(path7) ? { path: path7, world: await readWorldFile(cwd, path7) } : void 0;
215692
+ }
215656
215693
  async function readWorldFile(cwd, path7) {
215657
215694
  try {
215658
215695
  const text29 = await readFile5(path7, "utf8"), kept = parsedWorlds.get(path7);
@@ -216010,7 +216047,7 @@ async function executeRun(opts) {
216010
216047
  // A world's seed once (run-inputs.ts). Names only, never values: what a later `ancha runs upload` redacts (hosting spec §3.1).
216011
216048
  agentEnvironment: { passEnv: agent.passEnv ?? [], inheritEnv: agent.inheritEnv === true },
216012
216049
  isolation: { execution: executionDescription(agent), toolWorld: "fresh-per-attempt", agentProcess: agent.mode === "endpoint" && agent.start === void 0 ? "external-setup-adapter" : "fresh-per-attempt", agentState: agent.execution?.mode === "container" ? "fresh-container-scratch" : "provided-namespace-only", limits: agent.execution?.mode === "container" ? "Local Linux container, read-only source, bounded scratch, scoped tool gateway and explicit model hosts; not a multi-tenant cloud security certification." : "Agent files and external memory are shared unless the agent uses ANCHA_STATE_DIR or ANCHA_ATTEMPT_ID. This is not host or network isolation." }
216013
- }, null, 2)}
216050
+ })}
216014
216051
  `, { flag: "wx", mode: 384 });
216015
216052
  const kept = /* @__PURE__ */ new Map();
216016
216053
  for (const [index, item2] of cases.entries()) {
@@ -216200,9 +216237,15 @@ function logTail2(data5, cap) {
216200
216237
  if (newline !== -1 && newline < data5.length - 1) start = newline + 1;
216201
216238
  return Buffer.concat([note2(start), data5.subarray(start)]);
216202
216239
  }
216203
- function capFor(path7) {
216240
+ function capFor(path7, inputsBytes = BUNDLE_LIMITS2.largeFileBytes) {
216204
216241
  const name5 = path7.slice(path7.lastIndexOf("/") + 1);
216205
- return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : BUNDLE_LIMITS2.fileBytes;
216242
+ return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : path7 === "inputs.json" ? inputsBytes : BUNDLE_LIMITS2.fileBytes;
216243
+ }
216244
+ function readsLargeInputs(version6) {
216245
+ const match3 = /^(\d+)\.(\d+)\.(\d+)/.exec(version6 ?? "");
216246
+ if (!match3) return false;
216247
+ const [major, minor, patch] = match3.slice(1).map(Number);
216248
+ return major !== 0 ? major > 0 : minor !== 4 ? minor > 4 : patch >= 14;
216206
216249
  }
216207
216250
  async function runFiles(runDir, source) {
216208
216251
  const root3 = await readdir3(runDir, { withFileTypes: true });
@@ -216223,7 +216266,7 @@ async function packRun(options4) {
216223
216266
  const entries4 = [], omitted = [];
216224
216267
  for (const path7 of paths2) {
216225
216268
  let data5 = redact(await readFile8(join20(options4.runDir, path7)), options4.secrets);
216226
- const cap = capFor(path7);
216269
+ const cap = capFor(path7, options4.inputsBytes);
216227
216270
  if (data5.length > cap) {
216228
216271
  if (path7.endsWith("/agent.log")) data5 = logTail2(data5, cap);
216229
216272
  else if (options4.source === "cloud" && MANDATORY_CLOUD_PATH.test(path7)) throw tooBig2(`run ${options4.runId}: ${path7} is ${data5.length} bytes; a run keeps at most ${cap}`);
@@ -216576,7 +216619,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
216576
216619
  }
216577
216620
  }
216578
216621
  for (const e of projectToolCalls(t.trace)) {
216579
- if (e.source === "agent") agentCalls2++;
216622
+ if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
216580
216623
  if (e.gap === true) {
216581
216624
  const key4 = JSON.stringify([e.service, e.method, e.path]);
216582
216625
  const gap6 = gaps2.get(key4);
@@ -221237,13 +221280,13 @@ function endedSentence(view3) {
221237
221280
  return view3.exitCode === null ? `The agent stopped on a signal after ${view3.realMs} ms.` : `The agent exited with code ${view3.exitCode} after ${view3.realMs} ms.`;
221238
221281
  }
221239
221282
  function attemptOutcome(view3, ctx) {
221240
- const calls2 = view3.trace.filter((entry3) => entry3.source === "agent" && !isAnswer(entry3));
221283
+ const calls2 = view3.trace.filter((entry3) => entry3.source === "agent" && !isAgentAnswer(entry3));
221241
221284
  const netsuite = calls2.filter((entry3) => entry3.service === "netsuite");
221242
221285
  const unserved = netsuite.filter((entry3) => entry3.gap === true || kindOf2(entry3.path) === "restlet" || kindOf2(entry3.path) === "soap");
221243
221286
  const used = netsuite.filter((entry3) => !unserved.includes(entry3)), data5 = used.filter((entry3) => kindOf2(entry3.path) !== "auth");
221244
221287
  const served = used.filter((entry3) => entry3.status !== void 0 && entry3.status < 400);
221245
221288
  const hosts = netsuiteHosts(view3.log);
221246
- const done = view3.trace.findLast(isAnswer), answer = done === void 0 ? void 0 : answerOf(done);
221289
+ const done = view3.trace.findLast(isAgentAnswer), answer = done === void 0 ? void 0 : answerOf(done);
221247
221290
  const byStatus = {};
221248
221291
  for (const entry3 of calls2) if (entry3.status !== void 0) byStatus[String(entry3.status)] = (byStatus[String(entry3.status)] ?? 0) + 1;
221249
221292
  const gaps2 = [...new Set(calls2.filter((entry3) => entry3.gap === true || unserved.includes(entry3)).map((entry3) => `${entry3.method} ${entry3.path}`))];
@@ -221289,13 +221332,12 @@ function attemptOutcome(view3, ctx) {
221289
221332
  }
221290
221333
  return out({ code: "answered", level: "pass", message: `It answered ${quoted3(answer.text)}.` });
221291
221334
  }
221292
- var isAnswer, oneLine4, quoted3, times, list17, NETSUITE_HOST, netsuiteHosts, customers2, words6, PROVIDER_KEYS, SIGN, OUTSIDE, SERVED, NO_ANSWER, POST_ANSWER;
221335
+ var oneLine4, quoted3, times, list17, NETSUITE_HOST, netsuiteHosts, customers2, words6, PROVIDER_KEYS, SIGN, OUTSIDE, SERVED, NO_ANSWER, POST_ANSWER;
221293
221336
  var init_agent_outcome = __esm({
221294
221337
  "backend/src/agent-outcome.ts"() {
221295
221338
  "use strict";
221296
221339
  init_src();
221297
221340
  init_agent_fix();
221298
- isAnswer = (entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done";
221299
221341
  oneLine4 = (text29) => text29.replace(/\s+/g, " ").trim();
221300
221342
  quoted3 = (text29) => {
221301
221343
  const line2 = oneLine4(text29);
@@ -221596,8 +221638,9 @@ function finalizeInput(value5) {
221596
221638
  if (missing8 !== void 0) wrong(`has no ${what}.${missing8}`);
221597
221639
  return v;
221598
221640
  };
221599
- const input4 = fields11(value5, "input", ["version", "jobId", "bundleHash", "workspace", "startedAt", "finishedAt", "terminalIntent", "options", "attempts", "execution", "provenance", "requestedConcurrency", "effectiveConcurrency", "observedPeakConcurrency", "caps"]);
221641
+ const input4 = fields11(value5, "input", ["version", "jobId", "bundleHash", "workspace", "startedAt", "finishedAt", "terminalIntent", "options", "attempts", "execution", "provenance", "requestedConcurrency", "effectiveConcurrency", "observedPeakConcurrency", "caps"], ["cliVersion"]);
221600
221642
  if (input4.version !== 1) wrong(`has version ${JSON.stringify(input4.version)}`);
221643
+ if (input4.cliVersion !== void 0 && typeof input4.cliVersion !== "string") wrong("names a CLI version that is not one");
221601
221644
  if (typeof input4.jobId !== "string" || !CLOUD_RUN_ID.test(input4.jobId)) wrong("names no cloud run");
221602
221645
  if (typeof input4.bundleHash !== "string" || !SHA256.test(input4.bundleHash)) wrong("has no bundle hash");
221603
221646
  if (typeof input4.workspace !== "string" || !/^[a-z0-9][a-z0-9-]{0,99}$/.test(input4.workspace)) wrong("names no workspace");
@@ -221835,7 +221878,7 @@ async function assembleCloudRun(options4) {
221835
221878
  const value5 = { id: item2.caseId, scenarioId: item2.scene.id, seed: item2.seed, compiledFingerprint: sceneFingerprint(item2.scene), identity: {} };
221836
221879
  return { ...value5, fingerprint: sceneFingerprint(value5), scene: item2.scene };
221837
221880
  });
221838
- await writeFile18(join42(runDir, "inputs.json"), `${JSON.stringify({ schemaVersion: 1, cases: sharedSeeds(frozen), isolation: { execution: "cloud", toolWorld: "fresh-per-attempt", agentProcess: "fresh-machine-per-attempt", agentState: "fresh-machine-per-attempt" } }, null, 2)}
221881
+ await writeFile18(join42(runDir, "inputs.json"), `${JSON.stringify({ schemaVersion: 1, cases: sharedSeeds(frozen), isolation: { execution: "cloud", toolWorld: "fresh-per-attempt", agentProcess: "fresh-machine-per-attempt", agentState: "fresh-machine-per-attempt" } })}
221839
221882
  `, { flag: "wx", mode: 384 });
221840
221883
  const results = new Map(cases.map((item2) => [item2.caseId, { scene: item2.scene, trials: [], requestedTrials: resolved.attempts, ...item2.records !== void 0 && { records: item2.records } }]));
221841
221884
  for (const item2 of cases) {
@@ -221882,7 +221925,16 @@ async function assembleCloudRun(options4) {
221882
221925
  await writeFile18(join42(runDir, "reproduction.json"), json35(summary.reproduction), { flag: "wx", mode: 384 });
221883
221926
  await writeFile18(join42(runDir, "cloud.json"), json35({ version: 1, jobId: runId2, bundleHash: input4.bundleHash, startedAt: input4.startedAt, finishedAt: input4.finishedAt, terminalIntent: input4.terminalIntent, attempts: input4.attempts }), { flag: "wx", mode: 384 });
221884
221927
  await writeFile18(join42(runDir, "summary.json"), json35(summary), { flag: "wx", mode: 384 });
221885
- const { archive } = await packRun({ runDir, runId: runId2, createdAt: input4.startedAt, source: "cloud", cli: options4.cli ?? "", project: { name: manifest2.agentName, git: null }, secrets: [] });
221928
+ const { archive } = await packRun({
221929
+ runDir,
221930
+ runId: runId2,
221931
+ createdAt: input4.startedAt,
221932
+ source: "cloud",
221933
+ cli: options4.cli ?? "",
221934
+ project: { name: manifest2.agentName, git: null },
221935
+ secrets: [],
221936
+ inputsBytes: readsLargeInputs(input4.cliVersion) ? BUNDLE_LIMITS2.largeFileBytes : BUNDLE_LIMITS2.fileBytes
221937
+ });
221886
221938
  const archivePath = join42(options4.outDir, `${runId2}.tar.gz`);
221887
221939
  await writeFile18(archivePath, archive, { flag: "wx", mode: 384 });
221888
221940
  return { archivePath, sha256: sha2565(archive), runId: runId2, exitCode: summary.exitCode, verdict: summary.verdict };
@@ -232125,7 +232177,7 @@ var PlaygroundService = class {
232125
232177
  if (event3.error !== void 0) attempt.error = event3.error.slice(0, 4e3);
232126
232178
  const previous = await this.store.evidence(run6.id, attempt.id);
232127
232179
  const trace = event3.trace ?? previous?.trace ?? [];
232128
- attempt.toolCalls = trace.length;
232180
+ attempt.toolCalls = trace.filter((entry3) => !isAgentAnswer(entry3)).length;
232129
232181
  const snapshot = event3.snapshot;
232130
232182
  const state3 = snapshot ? snapshot.state ?? snapshot : previous?.state;
232131
232183
  const harnessIssues = snapshot?.harnessIssues ?? event3.harnessIssues ?? previous?.harnessIssues;
@@ -234139,8 +234191,11 @@ async function loadReplayAttempt(cwd, ref22, out) {
234139
234191
  try {
234140
234192
  inputs2 = JSON.parse(await readFile32(join46(runDir, "inputs.json"), "utf8"));
234141
234193
  } catch (error65) {
234142
- if (missing7(error65)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${out ?? DEFAULT_RUNS_DIR}/`, cause: error65 });
234143
- throw error65;
234194
+ if (!missing7(error65)) throw error65;
234195
+ const left = await readFile32(join46(runDir, "bundle.json"), "utf8").then((text29) => JSON.parse(text29).omitted?.find((item2) => item2.path === "inputs.json")).catch(() => void 0);
234196
+ const mb = (bytes3) => `${(bytes3 / (1024 * 1024)).toFixed(1)} MB`;
234197
+ if (left) throw new AnchaError("USAGE", `run ${runId2} came without its inputs.json (${mb(left.bytes)}, past the ${mb(left.cap)} its archive kept), so replay can't rebuild its worlds`, { hint: "a run started with ancha 0.4.14 or later keeps an inputs.json up to 12 MB: run the tests again, then replay the new run", cause: error65 });
234198
+ throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${out ?? DEFAULT_RUNS_DIR}/`, cause: error65 });
234144
234199
  }
234145
234200
  const trials = (await readdir7(runDir).catch(() => [])).filter((name5) => TRIAL_DIR.test(name5)).sort();
234146
234201
  if (!TRIAL_DIR.test(trialDir) || !trials.includes(trialDir)) {
@@ -234244,6 +234299,8 @@ function registerReplay(program2, ctx) {
234244
234299
  if (opts.people !== void 0 && opts.people !== "live" && opts.people !== "strict") {
234245
234300
  throw new AnchaError("USAGE", `--people takes live or strict, not ${opts.people}`, { hint: "ancha replay latest/trial-<test>-1 --people strict" });
234246
234301
  }
234302
+ const runId2 = ref22.split("/")[0];
234303
+ if (/^run_cloud_/.test(runId2)) await cachedCloudRun(ctx, runId2, resolve36(cwd, opts.out ?? DEFAULT_RUNS_DIR));
234247
234304
  const attempt = await loadReplayAttempt(cwd, ref22, opts.out);
234248
234305
  const config11 = await ctx.loadConfig();
234249
234306
  const resolved = resolveRunAgent(config11, cwd, { ...opts.agent !== void 0 && { agent: opts.agent } });
@@ -238861,7 +238918,15 @@ var CliRuns = class {
238861
238918
  const raw3 = JSON.parse(rawChecks);
238862
238919
  checks2 = Array.isArray(raw3) ? raw3 : Array.isArray(raw3?.checks) ? raw3.checks : [];
238863
238920
  }
238864
- const toolCalls = (await optional2("trace.jsonl", 12e6) ?? "").split("\n").filter((line2) => line2.includes('"source":"agent"')).length;
238921
+ const toolCalls = (await optional2("trace.jsonl", 12e6) ?? "").split("\n").filter((line2) => {
238922
+ if (!line2.trim()) return false;
238923
+ try {
238924
+ const entry3 = JSON.parse(line2);
238925
+ return entry3?.source === "agent" && !isAgentAnswer(entry3);
238926
+ } catch {
238927
+ return false;
238928
+ }
238929
+ }).length;
238865
238930
  let response5;
238866
238931
  try {
238867
238932
  const text29 = await optional2("result.json", 4e6);
@@ -257178,14 +257243,23 @@ function agentVariables(info, scene2) {
257178
257243
  return { ...toolConnectionEnvironment(info.services), ...mcpConnectionEnvironment(info.mcp), ANCHA_ENV_ID: info.id, ...scene2 !== void 0 && { ANCHA_SCENE_ID: scene2.id, ANCHA_TASK: scene2.task } };
257179
257244
  }
257180
257245
  function registerWorldLifecycle(world5, ctx) {
257181
- world5.command("up").description("start a fresh world for your own harness: prints its tools' URLs and fake credentials").option("--scene <file>", "test file (scene.yaml) to start (default: the one test ancha.yaml names)").option("--test <file>", "test file to start; same as --scene").option("--world <id>", "a saved world from ancha world list").option("--on <where>", "local (this computer) or cloud (your workspace); default: the server --server-url, server.url or ANCHA_SERVER_URL names, else this computer").option("--seed <seed>", 'seed for ids and data (default: "<test id>:1")').option("--ttl <duration>", "remove the world after this long with no call from the agent and no ancha world or ancha check command on it", DEFAULT_TTL).action(async (opts) => {
257246
+ world5.command("up").description("start a fresh world for your own harness: prints its tools' URLs and fake credentials").option("--scene <file>", "test file (scene.yaml) to start (default: the one test ancha.yaml names)").option("--test <file>", "test file to start; same as --scene").option("--world <id>", "a world file (ancha/worlds/<id>.yaml) by id or path, or a saved world from ancha world list").option("--on <where>", "local (this computer) or cloud (your workspace); default: the server --server-url, server.url or ANCHA_SERVER_URL names, else this computer").option("--seed <seed>", 'seed for ids and data (default: "<test id>:1")').option("--ttl <duration>", "remove the world after this long with no call from the agent and no ancha world or ancha check command on it", DEFAULT_TTL).action(async (opts) => {
257182
257247
  if ([opts.scene, opts.test, opts.world].filter((value5) => value5 !== void 0).length > 1) throw new AnchaError("USAGE", "choose one of --scene, --test or --world");
257183
257248
  const ttlMs = ttl(opts.ttl);
257249
+ const fileWorld = opts.world !== void 0 ? await loadWorldFile(ctx.io.cwd, opts.world) : void 0;
257184
257250
  const where3 = await target4(ctx, opts.on);
257185
257251
  let scene2, scenePath, configuration, definition3;
257186
- if (opts.world !== void 0) {
257252
+ if (fileWorld !== void 0) {
257253
+ scene2 = worldToScene(fileWorld.world);
257254
+ definition3 = { scene: scene2 };
257255
+ } else if (opts.world !== void 0) {
257187
257256
  let saved;
257188
257257
  if (where3.local || isLoopbackUrl(where3.serverUrl)) {
257258
+ if (!/^world_[a-f0-9-]{36}$/.test(opts.world)) {
257259
+ throw new AnchaError("USAGE", `no world ${opts.world}: no ancha/worlds/${opts.world}.yaml, and ${opts.world} is not a saved world id (world_\u2026)`, {
257260
+ hint: "ancha world list shows saved worlds; world files are in ancha/worlds/ (ancha world gen --dataset netsuite-pe writes one)"
257261
+ });
257262
+ }
257189
257263
  saved = await withService(ctx, (service) => service.world(opts.world));
257190
257264
  } else {
257191
257265
  const key4 = await apiKeyFor(where3.serverUrl, ctx.io.env);
@@ -257206,7 +257280,7 @@ function registerWorldLifecycle(world5, ctx) {
257206
257280
  ctx.out.notice(where3.line);
257207
257281
  const backend = await openBackend({ serverUrl: where3.serverUrl, ...where3.controlToken !== void 0 && { controlToken: where3.controlToken } });
257208
257282
  try {
257209
- const seed43 = opts.seed ?? (opts.world !== void 0 ? "world-1" : void 0);
257283
+ const seed43 = opts.seed ?? (opts.world !== void 0 && fileWorld === void 0 ? "world-1" : void 0);
257210
257284
  const info = scene2 !== void 0 ? await backend.createEnv(scene2, seed43, { ttlMs }) : await backend.createSandbox(configuration, seed43, { ttlMs });
257211
257285
  await recordWorld(ctx.io.cwd, info.id, { serverUrl: where3.serverUrl, workspace: where3.workspace, local: where3.local, ...scenePath !== void 0 && { scene: scenePath }, definition: definition3, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
257212
257286
  const lease = await backend.renewEnv(info.id);
@@ -259521,7 +259595,7 @@ function artifacts(record28, runDir) {
259521
259595
  if (excluded2(attempt.outcome)) scene2.warnings.push({ trial: attempt.number, check: "pytest", message: `${attempt.outcome}: excluded from grading` });
259522
259596
  if (observed.length > 1) scene2.warnings.push({ trial: attempt.number, check: "pytest", message: "This attempt used multiple worlds; state.json and trace.jsonl show the first captured world. All captures are in world-observations.json." });
259523
259597
  const trace = Array.isArray(primary3?.trace) ? primary3.trace : [];
259524
- scene2.agentCalls += attempt.worlds.reduce((sum6, world5) => sum6 + (Array.isArray(world5.capture?.observation.trace) ? world5.capture.observation.trace.filter((entry3) => entry3?.source === "agent").length : 0), 0);
259598
+ scene2.agentCalls += attempt.worlds.reduce((sum6, world5) => sum6 + (Array.isArray(world5.capture?.observation.trace) ? world5.capture.observation.trace.filter((entry3) => entry3?.source === "agent" && !isAgentAnswer(entry3)).length : 0), 0);
259525
259599
  files2.set(`${base3}/checks.json`, json34(checks2));
259526
259600
  files2.set(`${base3}/result.json`, json34({ source: "pytest", outcome: attempt.outcome, reportedOutcome: record28.attempts.find((item2) => item2.number === attempt.number).outcome, startedAt: attempt.startedAt, finishedAt: attempt.finishedAt, errors: attemptErrors(attempt), capture: primary3 ? "observation" : "none" }));
259527
259601
  files2.set(`${base3}/world-observations.json`, json34(attempt.worlds));
@@ -260140,7 +260214,7 @@ var vendorBase = (service) => VENDOR_API_BASES[service] ?? `https://${service}.i
260140
260214
  function attemptToIr(entries4, traceId, agent, saved) {
260141
260215
  const records4 = [];
260142
260216
  for (const e of projectToolCalls(entries4)) {
260143
- if (e.source === "agent" && e.service === "agent" && e.path === "/done") continue;
260217
+ if (isAgentAnswer(e)) continue;
260144
260218
  if (e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/")) {
260145
260219
  const response5 = e.response;
260146
260220
  records4.push({
@@ -85210,6 +85210,9 @@ function carrierPortalSeedRecords(seed43) {
85210
85210
  ];
85211
85211
  }
85212
85212
 
85213
+ // packages/core/src/tools/netsuite-money.ts
85214
+ var netsuiteRound = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
85215
+
85213
85216
  // packages/core/src/tools/netsuite.ts
85214
85217
  var NETSUITE_ACCOUNT_TYPES = [
85215
85218
  "Bank",
@@ -85715,7 +85718,7 @@ function checkSeed(seed43, report3) {
85715
85718
  }
85716
85719
  function books(seed43, issue6, money13) {
85717
85720
  if (seed43.integration.customerCreditLimitHandlingOverride && !seed43.policy.allowCustomerCreditLimitHandlingOverride) issue6(["integration", "customerCreditLimitHandlingOverride"], "credit handling override requires policy permission");
85718
- const round2 = (v) => Math.sign(v) * Math.round(Number(`${Math.abs(v).toFixed(10)}e2`)) / 100 || 0;
85721
+ const round2 = netsuiteRound;
85719
85722
  const accountById = new Map(seed43.accounts.map((a) => [a.id, a])), itemById = new Map(seed43.items.map((i) => [i.id, i]));
85720
85723
  const itemTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.rate ?? 0)), 0));
85721
85724
  const buyTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.cost ?? itemById.get(line2.item)?.rate ?? 0)), 0));
@@ -141667,14 +141670,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
141667
141670
  CREATE VIEW ns_q_transactionline AS
141668
141671
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
141669
141672
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
141670
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
141673
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
141671
141674
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
141672
141675
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
141673
141676
  FROM ns_transactions t WHERE t.type <> 'Journal'
141674
141677
  UNION ALL
141675
141678
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
141676
141679
  ${signed("l.quantity", 2)}, l.rate,
141677
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
141680
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
141678
141681
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
141679
141682
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
141680
141683
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool8("l.isclosed")}, l.debit, l.credit,
@@ -142297,6 +142300,12 @@ function upgradeSchema(db3) {
142297
142300
  })();
142298
142301
  }
142299
142302
 
142303
+ // packages/server/src/twins/netsuite/money.ts
142304
+ var round = netsuiteRound;
142305
+ function registerRound(db3) {
142306
+ db3.function("ns_round", { deterministic: true }, (value4) => value4 === null || value4 === void 0 ? null : round(Number(value4)));
142307
+ }
142308
+
142300
142309
  // packages/server/src/twins/netsuite/banking-schema.ts
142301
142310
  var isBanking = (type) => ["bankingTransaction", "bankRecSuggestion", "transactionMatch"].includes(type);
142302
142311
  var read2 = (kind, target4) => ({ kind, ...target4 && { target: target4 } });
@@ -145124,6 +145133,7 @@ function sql(ctx) {
145124
145133
  upgradeSchema(db3);
145125
145134
  const registered = { clock: ctx.clock };
145126
145135
  db3.function("ns_today", { deterministic: false }, () => registered.clock.now().toISOString().slice(0, 10));
145136
+ registerRound(db3);
145127
145137
  clocks.set(db3, holder = registered);
145128
145138
  }
145129
145139
  holder.clock = ctx.clock;
@@ -145131,7 +145141,6 @@ function sql(ctx) {
145131
145141
  }
145132
145142
  var today = (ctx) => ctx.clock.now().toISOString().slice(0, 10);
145133
145143
  var stamp5 = (ctx) => ctx.clock.now().toISOString().replace(/\.\d{3}Z$/, "Z");
145134
- var round = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
145135
145144
  var qty = (value4) => Math.round(value4 * 1e8) / 1e8;
145136
145145
  var addDays = (date10, days) => new Date(Date.parse(`${date10}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
145137
145146
  var json31 = (text23) => {
@@ -147507,6 +147516,7 @@ var nth = (re, source, position, occurrence) => {
147507
147516
  return void 0;
147508
147517
  };
147509
147518
  function installFunctions(db3, hierarchy) {
147519
+ registerRound(db3);
147510
147520
  const register3 = (name5, fn) => {
147511
147521
  db3.function(`ns_suiteql_${name5}`, { deterministic: true, varargs: true }, fn);
147512
147522
  };
@@ -148754,10 +148764,10 @@ function balanceSheet(ctx, p2) {
148754
148764
  }
148755
148765
  function openItems2(ctx, side, to, subsidiary) {
148756
148766
  return sql(ctx).prepare(`SELECT t.id,t.type,t.tranid,t.trandate,t.duedate,i.entity,t.otherrefnum,
148757
- ROUND(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
148767
+ ns_round(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
148758
148768
  WHERE owner.trandate<=@to AND ((i.role='debt' AND a.doc=i.doc AND a.docline=i.line) OR (i.role='credit' AND a.source=i.doc AND a.sourceline=i.line))),0)
148759
148769
  - CASE WHEN i.role='credit' THEN COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment WHERE owner.trandate<=@to AND a.doc=i.doc AND a.docline=i.line),0) ELSE 0 END)
148760
- * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate),2) AS open
148770
+ * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate)) AS open
148761
148771
  FROM ns_item_original i JOIN ns_transactions t ON t.id=i.doc WHERE i.side=@side AND t.trandate<=@to AND (@subsidiary IS NULL OR i.subsidiary=@subsidiary)
148762
148772
  GROUP BY i.doc,i.entity,i.account ORDER BY t.trandate,t.id,i.account`).all({ to, side: side === "ar" ? "receivable" : "payable", subsidiary: subsidiary ?? null }).filter((row2) => row2.open !== 0);
148763
148773
  }
@@ -149546,7 +149556,7 @@ function expression2(ctx, type, filters, params10, plan4) {
149546
149556
  return out.join(" ");
149547
149557
  }
149548
149558
  var SUMMARIES = ["group", "count", "sum", "avg", "min", "max"];
149549
- var money12 = (value4) => value4 === void 0 ? "" : Number(value4).toFixed(2);
149559
+ var money12 = (value4) => value4 === void 0 ? "" : round(Number(value4)).toFixed(2);
149550
149560
  function listSearches(ctx, args) {
149551
149561
  const needle = args.query?.trim().toLowerCase();
149552
149562
  return { success: true, savedSearches: (config10(ctx).savedSearches ?? []).filter((s2) => !needle || s2.title.toLowerCase().includes(needle) || s2.id.includes(needle)).map((s2) => ({ id: s2.id, internalId: s2.internalId, title: s2.title, recordType: s2.type, isPublic: s2.isPublic })) };
@@ -204,14 +204,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
204
204
  CREATE VIEW ns_q_transactionline AS
205
205
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
206
206
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
207
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
207
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
208
208
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
209
209
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
210
210
  FROM ns_transactions t WHERE t.type <> 'Journal'
211
211
  UNION ALL
212
212
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
213
213
  ${signed("l.quantity", 2)}, l.rate,
214
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
214
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
215
215
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
216
216
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
217
217
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool("l.isclosed")}, l.debit, l.credit,
@@ -787,6 +787,15 @@ var DISPLAY = {
787
787
  shipstatus: { A: "Picked", B: "Packed", C: "Shipped" }
788
788
  };
789
789
 
790
+ // packages/core/src/tools/netsuite-money.ts
791
+ var netsuiteRound = (value) => Math.sign(value) * Math.round(Number(`${Math.abs(value).toFixed(10)}e2`)) / 100 || 0;
792
+
793
+ // packages/server/src/twins/netsuite/money.ts
794
+ var round = netsuiteRound;
795
+ function registerRound(db) {
796
+ db.function("ns_round", { deterministic: true }, (value) => value === null || value === void 0 ? null : round(Number(value)));
797
+ }
798
+
790
799
  // packages/server/src/twins/netsuite/suiteql.ts
791
800
  var SuiteqlError = class extends Error {
792
801
  gap;
@@ -2329,6 +2338,7 @@ var nth = (re, source, position, occurrence) => {
2329
2338
  return void 0;
2330
2339
  };
2331
2340
  function installFunctions(db, hierarchy) {
2341
+ registerRound(db);
2332
2342
  const register = (name, fn) => {
2333
2343
  db.function(`ns_suiteql_${name}`, { deterministic: true, varargs: true }, fn);
2334
2344
  };
package/lib/mcp-entry.mjs CHANGED
@@ -65632,6 +65632,9 @@ var carrierPortalStarterSeed = {
65632
65632
  messages: [{ id: "welcome", policy: "LM-10042", request: "LMR-PRIOR-01", subject: "Mailing address confirmed", body: "The requested mailing address has been approved." }]
65633
65633
  };
65634
65634
 
65635
+ // packages/core/src/tools/netsuite-money.ts
65636
+ var netsuiteRound = (value2) => Math.sign(value2) * Math.round(Number(`${Math.abs(value2).toFixed(10)}e2`)) / 100 || 0;
65637
+
65635
65638
  // packages/core/src/tools/netsuite.ts
65636
65639
  var NETSUITE_ACCOUNT_TYPES = [
65637
65640
  "Bank",
@@ -66136,7 +66139,7 @@ function checkSeed(seed2, report) {
66136
66139
  }
66137
66140
  function books(seed2, issue2, money8) {
66138
66141
  if (seed2.integration.customerCreditLimitHandlingOverride && !seed2.policy.allowCustomerCreditLimitHandlingOverride) issue2(["integration", "customerCreditLimitHandlingOverride"], "credit handling override requires policy permission");
66139
- const round2 = (v) => Math.sign(v) * Math.round(Number(`${Math.abs(v).toFixed(10)}e2`)) / 100 || 0;
66142
+ const round2 = netsuiteRound;
66140
66143
  const accountById = new Map(seed2.accounts.map((a) => [a.id, a])), itemById = new Map(seed2.items.map((i) => [i.id, i]));
66141
66144
  const itemTotal = (lines2) => round2(lines2.reduce((sum, line2) => sum + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.rate ?? 0)), 0));
66142
66145
  const buyTotal = (lines2) => round2(lines2.reduce((sum, line2) => sum + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.cost ?? itemById.get(line2.item)?.rate ?? 0)), 0));
@@ -204,14 +204,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
204
204
  CREATE VIEW ns_q_transactionline AS
205
205
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
206
206
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
207
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
207
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
208
208
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
209
209
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
210
210
  FROM ns_transactions t WHERE t.type <> 'Journal'
211
211
  UNION ALL
212
212
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
213
213
  ${signed("l.quantity", 2)}, l.rate,
214
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
214
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
215
215
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
216
216
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
217
217
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool("l.isclosed")}, l.debit, l.credit,
@@ -787,6 +787,15 @@ var DISPLAY = {
787
787
  shipstatus: { A: "Picked", B: "Packed", C: "Shipped" }
788
788
  };
789
789
 
790
+ // packages/core/src/tools/netsuite-money.ts
791
+ var netsuiteRound = (value) => Math.sign(value) * Math.round(Number(`${Math.abs(value).toFixed(10)}e2`)) / 100 || 0;
792
+
793
+ // packages/server/src/twins/netsuite/money.ts
794
+ var round = netsuiteRound;
795
+ function registerRound(db) {
796
+ db.function("ns_round", { deterministic: true }, (value) => value === null || value === void 0 ? null : round(Number(value)));
797
+ }
798
+
790
799
  // packages/server/src/twins/netsuite/suiteql.ts
791
800
  var SuiteqlError = class extends Error {
792
801
  gap;
@@ -2329,6 +2338,7 @@ var nth = (re, source, position, occurrence) => {
2329
2338
  return void 0;
2330
2339
  };
2331
2340
  function installFunctions(db, hierarchy) {
2341
+ registerRound(db);
2332
2342
  const register = (name, fn) => {
2333
2343
  db.function(`ns_suiteql_${name}`, { deterministic: true, varargs: true }, fn);
2334
2344
  };
package/lib/worker.mjs CHANGED
@@ -30022,6 +30022,15 @@ var init_carrier_portal = __esm({
30022
30022
  }
30023
30023
  });
30024
30024
 
30025
+ // packages/core/src/tools/netsuite-money.ts
30026
+ var netsuiteRound;
30027
+ var init_netsuite_money = __esm({
30028
+ "packages/core/src/tools/netsuite-money.ts"() {
30029
+ "use strict";
30030
+ netsuiteRound = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
30031
+ }
30032
+ });
30033
+
30025
30034
  // packages/core/src/tools/netsuite.ts
30026
30035
  function recordNamer(seed43) {
30027
30036
  const symbols = new Map(seed43.currencies.map((c) => [c.id, c.symbol ?? c.name]));
@@ -30085,7 +30094,7 @@ function checkSeed(seed43, report3) {
30085
30094
  }
30086
30095
  function books(seed43, issue6, money13) {
30087
30096
  if (seed43.integration.customerCreditLimitHandlingOverride && !seed43.policy.allowCustomerCreditLimitHandlingOverride) issue6(["integration", "customerCreditLimitHandlingOverride"], "credit handling override requires policy permission");
30088
- const round2 = (v) => Math.sign(v) * Math.round(Number(`${Math.abs(v).toFixed(10)}e2`)) / 100 || 0;
30097
+ const round2 = netsuiteRound;
30089
30098
  const accountById = new Map(seed43.accounts.map((a) => [a.id, a])), itemById = new Map(seed43.items.map((i) => [i.id, i]));
30090
30099
  const itemTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.rate ?? 0)), 0));
30091
30100
  const buyTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.cost ?? itemById.get(line2.item)?.rate ?? 0)), 0));
@@ -30603,6 +30612,7 @@ var init_netsuite = __esm({
30603
30612
  "packages/core/src/tools/netsuite.ts"() {
30604
30613
  "use strict";
30605
30614
  init_zod();
30615
+ init_netsuite_money();
30606
30616
  NETSUITE_ACCOUNT_TYPES = [
30607
30617
  "Bank",
30608
30618
  "AcctRec",
@@ -40531,9 +40541,11 @@ function projectToolCalls(trace) {
40531
40541
  };
40532
40542
  });
40533
40543
  }
40544
+ var isAgentAnswer;
40534
40545
  var init_tool_call_trace = __esm({
40535
40546
  "packages/core/src/tool-call-trace.ts"() {
40536
40547
  "use strict";
40548
+ isAgentAnswer = (entry2) => entry2.source === "agent" && entry2.service === "agent" && entry2.path === "/done";
40537
40549
  }
40538
40550
  });
40539
40551
 
@@ -40635,6 +40647,7 @@ var init_evals = __esm({
40635
40647
  "packages/core/src/datasets/netsuite-pe/evals.ts"() {
40636
40648
  "use strict";
40637
40649
  init_netsuite();
40650
+ init_netsuite_money();
40638
40651
  }
40639
40652
  });
40640
40653
 
@@ -159595,14 +159608,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
159595
159608
  CREATE VIEW ns_q_transactionline AS
159596
159609
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
159597
159610
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
159598
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
159611
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
159599
159612
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
159600
159613
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
159601
159614
  FROM ns_transactions t WHERE t.type <> 'Journal'
159602
159615
  UNION ALL
159603
159616
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
159604
159617
  ${signed("l.quantity", 2)}, l.rate,
159605
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
159618
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
159606
159619
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
159607
159620
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
159608
159621
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool8("l.isclosed")}, l.debit, l.credit,
@@ -160079,6 +160092,19 @@ CREATE VIEW ns_q_mediaitemfolder AS SELECT id, name, parent, description, datecr
160079
160092
  }
160080
160093
  });
160081
160094
 
160095
+ // packages/server/src/twins/netsuite/money.ts
160096
+ function registerRound(db3) {
160097
+ db3.function("ns_round", { deterministic: true }, (value4) => value4 === null || value4 === void 0 ? null : round(Number(value4)));
160098
+ }
160099
+ var round;
160100
+ var init_money = __esm({
160101
+ "packages/server/src/twins/netsuite/money.ts"() {
160102
+ "use strict";
160103
+ init_netsuite_money();
160104
+ round = netsuiteRound;
160105
+ }
160106
+ });
160107
+
160082
160108
  // packages/server/src/twins/netsuite/banking-schema.ts
160083
160109
  var isBanking, read5, list15, BANK_FIELDS, BANK_LINES;
160084
160110
  var init_banking_schema = __esm({
@@ -162662,6 +162688,7 @@ function sql(ctx) {
162662
162688
  upgradeSchema(db3);
162663
162689
  const registered = { clock: ctx.clock };
162664
162690
  db3.function("ns_today", { deterministic: false }, () => registered.clock.now().toISOString().slice(0, 10));
162691
+ registerRound(db3);
162665
162692
  clocks.set(db3, holder = registered);
162666
162693
  }
162667
162694
  holder.clock = ctx.clock;
@@ -163420,13 +163447,14 @@ function dumpState41(ctx) {
163420
163447
  records: db3.prepare("SELECT type, id, externalid, fields FROM ns_records ORDER BY type, id").all().map((r2) => clean({ type: r2.type, id: r2.id, externalId: r2.externalid, fields: json31(r2.fields) }))
163421
163448
  };
163422
163449
  }
163423
- var RECORD_ROOT, LIST_KINDS, isTx, isItem, isEntity, isList, customerOf, vendorOf, AR, AP, FUNDS, BANK2, TX, TX_CODE, TX_LABEL, ORDERS, sublistsOf, r, w, ref21, HOLD, statusOptions, MONEY, SEGMENTS2, DATED, ENTITY, ITEM_COMMON, LIST_FIELDS, TX_BASE, party2, ADDRESSES, SALE, order4, FIELDS3, LINE_SEGMENTS, ITEM_LINE, LINE_FIELDS, clocks, today, stamp5, round, qty, addDays, json31, config10, customFields2, entityRow, itemRow, txRow, listRow, periodRow, lineRows, allLines, unpaid, unapplied, applications, listName, termDays, firstList, accountOfType, accountType, movesStock, nextTranId, statusText, href, selfLink, entityName, accountName, option3, PASSTHROUGH, docOpen, payable, addressBookLines, extraOwner;
163450
+ var RECORD_ROOT, LIST_KINDS, isTx, isItem, isEntity, isList, customerOf, vendorOf, AR, AP, FUNDS, BANK2, TX, TX_CODE, TX_LABEL, ORDERS, sublistsOf, r, w, ref21, HOLD, statusOptions, MONEY, SEGMENTS2, DATED, ENTITY, ITEM_COMMON, LIST_FIELDS, TX_BASE, party2, ADDRESSES, SALE, order4, FIELDS3, LINE_SEGMENTS, ITEM_LINE, LINE_FIELDS, clocks, today, stamp5, qty, addDays, json31, config10, customFields2, entityRow, itemRow, txRow, listRow, periodRow, lineRows, allLines, unpaid, unapplied, applications, listName, termDays, firstList, accountOfType, accountType, movesStock, nextTranId, statusText, href, selfLink, entityName, accountName, option3, PASSTHROUGH, docOpen, payable, addressBookLines, extraOwner;
163424
163451
  var init_store5 = __esm({
163425
163452
  "packages/server/src/twins/netsuite/store.ts"() {
163426
163453
  "use strict";
163427
163454
  init_open_items();
163428
163455
  init_netsuite();
163429
163456
  init_schema7();
163457
+ init_money();
163430
163458
  init_banking_schema();
163431
163459
  init_banking();
163432
163460
  init_errors6();
@@ -163747,7 +163775,6 @@ var init_store5 = __esm({
163747
163775
  clocks = /* @__PURE__ */ new WeakMap();
163748
163776
  today = (ctx) => ctx.clock.now().toISOString().slice(0, 10);
163749
163777
  stamp5 = (ctx) => ctx.clock.now().toISOString().replace(/\.\d{3}Z$/, "Z");
163750
- round = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
163751
163778
  qty = (value4) => Math.round(value4 * 1e8) / 1e8;
163752
163779
  addDays = (date10, days) => new Date(Date.parse(`${date10}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
163753
163780
  json31 = (text24) => {
@@ -164310,6 +164337,7 @@ function* matches7(re, source, position) {
164310
164337
  }
164311
164338
  }
164312
164339
  function installFunctions(db3, hierarchy) {
164340
+ registerRound(db3);
164313
164341
  const register3 = (name5, fn) => {
164314
164342
  db3.function(`ns_suiteql_${name5}`, { deterministic: true, varargs: true }, fn);
164315
164343
  };
@@ -164588,6 +164616,7 @@ var init_suiteql = __esm({
164588
164616
  "packages/server/src/twins/netsuite/suiteql.ts"() {
164589
164617
  "use strict";
164590
164618
  init_schema7();
164619
+ init_money();
164591
164620
  SuiteqlError = class extends Error {
164592
164621
  gap;
164593
164622
  constructor(message7, gap6 = false) {
@@ -166674,10 +166703,10 @@ function balanceSheet(ctx, p2) {
166674
166703
  }
166675
166704
  function openItems2(ctx, side, to, subsidiary) {
166676
166705
  return sql(ctx).prepare(`SELECT t.id,t.type,t.tranid,t.trandate,t.duedate,i.entity,t.otherrefnum,
166677
- ROUND(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
166706
+ ns_round(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
166678
166707
  WHERE owner.trandate<=@to AND ((i.role='debt' AND a.doc=i.doc AND a.docline=i.line) OR (i.role='credit' AND a.source=i.doc AND a.sourceline=i.line))),0)
166679
166708
  - CASE WHEN i.role='credit' THEN COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment WHERE owner.trandate<=@to AND a.doc=i.doc AND a.docline=i.line),0) ELSE 0 END)
166680
- * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate),2) AS open
166709
+ * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate)) AS open
166681
166710
  FROM ns_item_original i JOIN ns_transactions t ON t.id=i.doc WHERE i.side=@side AND t.trandate<=@to AND (@subsidiary IS NULL OR i.subsidiary=@subsidiary)
166682
166711
  GROUP BY i.doc,i.entity,i.account ORDER BY t.trandate,t.id,i.account`).all({ to, side: side === "ar" ? "receivable" : "payable", subsidiary: subsidiary ?? null }).filter((row2) => row2.open !== 0);
166683
166712
  }
@@ -167586,7 +167615,7 @@ var init_searches = __esm({
167586
167615
  iso20 = (d) => d.toISOString().slice(0, 10);
167587
167616
  at2 = (y, m, d) => new Date(Date.UTC(y, m, d));
167588
167617
  SUMMARIES = ["group", "count", "sum", "avg", "min", "max"];
167589
- money12 = (value4) => value4 === void 0 ? "" : Number(value4).toFixed(2);
167618
+ money12 = (value4) => value4 === void 0 ? "" : round(Number(value4)).toFixed(2);
167590
167619
  }
167591
167620
  });
167592
167621
 
@@ -177592,9 +177621,9 @@ function logTail(data5, cap) {
177592
177621
  if (newline !== -1 && newline < data5.length - 1) start = newline + 1;
177593
177622
  return Buffer.concat([note2(start), data5.subarray(start)]);
177594
177623
  }
177595
- function capFor(path6) {
177624
+ function capFor(path6, inputsBytes = BUNDLE_LIMITS2.largeFileBytes) {
177596
177625
  const name5 = path6.slice(path6.lastIndexOf("/") + 1);
177597
- return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : BUNDLE_LIMITS2.fileBytes;
177626
+ return name5 === "trace.jsonl" || name5 === "state.json" ? BUNDLE_LIMITS2.largeFileBytes : name5 === "agent.log" ? BUNDLE_LIMITS2.agentLogBytes : path6 === "inputs.json" ? inputsBytes : BUNDLE_LIMITS2.fileBytes;
177598
177627
  }
177599
177628
  async function runFiles(runDir, source) {
177600
177629
  const root3 = await readdir(runDir, { withFileTypes: true });
@@ -177615,7 +177644,7 @@ async function packRun(options4) {
177615
177644
  const entries3 = [], omitted = [];
177616
177645
  for (const path6 of paths2) {
177617
177646
  let data5 = redact(await readFile3(join4(options4.runDir, path6)), options4.secrets);
177618
- const cap = capFor(path6);
177647
+ const cap = capFor(path6, options4.inputsBytes);
177619
177648
  if (data5.length > cap) {
177620
177649
  if (path6.endsWith("/agent.log")) data5 = logTail(data5, cap);
177621
177650
  else if (options4.source === "cloud" && MANDATORY_CLOUD_PATH.test(path6)) throw tooBig(`run ${options4.runId}: ${path6} is ${data5.length} bytes; a run keeps at most ${cap}`);
@@ -203676,7 +203705,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
203676
203705
  }
203677
203706
  }
203678
203707
  for (const e of projectToolCalls(t.trace)) {
203679
- if (e.source === "agent") agentCalls2++;
203708
+ if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
203680
203709
  if (e.gap === true) {
203681
203710
  const key4 = JSON.stringify([e.service, e.method, e.path]);
203682
203711
  const gap6 = gaps2.get(key4);
@@ -206566,7 +206595,7 @@ async function executeRun(opts) {
206566
206595
  // A world's seed once (run-inputs.ts). Names only, never values: what a later `ancha runs upload` redacts (hosting spec §3.1).
206567
206596
  agentEnvironment: { passEnv: agent.passEnv ?? [], inheritEnv: agent.inheritEnv === true },
206568
206597
  isolation: { execution: executionDescription(agent), toolWorld: "fresh-per-attempt", agentProcess: agent.mode === "endpoint" && agent.start === void 0 ? "external-setup-adapter" : "fresh-per-attempt", agentState: agent.execution?.mode === "container" ? "fresh-container-scratch" : "provided-namespace-only", limits: agent.execution?.mode === "container" ? "Local Linux container, read-only source, bounded scratch, scoped tool gateway and explicit model hosts; not a multi-tenant cloud security certification." : "Agent files and external memory are shared unless the agent uses ANCHA_STATE_DIR or ANCHA_ATTEMPT_ID. This is not host or network isolation." }
206569
- }, null, 2)}
206598
+ })}
206570
206599
  `, { flag: "wx", mode: 384 });
206571
206600
  const kept = /* @__PURE__ */ new Map();
206572
206601
  for (const [index, item2] of cases.entries()) {
@@ -100895,6 +100895,9 @@ function carrierPortalSeedRecords(seed43) {
100895
100895
  ];
100896
100896
  }
100897
100897
 
100898
+ // packages/core/src/tools/netsuite-money.ts
100899
+ var netsuiteRound = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
100900
+
100898
100901
  // packages/core/src/tools/netsuite.ts
100899
100902
  var NETSUITE_ACCOUNT_TYPES = [
100900
100903
  "Bank",
@@ -101400,7 +101403,7 @@ function checkSeed(seed43, report3) {
101400
101403
  }
101401
101404
  function books(seed43, issue6, money13) {
101402
101405
  if (seed43.integration.customerCreditLimitHandlingOverride && !seed43.policy.allowCustomerCreditLimitHandlingOverride) issue6(["integration", "customerCreditLimitHandlingOverride"], "credit handling override requires policy permission");
101403
- const round2 = (v) => Math.sign(v) * Math.round(Number(`${Math.abs(v).toFixed(10)}e2`)) / 100 || 0;
101406
+ const round2 = netsuiteRound;
101404
101407
  const accountById = new Map(seed43.accounts.map((a) => [a.id, a])), itemById = new Map(seed43.items.map((i) => [i.id, i]));
101405
101408
  const itemTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.rate ?? 0)), 0));
101406
101409
  const buyTotal = (lines2) => round2(lines2.reduce((sum5, line2) => sum5 + round2(line2.quantity * (line2.rate ?? itemById.get(line2.item)?.cost ?? itemById.get(line2.item)?.rate ?? 0)), 0));
@@ -157924,14 +157927,14 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
157924
157927
  CREATE VIEW ns_q_transactionline AS
157925
157928
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
157926
157929
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
157927
- NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
157930
+ NULL AS rate, ns_round(${signed("t.total", 0)} * t.exchangerate) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
157928
157931
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
157929
157932
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
157930
157933
  FROM ns_transactions t WHERE t.type <> 'Journal'
157931
157934
  UNION ALL
157932
157935
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
157933
157936
  ${signed("l.quantity", 2)}, l.rate,
157934
- ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
157937
+ ns_round(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate),
157935
157938
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
157936
157939
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
157937
157940
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool8("l.isclosed")}, l.debit, l.credit,
@@ -158554,6 +158557,12 @@ function upgradeSchema(db3) {
158554
158557
  })();
158555
158558
  }
158556
158559
 
158560
+ // packages/server/src/twins/netsuite/money.ts
158561
+ var round = netsuiteRound;
158562
+ function registerRound(db3) {
158563
+ db3.function("ns_round", { deterministic: true }, (value4) => value4 === null || value4 === void 0 ? null : round(Number(value4)));
158564
+ }
158565
+
158557
158566
  // packages/server/src/twins/netsuite/banking-schema.ts
158558
158567
  var isBanking = (type) => ["bankingTransaction", "bankRecSuggestion", "transactionMatch"].includes(type);
158559
158568
  var read5 = (kind, target4) => ({ kind, ...target4 && { target: target4 } });
@@ -161381,6 +161390,7 @@ function sql(ctx) {
161381
161390
  upgradeSchema(db3);
161382
161391
  const registered = { clock: ctx.clock };
161383
161392
  db3.function("ns_today", { deterministic: false }, () => registered.clock.now().toISOString().slice(0, 10));
161393
+ registerRound(db3);
161384
161394
  clocks.set(db3, holder = registered);
161385
161395
  }
161386
161396
  holder.clock = ctx.clock;
@@ -161388,7 +161398,6 @@ function sql(ctx) {
161388
161398
  }
161389
161399
  var today = (ctx) => ctx.clock.now().toISOString().slice(0, 10);
161390
161400
  var stamp5 = (ctx) => ctx.clock.now().toISOString().replace(/\.\d{3}Z$/, "Z");
161391
- var round = (value4) => Math.sign(value4) * Math.round(Number(`${Math.abs(value4).toFixed(10)}e2`)) / 100 || 0;
161392
161401
  var qty = (value4) => Math.round(value4 * 1e8) / 1e8;
161393
161402
  var addDays = (date10, days) => new Date(Date.parse(`${date10}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
161394
161403
  var json31 = (text23) => {
@@ -163764,6 +163773,7 @@ var nth = (re, source, position, occurrence) => {
163764
163773
  return void 0;
163765
163774
  };
163766
163775
  function installFunctions(db3, hierarchy) {
163776
+ registerRound(db3);
163767
163777
  const register3 = (name5, fn) => {
163768
163778
  db3.function(`ns_suiteql_${name5}`, { deterministic: true, varargs: true }, fn);
163769
163779
  };
@@ -165011,10 +165021,10 @@ function balanceSheet(ctx, p2) {
165011
165021
  }
165012
165022
  function openItems2(ctx, side, to, subsidiary) {
165013
165023
  return sql(ctx).prepare(`SELECT t.id,t.type,t.tranid,t.trandate,t.duedate,i.entity,t.otherrefnum,
165014
- ROUND(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
165024
+ ns_round(SUM((i.original - COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment
165015
165025
  WHERE owner.trandate<=@to AND ((i.role='debt' AND a.doc=i.doc AND a.docline=i.line) OR (i.role='credit' AND a.source=i.doc AND a.sourceline=i.line))),0)
165016
165026
  - CASE WHEN i.role='credit' THEN COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions owner ON owner.id=a.payment WHERE owner.trandate<=@to AND a.doc=i.doc AND a.docline=i.line),0) ELSE 0 END)
165017
- * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate),2) AS open
165027
+ * CASE i.role WHEN 'debt' THEN 1 ELSE -1 END * t.exchangerate)) AS open
165018
165028
  FROM ns_item_original i JOIN ns_transactions t ON t.id=i.doc WHERE i.side=@side AND t.trandate<=@to AND (@subsidiary IS NULL OR i.subsidiary=@subsidiary)
165019
165029
  GROUP BY i.doc,i.entity,i.account ORDER BY t.trandate,t.id,i.account`).all({ to, side: side === "ar" ? "receivable" : "payable", subsidiary: subsidiary ?? null }).filter((row2) => row2.open !== 0);
165020
165030
  }
@@ -165803,7 +165813,7 @@ function expression2(ctx, type, filters, params10, plan4) {
165803
165813
  return out.join(" ");
165804
165814
  }
165805
165815
  var SUMMARIES = ["group", "count", "sum", "avg", "min", "max"];
165806
- var money12 = (value4) => value4 === void 0 ? "" : Number(value4).toFixed(2);
165816
+ var money12 = (value4) => value4 === void 0 ? "" : round(Number(value4)).toFixed(2);
165807
165817
  function listSearches(ctx, args) {
165808
165818
  const needle = args.query?.trim().toLowerCase();
165809
165819
  return { success: true, savedSearches: (config10(ctx).savedSearches ?? []).filter((s2) => !needle || s2.title.toLowerCase().includes(needle) || s2.id.includes(needle)).map((s2) => ({ id: s2.id, internalId: s2.internalId, title: s2.title, recordType: s2.type, isPublic: s2.isPublic })) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "type": "module",
5
5
  "description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, each attempt on a fresh cloud machine in your app.ancha.io workspace, or on your computer.",
6
6
  "bugs": {