@ancha-labs/cli 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/ancha.mjs +154 -140
- package/lib/worker.mjs +5 -2
- package/package.json +1 -1
package/lib/ancha.mjs
CHANGED
|
@@ -100287,7 +100287,7 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
|
|
|
100287
100287
|
}
|
|
100288
100288
|
if (reads2.length) cx.ask("tools.pure", `Which of these tools only compute from their arguments, reading and changing nothing (a calculator, a formatter): ${reads2.join(", ")}? A test runs those itself when production never made the call.`, ["none", "all", reads2.join(",")], 0, { type: "text" });
|
|
100289
100289
|
if (names3.length) {
|
|
100290
|
-
cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}
|
|
100290
|
+
cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}. The others are the agent's own functions: the test answers them when the agent wraps them (wrapTools from @ancha-labs/tools, ancha.wrap_tools in Python).`, ["none", "all", names3.join(",")], 0, { type: "text" });
|
|
100291
100291
|
if (mcp.size) cx.note("answered", "tools.mcp", `your answer: ${[...mcp].join(", ")} over MCP`);
|
|
100292
100292
|
}
|
|
100293
100293
|
const cut = calls2.filter((r) => r.truncated).length;
|
|
@@ -123276,8 +123276,8 @@ async function handleApiCall(c) {
|
|
|
123276
123276
|
const args = await readArgs(c.req.raw);
|
|
123277
123277
|
ctx.signal?.throwIfAborted();
|
|
123278
123278
|
if (name5 === "apps.connections.open" && c.req.method !== "POST") throw new SlackError("method_not_supported");
|
|
123279
|
-
const
|
|
123280
|
-
const body6 =
|
|
123279
|
+
const access8 = reads.has(name5) ? withRead : withMutation;
|
|
123280
|
+
const body6 = access8(ctx, () => {
|
|
123281
123281
|
const caller2 = authenticate(ctx, tokenOf(c.req.raw, args), name5 === "apps.connections.open");
|
|
123282
123282
|
return method2(ctx, args, caller2);
|
|
123283
123283
|
});
|
|
@@ -127993,8 +127993,8 @@ function handle(route11) {
|
|
|
127993
127993
|
}
|
|
127994
127994
|
}
|
|
127995
127995
|
try {
|
|
127996
|
-
const
|
|
127997
|
-
const result =
|
|
127996
|
+
const access8 = route11.read ? withRead : withMutation;
|
|
127997
|
+
const result = access8(ctx, () => {
|
|
127998
127998
|
const caller2 = authenticate2(c, route11.scopes);
|
|
127999
127999
|
const query11 = readQuery(c, route11.query ?? []);
|
|
128000
128000
|
if (bodyError) throw bodyError;
|
|
@@ -131793,9 +131793,9 @@ function authenticate4(c, write4) {
|
|
|
131793
131793
|
if (write4 && principal.readOnly) throw new AdsError2(403, "This credential cannot modify the account", "permission_denied");
|
|
131794
131794
|
return { account: account8, seed: seed40, readOnly: principal.readOnly };
|
|
131795
131795
|
}
|
|
131796
|
-
function consumeQuota(ctx,
|
|
131797
|
-
const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits =
|
|
131798
|
-
const scopes3 = [{ name:
|
|
131796
|
+
function consumeQuota(ctx, access8, route11) {
|
|
131797
|
+
const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits = access8.seed.limits;
|
|
131798
|
+
const scopes3 = [{ name: access8.account.id, limit: limits.perAccountPerMinute }, { name: `${access8.account.id}:${route11}`, limit: limits.perEndpointPerMinute }];
|
|
131799
131799
|
for (const scope3 of scopes3) {
|
|
131800
131800
|
const row = ctx.store.db.prepare("SELECT bucket,count FROM chatgpt_ads_quota WHERE scope=?").get(scope3.name);
|
|
131801
131801
|
if (row?.bucket === bucket2 && row.count >= scope3.limit) throw new AdsError2(429, "Advertiser API request rate exceeded", "rate_limit_exceeded");
|
|
@@ -131815,10 +131815,10 @@ function handle2(route11) {
|
|
|
131815
131815
|
}
|
|
131816
131816
|
return withMutation(c.env.ctx, () => {
|
|
131817
131817
|
try {
|
|
131818
|
-
const
|
|
131819
|
-
consumeQuota(c.env.ctx,
|
|
131818
|
+
const access8 = authenticate4(c, route11.write ?? route11.method === "POST");
|
|
131819
|
+
consumeQuota(c.env.ctx, access8, `${route11.method} ${route11.path}`);
|
|
131820
131820
|
if (parseError) throw parseError;
|
|
131821
|
-
return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6,
|
|
131821
|
+
return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6, access8)), { headers: { "content-type": "application/json; charset=utf-8" } }));
|
|
131822
131822
|
} catch (error64) {
|
|
131823
131823
|
if (!(error64 instanceof AdsError2)) throw error64;
|
|
131824
131824
|
return new Response(JSON.stringify({ error: { message: error64.message, type: error64.status === 401 ? "authentication_error" : error64.status === 429 ? "rate_limit_error" : "invalid_request_error", code: error64.code, param: error64.param } }), { status: error64.status, headers: { "content-type": "application/json; charset=utf-8", ...error64.status === 501 ? { [GAP_HEADER]: "1" } : {} } });
|
|
@@ -131826,8 +131826,8 @@ function handle2(route11) {
|
|
|
131826
131826
|
});
|
|
131827
131827
|
};
|
|
131828
131828
|
}
|
|
131829
|
-
function find(
|
|
131830
|
-
const row =
|
|
131829
|
+
function find(access8, kind, id12) {
|
|
131830
|
+
const row = access8.seed[kind].find((item2) => item2.id === id12 && item2.accountId === access8.account.id);
|
|
131831
131831
|
if (!row) throw new AdsError2(404, "Resource not found", "resource_not_found");
|
|
131832
131832
|
return row;
|
|
131833
131833
|
}
|
|
@@ -131852,15 +131852,15 @@ function canonical3(value5) {
|
|
|
131852
131852
|
if (value5 && typeof value5 === "object") return `{${Object.entries(value5).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
|
|
131853
131853
|
return JSON.stringify(value5);
|
|
131854
131854
|
}
|
|
131855
|
-
function idempotency(c,
|
|
131855
|
+
function idempotency(c, access8, kind, body6) {
|
|
131856
131856
|
const key3 = c.req.header("idempotency-key");
|
|
131857
131857
|
if (key3 === void 0) return { existing: void 0, remember: (_id) => {
|
|
131858
131858
|
} };
|
|
131859
131859
|
if (key3.length > 255 || !key3.trim()) invalid8("Idempotency-Key requires 1\u2013255 characters and non-whitespace");
|
|
131860
131860
|
const fingerprint = createHash13("sha256").update(canonical3(body6)).digest("hex");
|
|
131861
|
-
const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(
|
|
131861
|
+
const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access8.account.id, kind, key3);
|
|
131862
131862
|
if (prior && prior.fingerprint !== fingerprint) throw new AdsError2(409, "Idempotency-Key was used with different input", "idempotency_conflict");
|
|
131863
|
-
return { existing: prior ? find(
|
|
131863
|
+
return { existing: prior ? find(access8, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access8.account.id, kind, key3, fingerprint, id12) };
|
|
131864
131864
|
}
|
|
131865
131865
|
|
|
131866
131866
|
// packages/server/src/twins/chatgpt-ads/routes.ts
|
|
@@ -131876,40 +131876,40 @@ function targeting2(value5, previous) {
|
|
|
131876
131876
|
const parsed3 = parse5(ChatGPTAdsTargetingSchema, body6);
|
|
131877
131877
|
return { ...parsed3, ...!Object.hasOwn(body6, "platforms") && previous?.platforms !== void 0 ? { platforms: previous.platforms } : {} };
|
|
131878
131878
|
}
|
|
131879
|
-
function bidding(value5, campaign2,
|
|
131879
|
+
function bidding(value5, campaign2, access8) {
|
|
131880
131880
|
const body6 = object6(value5, "bidding_config");
|
|
131881
131881
|
keys(body6, ["billing_event_type", "strategy", "max_bid_micros"], "bidding_config");
|
|
131882
131882
|
if (body6.strategy === "maximize_conversions") unsupported5("conversion bidding");
|
|
131883
131883
|
const bid = parse5(ChatGPTAdsBiddingSchema, body6), billing = campaign2.bidding_type === "clicks" ? "click" : "impression";
|
|
131884
131884
|
if (bid.billing_event_type !== billing) invalid8("Bidding must match the campaign billing event", "bidding_config");
|
|
131885
|
-
if (billing === "impression" && !
|
|
131885
|
+
if (billing === "impression" && !access8.account.impressionBiddingEnabled) throw new AdsError2(403, "Account is not eligible for impression bidding", "permission_denied");
|
|
131886
131886
|
const strategy = bid.strategy ?? (bid.max_bid_micros !== void 0 ? "fixed_bid" : "maximize_clicks");
|
|
131887
131887
|
if (strategy === "fixed_bid" && bid.max_bid_micros === void 0) invalid8("Fixed bid requires max_bid_micros");
|
|
131888
131888
|
if (strategy === "maximize_clicks" && (billing !== "click" || bid.max_bid_micros !== void 0)) invalid8("Maximize clicks requires click billing and no fixed bid");
|
|
131889
131889
|
return { ...bid, strategy };
|
|
131890
131890
|
}
|
|
131891
|
-
function creative(value5,
|
|
131891
|
+
function creative(value5, access8, creating) {
|
|
131892
131892
|
const body6 = object6(value5, "creative");
|
|
131893
131893
|
keys(body6, ["type", "title", "body", "target_url", "file_id", "price"], "creative");
|
|
131894
131894
|
if (body6.type !== void 0 && body6.type !== "chat_card") unsupported5(`creative type ${String(body6.type)}`);
|
|
131895
131895
|
const parsed3 = parse5(ChatGPTAdsCreativeSchema, body6);
|
|
131896
131896
|
if (creating && parsed3.title.length < 3) invalid8("New creative title must have at least 3 characters", "creative.title");
|
|
131897
|
-
const file3 =
|
|
131897
|
+
const file3 = access8.seed.files.find((f) => f.id === parsed3.file_id && f.accountId === access8.account.id);
|
|
131898
131898
|
if (!file3) invalid8("Creative file is not available to this account", "creative.file_id");
|
|
131899
131899
|
if (file3.width < 640 || file3.height < 640) invalid8("Creative image must be at least 640 by 640", "creative.file_id");
|
|
131900
131900
|
return parsed3;
|
|
131901
131901
|
}
|
|
131902
|
-
function parent(
|
|
131902
|
+
function parent(access8, kind, value5) {
|
|
131903
131903
|
if (kind === "campaigns") return void 0;
|
|
131904
|
-
const row = find(
|
|
131904
|
+
const row = find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(value5[kind === "adGroups" ? "campaign_id" : "ad_group_id"], "parent id", 200));
|
|
131905
131905
|
if (row.status === "archived") invalid8("Cannot create a child of an archived resource");
|
|
131906
|
-
if (kind === "ads" && find(
|
|
131906
|
+
if (kind === "ads" && find(access8, "campaigns", row.campaign_id).status === "archived") invalid8("Cannot create an ad in an archived campaign");
|
|
131907
131907
|
return row;
|
|
131908
131908
|
}
|
|
131909
131909
|
function validateSeed(seed40) {
|
|
131910
131910
|
return parse5(ChatGPTAdsSeedSchema, seed40);
|
|
131911
131911
|
}
|
|
131912
|
-
function mutate2(c,
|
|
131912
|
+
function mutate2(c, access8, kind, input2, existing2) {
|
|
131913
131913
|
const body6 = object6(input2), creating = !existing2;
|
|
131914
131914
|
keys(body6, creating ? createFields[kind] : updateFields[kind], kind);
|
|
131915
131915
|
if (creating && !["active", "paused"].includes(body6.status)) invalid8("Create status must be active or paused", "status");
|
|
@@ -131919,29 +131919,29 @@ function mutate2(c, access7, kind, input2, existing2) {
|
|
|
131919
131919
|
if (!creating && Object.keys(body6).length === 0) invalid8("Update must specify a field");
|
|
131920
131920
|
if (existing2?.status === "archived") invalid8("Archived resources cannot be changed");
|
|
131921
131921
|
if (kind === "campaigns" && body6.bidding_type !== void 0 && !["impressions", "clicks"].includes(body6.bidding_type)) unsupported5("conversion campaign bidding");
|
|
131922
|
-
const ancestor = creating ? parent(
|
|
131922
|
+
const ancestor = creating ? parent(access8, kind, body6) : void 0;
|
|
131923
131923
|
const timestamp3 = now(c.env.ctx), prefix2 = collections2.find((x) => x.kind === kind).prefix;
|
|
131924
131924
|
let provisional = `${prefix2}_validation`;
|
|
131925
|
-
while (
|
|
131926
|
-
let candidate = creating ? { id: provisional, accountId:
|
|
131925
|
+
while (access8.seed[kind].some((x) => x.id === provisional)) provisional += "x";
|
|
131926
|
+
let candidate = creating ? { id: provisional, accountId: access8.account.id, created_at: timestamp3, updated_at: timestamp3, ...body6 } : { ...existing2, ...body6, updated_at: timestamp3 };
|
|
131927
131927
|
if (kind === "campaigns") {
|
|
131928
131928
|
if (creating && body6.bidding_type === void 0) candidate.bidding_type = "impressions";
|
|
131929
131929
|
if (Object.hasOwn(body6, "targeting")) candidate.targeting = targeting2(body6.targeting, existing2?.targeting);
|
|
131930
131930
|
if (body6.budget !== void 0) keys(object6(body6.budget, "budget"), ["daily_spend_limit_micros", "lifetime_spend_limit_micros"], "budget");
|
|
131931
131931
|
if (candidate.end_time !== void 0 && candidate.end_time !== null && Number(candidate.end_time) <= Number(candidate.start_time ?? timestamp3)) invalid8("end_time must follow start_time");
|
|
131932
131932
|
} else if (kind === "adGroups") {
|
|
131933
|
-
if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(
|
|
131933
|
+
if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access8, "campaigns", existing2.campaign_id), access8);
|
|
131934
131934
|
} else {
|
|
131935
|
-
if (body6.creative !== void 0) candidate.creative = creative(body6.creative,
|
|
131935
|
+
if (body6.creative !== void 0) candidate.creative = creative(body6.creative, access8, creating);
|
|
131936
131936
|
if (creating || body6.creative !== void 0) {
|
|
131937
|
-
const policy =
|
|
131937
|
+
const policy = access8.account.newAdReview;
|
|
131938
131938
|
candidate = { ...candidate, review: { status: "in_review" }, reviewAfterMs: c.env.ctx.clock.elapsedMs() + policy.delayMs, reviewOutcome: policy.outcome, reviewReason: policy.reason };
|
|
131939
131939
|
}
|
|
131940
131940
|
}
|
|
131941
|
-
const rows33 = [...
|
|
131941
|
+
const rows33 = [...access8.seed[kind]];
|
|
131942
131942
|
if (creating) rows33.push(candidate);
|
|
131943
131943
|
else rows33[rows33.findIndex((x) => x.id === existing2.id)] = candidate;
|
|
131944
|
-
const seed40 = validateSeed({ ...
|
|
131944
|
+
const seed40 = validateSeed({ ...access8.seed, [kind]: rows33 });
|
|
131945
131945
|
const result = seed40[kind].find((x) => x.id === candidate.id);
|
|
131946
131946
|
if (creating) {
|
|
131947
131947
|
let id12;
|
|
@@ -131953,7 +131953,7 @@ function mutate2(c, access7, kind, input2, existing2) {
|
|
|
131953
131953
|
save3(c.env.ctx, seed40);
|
|
131954
131954
|
return { seed: seed40, item: result };
|
|
131955
131955
|
}
|
|
131956
|
-
function list6(c,
|
|
131956
|
+
function list6(c, access8, kind) {
|
|
131957
131957
|
const parentKey = kind === "adGroups" ? "campaign_id" : kind === "ads" ? "ad_group_id" : void 0;
|
|
131958
131958
|
const query11 = params3(c, ["include", "name", "limit", "after", "before", "order", ...parentKey ? [parentKey] : []], ["include"]), issues = includes2(query11);
|
|
131959
131959
|
if (query11.order !== void 0 && !["asc", "desc"].includes(query11.order)) invalid8("order must be asc or desc");
|
|
@@ -131961,42 +131961,42 @@ function list6(c, access7, kind) {
|
|
|
131961
131961
|
const name5 = text15(query11.name, "name");
|
|
131962
131962
|
if (name5.length < 3 || !name5.trim()) invalid8("name must have at least three characters");
|
|
131963
131963
|
}
|
|
131964
|
-
if (parentKey && query11[parentKey] !== void 0) find(
|
|
131965
|
-
const rows33 =
|
|
131964
|
+
if (parentKey && query11[parentKey] !== void 0) find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(query11[parentKey], parentKey, 200));
|
|
131965
|
+
const rows33 = access8.seed[kind].filter((row) => row.accountId === access8.account.id && (query11.name === void 0 || row.name === query11.name) && (!parentKey || query11[parentKey] === void 0 || row[parentKey] === query11[parentKey]));
|
|
131966
131966
|
rows33.sort((a, b) => (a.created_at - b.created_at || a.id.localeCompare(b.id)) * (query11.order === "asc" ? 1 : -1));
|
|
131967
131967
|
const page15 = pagination(rows33, query11);
|
|
131968
|
-
return { ...page15, data: page15.data.map((row) => project5(c.env.ctx,
|
|
131968
|
+
return { ...page15, data: page15.data.map((row) => project5(c.env.ctx, access8.seed, kind, row, issues)) };
|
|
131969
131969
|
}
|
|
131970
|
-
var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body,
|
|
131970
|
+
var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body, access8) => {
|
|
131971
131971
|
params3(c, []);
|
|
131972
|
-
return accountView(
|
|
131972
|
+
return accountView(access8.account);
|
|
131973
131973
|
} }];
|
|
131974
131974
|
for (const { kind, path: path6 } of collections2) {
|
|
131975
131975
|
catalogRoutes.push(
|
|
131976
|
-
{ method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b,
|
|
131977
|
-
{ method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6,
|
|
131976
|
+
{ method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b, access8) => list6(c, access8, kind) },
|
|
131977
|
+
{ method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6, access8) => {
|
|
131978
131978
|
params3(c, []);
|
|
131979
|
-
const retry = idempotency(c,
|
|
131980
|
-
if (retry.existing) return project5(c.env.ctx,
|
|
131981
|
-
const result = mutate2(c,
|
|
131979
|
+
const retry = idempotency(c, access8, kind, body6);
|
|
131980
|
+
if (retry.existing) return project5(c.env.ctx, access8.seed, kind, retry.existing);
|
|
131981
|
+
const result = mutate2(c, access8, kind, body6);
|
|
131982
131982
|
retry.remember(result.item.id);
|
|
131983
131983
|
return project5(c.env.ctx, result.seed, kind, result.item);
|
|
131984
131984
|
} },
|
|
131985
|
-
{ method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body,
|
|
131985
|
+
{ method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body, access8) => {
|
|
131986
131986
|
const query11 = params3(c, ["include"], ["include"]);
|
|
131987
|
-
return project5(c.env.ctx,
|
|
131987
|
+
return project5(c.env.ctx, access8.seed, kind, find(access8, kind, c.req.param("id")), includes2(query11));
|
|
131988
131988
|
} },
|
|
131989
|
-
{ method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6,
|
|
131989
|
+
{ method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6, access8) => {
|
|
131990
131990
|
params3(c, []);
|
|
131991
|
-
const result = mutate2(c,
|
|
131991
|
+
const result = mutate2(c, access8, kind, body6, find(access8, kind, c.req.param("id")));
|
|
131992
131992
|
return project5(c.env.ctx, result.seed, kind, result.item);
|
|
131993
131993
|
} }
|
|
131994
131994
|
);
|
|
131995
|
-
for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body,
|
|
131995
|
+
for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body, access8) => {
|
|
131996
131996
|
params3(c, []);
|
|
131997
|
-
const existing2 = find(
|
|
131998
|
-
if (existing2.status === status5) return project5(c.env.ctx,
|
|
131999
|
-
const result = mutate2(c,
|
|
131997
|
+
const existing2 = find(access8, kind, c.req.param("id"));
|
|
131998
|
+
if (existing2.status === status5) return project5(c.env.ctx, access8.seed, kind, existing2);
|
|
131999
|
+
const result = mutate2(c, access8, kind, { status: status5 }, existing2);
|
|
132000
132000
|
return project5(c.env.ctx, result.seed, kind, result.item);
|
|
132001
132001
|
} });
|
|
132002
132002
|
}
|
|
@@ -132022,7 +132022,7 @@ function bound(value5, field4) {
|
|
|
132022
132022
|
if (typeof value5 !== "number" || !Number.isSafeInteger(value5)) invalid8(`Invalid ${field4}`);
|
|
132023
132023
|
return value5;
|
|
132024
132024
|
}
|
|
132025
|
-
function report(c,
|
|
132025
|
+
function report(c, access8, scope3) {
|
|
132026
132026
|
const query11 = params3(c, ["time_granularity", "aggregation_level", "limit", "after", "before", "time_ranges", "fields", "filters", "sort"], ["time_ranges", "fields", "filters", "sort"]);
|
|
132027
132027
|
const granularity = query11.time_granularity ?? "daily";
|
|
132028
132028
|
if (!["none", "daily"].includes(granularity)) unsupported5(`insights time_granularity ${String(granularity)}`);
|
|
@@ -132030,8 +132030,8 @@ function report(c, access7, scope3) {
|
|
|
132030
132030
|
if (!levels.includes(requested2)) invalid8("Invalid aggregation_level");
|
|
132031
132031
|
const level3 = requested2;
|
|
132032
132032
|
if (levels.indexOf(level3) < levels.indexOf(scope3)) invalid8("Aggregation must be at or below the endpoint scope");
|
|
132033
|
-
const scopeId = scope3 === "ad_account" ?
|
|
132034
|
-
if (scope3 !== "ad_account") find(
|
|
132033
|
+
const scopeId = scope3 === "ad_account" ? access8.account.id : c.req.param("id");
|
|
132034
|
+
if (scope3 !== "ad_account") find(access8, scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "adGroups" : "ads", scopeId);
|
|
132035
132035
|
const at3 = now(c.env.ctx), earliest = at3 - 5 * 366 * 86400, ranges2 = array2(query11.time_ranges);
|
|
132036
132036
|
if (ranges2.length > 1) invalid8("Exactly one time range is supported");
|
|
132037
132037
|
let start = Math.ceil(earliest / 3600) * 3600, end = Math.floor(at3 / 3600) * 3600;
|
|
@@ -132080,16 +132080,16 @@ function report(c, access7, scope3) {
|
|
|
132080
132080
|
if (!["asc", "desc"].includes(s.direction)) invalid8("Sort direction must be asc or desc");
|
|
132081
132081
|
return { key: key3, direction: s.direction };
|
|
132082
132082
|
});
|
|
132083
|
-
const ads = new Map(
|
|
132083
|
+
const ads = new Map(access8.seed.ads.filter((x) => x.accountId === access8.account.id).map((x) => [x.id, x])), groups = new Map(access8.seed.adGroups.map((x) => [x.id, x])), campaigns = new Map(access8.seed.campaigns.map((x) => [x.id, x]));
|
|
132084
132084
|
const totals2 = /* @__PURE__ */ new Map();
|
|
132085
|
-
for (const observation of
|
|
132085
|
+
for (const observation of access8.seed.insights) {
|
|
132086
132086
|
if (observation.availableAfterMs > c.env.ctx.clock.elapsedMs() || observation.start_time < start || observation.end_time > end || observation.end_time > at3) continue;
|
|
132087
132087
|
const ad = ads.get(observation.adId);
|
|
132088
132088
|
if (!ad) continue;
|
|
132089
132089
|
const group5 = groups.get(ad.ad_group_id), campaign2 = campaigns.get(group5.campaign_id);
|
|
132090
|
-
const entities = { ad_account:
|
|
132090
|
+
const entities = { ad_account: access8.account, campaign: campaign2, ad_group: group5, ad };
|
|
132091
132091
|
if (entities[scope3].id !== scopeId) continue;
|
|
132092
|
-
const bucket2 = granularity === "daily" ? dayBounds(observation.start_time,
|
|
132092
|
+
const bucket2 = granularity === "daily" ? dayBounds(observation.start_time, access8.account.timezone) : void 0;
|
|
132093
132093
|
const from = bucket2 ? Math.max(start, bucket2.start) : start, to = bucket2 ? Math.min(end, bucket2.end) : end;
|
|
132094
132094
|
const id12 = `start=${from}:end=${to}:entity_id=${entities[level3].id}`;
|
|
132095
132095
|
let total = totals2.get(id12);
|
|
@@ -132123,7 +132123,7 @@ function report(c, access7, scope3) {
|
|
|
132123
132123
|
return a.start_time - b.start_time || a.id.localeCompare(b.id);
|
|
132124
132124
|
});
|
|
132125
132125
|
const page15 = pagination(rows33, query11, 20, 2e3);
|
|
132126
|
-
return { ...page15, timezone:
|
|
132126
|
+
return { ...page15, timezone: access8.account.timezone, count: page15.data.length, data: page15.data.map(({ id: id12, start_time, end_time, values: values2 }) => {
|
|
132127
132127
|
const row = { id: id12, start_time, end_time };
|
|
132128
132128
|
for (const name5 of fields11) {
|
|
132129
132129
|
const [entity, key3] = name5.split("."), wire2 = name5 === "metadata.readable_time" ? "readable_time" : metrics.includes(key3) ? key3 : `${entity}_${key3}`;
|
|
@@ -132132,7 +132132,7 @@ function report(c, access7, scope3) {
|
|
|
132132
132132
|
return row;
|
|
132133
132133
|
}) };
|
|
132134
132134
|
}
|
|
132135
|
-
var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body,
|
|
132135
|
+
var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body, access8) => report(c, access8, scope3) }));
|
|
132136
132136
|
|
|
132137
132137
|
// packages/server/src/twins/chatgpt-ads/index.ts
|
|
132138
132138
|
var chatGPTAdsRoutes = [...catalogRoutes, ...insightsRoutes];
|
|
@@ -135546,8 +135546,8 @@ function visible2(ctx, type, record23) {
|
|
|
135546
135546
|
return true;
|
|
135547
135547
|
}
|
|
135548
135548
|
function permission5(ctx, write4 = false) {
|
|
135549
|
-
const
|
|
135550
|
-
if (!
|
|
135549
|
+
const access8 = config4(ctx).access;
|
|
135550
|
+
if (!access8.read || write4 && !access8.write) throw new SalesforceError(403, "INSUFFICIENT_ACCESS_OR_READONLY", "The session does not have permission for this operation.");
|
|
135551
135551
|
}
|
|
135552
135552
|
function getRecord2(ctx, type, id12) {
|
|
135553
135553
|
permission5(ctx);
|
|
@@ -135636,8 +135636,8 @@ function deleteRecord(ctx, type, id12) {
|
|
|
135636
135636
|
history2(ctx, type, id12, "delete", prior, null);
|
|
135637
135637
|
}
|
|
135638
135638
|
function dumpState9(ctx) {
|
|
135639
|
-
const { org: org5, access:
|
|
135640
|
-
return { org: org5, access:
|
|
135639
|
+
const { org: org5, access: access8 } = config4(ctx);
|
|
135640
|
+
return { org: org5, access: access8, ...Object.fromEntries(salesforceObjectNames.map((type) => [salesforceCollections[type], rows29(ctx, type)])), history: ctx.store.db.prepare("SELECT * FROM salesforce_history ORDER BY ordinal").all().map((row) => ({ ordinal: row.ordinal, object: row.type, id: row.id, operation: row.operation, at: row.at, before: row.before_json ? JSON.parse(row.before_json) : null, after: row.after_json ? JSON.parse(row.after_json) : null })) };
|
|
135641
135641
|
}
|
|
135642
135642
|
|
|
135643
135643
|
// packages/server/src/twins/salesforce/query.ts
|
|
@@ -137887,8 +137887,8 @@ function visibleParents(ctx, caller2, file3) {
|
|
|
137887
137887
|
const parent2 = getFile(ctx, file3.parent);
|
|
137888
137888
|
return parent2 && accessTo(ctx, caller2, parent2).role !== null ? [parent2.id] : [];
|
|
137889
137889
|
}
|
|
137890
|
-
function fileResource(ctx, caller2, file3,
|
|
137891
|
-
const role3 =
|
|
137890
|
+
function fileResource(ctx, caller2, file3, access8 = accessTo(ctx, caller2, file3)) {
|
|
137891
|
+
const role3 = access8.role ?? "reader", editor = isEditorFile(file3), folder = isFolder(file3), binary = !editor && !folder;
|
|
137892
137892
|
const trash2 = trashedBy(ctx, file3), granted = effectivePermissions(ctx, file3), caps = capabilities(file3, role3);
|
|
137893
137893
|
const properties2 = JSON.parse(file3.properties), appProperties = JSON.parse(file3.app_properties);
|
|
137894
137894
|
const extension2 = binary && /\.([A-Za-z0-9]+)$/.exec(file3.original_filename ?? file3.name)?.[1];
|
|
@@ -137920,7 +137920,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
|
|
|
137920
137920
|
modifiedTime: iso(file3.modified_ms),
|
|
137921
137921
|
...file3.modified_by === caller2.email && { modifiedByMeTime: iso(file3.modified_ms) },
|
|
137922
137922
|
modifiedByMe: file3.modified_by === caller2.email,
|
|
137923
|
-
...
|
|
137923
|
+
...access8.direct && file3.owner !== caller2.email && { sharedWithMeTime: iso(access8.direct.created_ms), sharingUser: userResource(ctx, caller2, file3.owner) },
|
|
137924
137924
|
owners: [userResource(ctx, caller2, file3.owner)],
|
|
137925
137925
|
lastModifyingUser: userResource(ctx, caller2, file3.modified_by),
|
|
137926
137926
|
shared: granted.length > 1,
|
|
@@ -137949,7 +137949,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
|
|
|
137949
137949
|
function headRevision(ctx, fileId) {
|
|
137950
137950
|
return ctx.store.db.prepare("SELECT id FROM gdrive_revisions WHERE file_id = ? ORDER BY rowid DESC LIMIT 1").get(fileId)?.id;
|
|
137951
137951
|
}
|
|
137952
|
-
function searchable(ctx, caller2, file3,
|
|
137952
|
+
function searchable(ctx, caller2, file3, access8) {
|
|
137953
137953
|
const granted = effectivePermissions(ctx, file3);
|
|
137954
137954
|
const people3 = (min) => granted.filter((entry3) => (entry3.grant.type === "user" || entry3.grant.type === "group") && RANK2[entry3.grant.role] >= RANK2[min]).map((entry3) => entry3.grant.email);
|
|
137955
137955
|
const anyone = granted.find((entry3) => entry3.grant.type === "anyone"), domain2 = granted.find((entry3) => entry3.grant.type === "domain");
|
|
@@ -137970,7 +137970,7 @@ ${text24}`,
|
|
|
137970
137970
|
owners: [file3.owner],
|
|
137971
137971
|
writers: people3("writer"),
|
|
137972
137972
|
readers: people3("reader"),
|
|
137973
|
-
sharedWithMe:
|
|
137973
|
+
sharedWithMe: access8.direct !== null && file3.owner !== caller2.email,
|
|
137974
137974
|
visibility: anyone ? anyone.grant.allow_discovery ? "anyoneCanFind" : "anyoneWithLink" : domain2 ? domain2.grant.allow_discovery ? "domainCanFind" : "domainWithLink" : "limited"
|
|
137975
137975
|
};
|
|
137976
137976
|
}
|
|
@@ -138038,10 +138038,10 @@ function resolve4(ctx, caller2, id12, minimum = "reader") {
|
|
|
138038
138038
|
if (id12 === "root" || id12 === caller2.root) return { file: rootFolder(ctx, caller2), access: { role: "owner", listed: true, direct: null } };
|
|
138039
138039
|
throw notFound3(id12);
|
|
138040
138040
|
}
|
|
138041
|
-
const
|
|
138042
|
-
if (
|
|
138043
|
-
if (RANK2[
|
|
138044
|
-
return { file: file3, access:
|
|
138041
|
+
const access8 = accessTo(ctx, caller2, file3);
|
|
138042
|
+
if (access8.role === null) throw notFound3(id12);
|
|
138043
|
+
if (RANK2[access8.role] < RANK2[minimum]) throw forbidden();
|
|
138044
|
+
return { file: file3, access: access8 };
|
|
138045
138045
|
}
|
|
138046
138046
|
function rootFolder(ctx, caller2) {
|
|
138047
138047
|
const user8 = getUser4(ctx, caller2.email);
|
|
@@ -138074,9 +138074,9 @@ function rootFolder(ctx, caller2) {
|
|
|
138074
138074
|
var isRoot = (caller2, file3) => file3.id === caller2.root;
|
|
138075
138075
|
function writableParent(ctx, caller2, id12) {
|
|
138076
138076
|
if (id12 === "root" || id12 === caller2.root) return null;
|
|
138077
|
-
const { file: file3, access:
|
|
138077
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, id12);
|
|
138078
138078
|
if (!isFolder(file3)) throw new DriveError(400, "invalid", "The specified parent is not a folder.", { name: "parents" });
|
|
138079
|
-
if (RANK2[
|
|
138079
|
+
if (RANK2[access8.role] < RANK2.writer) throw forbidden();
|
|
138080
138080
|
return file3.id;
|
|
138081
138081
|
}
|
|
138082
138082
|
function parentList(value5) {
|
|
@@ -138266,10 +138266,10 @@ function listFiles(call3) {
|
|
|
138266
138266
|
const offset16 = readPageToken(params9.get("pageToken"), binding2);
|
|
138267
138267
|
const matches7 = [];
|
|
138268
138268
|
for (const file3 of allFiles(ctx)) {
|
|
138269
|
-
const
|
|
138270
|
-
if (
|
|
138269
|
+
const access8 = accessTo(ctx, caller2, file3);
|
|
138270
|
+
if (access8.role === null || !access8.listed) continue;
|
|
138271
138271
|
if (corpora === "domain" && !effectivePermissions(ctx, file3).some((entry3) => entry3.grant.type === "domain" && entry3.grant.domain === caller2.domain)) continue;
|
|
138272
|
-
if (predicate(searchable(ctx, caller2, file3,
|
|
138272
|
+
if (predicate(searchable(ctx, caller2, file3, access8))) matches7.push({ file: file3, access: access8 });
|
|
138273
138273
|
}
|
|
138274
138274
|
matches7.sort((a, b) => order4(a.file, b.file));
|
|
138275
138275
|
const page15 = matches7.slice(offset16, offset16 + pageSize2);
|
|
@@ -138277,18 +138277,18 @@ function listFiles(call3) {
|
|
|
138277
138277
|
kind: "drive#fileList",
|
|
138278
138278
|
incompleteSearch: false,
|
|
138279
138279
|
...offset16 + pageSize2 < matches7.length && { nextPageToken: pageToken(offset16 + pageSize2, binding2) },
|
|
138280
|
-
files: page15.map(({ file: file3, access:
|
|
138280
|
+
files: page15.map(({ file: file3, access: access8 }) => fileResource(ctx, caller2, file3, access8))
|
|
138281
138281
|
}, selection));
|
|
138282
138282
|
}
|
|
138283
138283
|
function getFileRoute(call3) {
|
|
138284
138284
|
const params9 = parameters(call3.url, []);
|
|
138285
|
-
const { file: file3, access:
|
|
138285
|
+
const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
|
|
138286
138286
|
if (params9.get("alt") === "media") {
|
|
138287
138287
|
if (isFolder(file3) || isEditorFile(file3)) throw new DriveError(403, "fileNotDownloadable", "Only files with binary content can be downloaded. Use Export with Docs Editors files.", { name: "alt" });
|
|
138288
|
-
if (file3.copy_requires_writer === 1 && RANK2[
|
|
138288
|
+
if (file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotDownloadFile", "The user does not have sufficient permissions to download this file.");
|
|
138289
138289
|
return new Response(new Uint8Array(file3.content ?? Buffer.alloc(0)), { status: 200, headers: { "content-type": file3.mime_type, "content-length": String(file3.content?.length ?? 0) } });
|
|
138290
138290
|
}
|
|
138291
|
-
return json9(project8(fileResource(call3.ctx, call3.caller, file3,
|
|
138291
|
+
return json9(project8(fileResource(call3.ctx, call3.caller, file3, access8), fileMask(params9)));
|
|
138292
138292
|
}
|
|
138293
138293
|
function createFile(call3, media, metadata7 = jsonBody2(call3.body)) {
|
|
138294
138294
|
const { ctx, caller: caller2 } = call3;
|
|
@@ -138349,9 +138349,9 @@ function updateFile(call3, media, metadata7 = jsonBody2(call3.body)) {
|
|
|
138349
138349
|
const params9 = parameters(call3.url, ["addParents", "removeParents"]);
|
|
138350
138350
|
fileBody(metadata7, UPDATE_WRITABLE);
|
|
138351
138351
|
if (metadata7.contentHints !== void 0) unsupported11("contentHints");
|
|
138352
|
-
const { file: file3, access:
|
|
138352
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
|
|
138353
138353
|
if (isRoot(caller2, file3)) throw forbidden();
|
|
138354
|
-
const role3 =
|
|
138354
|
+
const role3 = access8.role, editor = RANK2[role3] >= RANK2.writer;
|
|
138355
138355
|
const next2 = { ...file3 };
|
|
138356
138356
|
let edited = false;
|
|
138357
138357
|
const edit = () => {
|
|
@@ -138469,8 +138469,8 @@ function remove(ctx, caller2, file3) {
|
|
|
138469
138469
|
}
|
|
138470
138470
|
function deleteFile(call3) {
|
|
138471
138471
|
parameters(call3.url, []);
|
|
138472
|
-
const { file: file3, access:
|
|
138473
|
-
if (
|
|
138472
|
+
const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
|
|
138473
|
+
if (access8.role !== "owner" || isRoot(call3.caller, file3)) throw forbidden();
|
|
138474
138474
|
remove(call3.ctx, call3.caller, file3);
|
|
138475
138475
|
return new Response(null, { status: 204 });
|
|
138476
138476
|
}
|
|
@@ -138488,8 +138488,8 @@ function copyFile(call3) {
|
|
|
138488
138488
|
const metadata7 = jsonBody2(call3.body);
|
|
138489
138489
|
fileBody(metadata7, COPY_WRITABLE);
|
|
138490
138490
|
if (metadata7.contentHints !== void 0) unsupported11("contentHints");
|
|
138491
|
-
const { file: file3, access:
|
|
138492
|
-
if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[
|
|
138491
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
|
|
138492
|
+
if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotCopyFile", "This file cannot be copied by the user.");
|
|
138493
138493
|
const mimeType = stringField(metadata7, "mimeType", 255);
|
|
138494
138494
|
if (mimeType !== void 0 && mimeType !== file3.mime_type) unsupported11("converting a file while copying it");
|
|
138495
138495
|
const parents = parentList(metadata7.parents);
|
|
@@ -138585,10 +138585,10 @@ function emailAddress(body6) {
|
|
|
138585
138585
|
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw new DriveError(400, "invalid", "Invalid email address.", { name: "permission.emailAddress" });
|
|
138586
138586
|
return email10;
|
|
138587
138587
|
}
|
|
138588
|
-
function transferOwnership(call3, file3,
|
|
138588
|
+
function transferOwnership(call3, file3, access8, email10, params9) {
|
|
138589
138589
|
const { ctx, caller: caller2 } = call3;
|
|
138590
138590
|
if (!booleanParameter(params9, "transferOwnership", false)) throw new DriveError(403, "forbidden", "The transferOwnership parameter must be enabled when the permission role is 'owner'.");
|
|
138591
|
-
if (
|
|
138591
|
+
if (access8.role !== "owner") throw forbidden();
|
|
138592
138592
|
if (email10 === file3.owner) throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "The owner already has access."');
|
|
138593
138593
|
if (email10.split("@")[1] !== file3.owner.split("@")[1]) {
|
|
138594
138594
|
throw new DriveError(400, "ownershipChangeAcrossDomainNotPermitted", `Bad Request. User message: "Sorry, cannot transfer ownership to ${email10}. Ownership can only be transferred to another user in the same organization as the current owner."`);
|
|
@@ -138635,15 +138635,15 @@ function createPermission(call3) {
|
|
|
138635
138635
|
if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner" || key3 === "inheritedPermissionsDisabled") unsupported11(`permission field ${key3}`);
|
|
138636
138636
|
if (!["type", "role", "emailAddress", "domain", "allowFileDiscovery"].includes(key3)) throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
|
|
138637
138637
|
}
|
|
138638
|
-
const { file: file3, access:
|
|
138639
|
-
if (isRoot(caller2, file3) || !canShare(file3,
|
|
138638
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
|
|
138639
|
+
if (isRoot(caller2, file3) || !canShare(file3, access8.role)) throw forbidden();
|
|
138640
138640
|
const type = body6.type, role3 = body6.role;
|
|
138641
138641
|
if (type === void 0) throw new DriveError(400, "required", "Permission type field required", { name: "permission.type" });
|
|
138642
138642
|
if (role3 === void 0) throw new DriveError(400, "required", "Permission role field required", { name: "permission.role" });
|
|
138643
138643
|
if (!["user", "group", "domain", "anyone"].includes(String(type))) throw new DriveError(400, "invalid", "Invalid permission type.", { name: "permission.type" });
|
|
138644
138644
|
if (role3 === "owner") {
|
|
138645
138645
|
if (type !== "user") unsupported11(`the owner role for a ${String(type)} permission`);
|
|
138646
|
-
return transferOwnership(call3, file3,
|
|
138646
|
+
return transferOwnership(call3, file3, access8, emailAddress(body6), params9);
|
|
138647
138647
|
}
|
|
138648
138648
|
if (role3 === "organizer" || role3 === "fileOrganizer") throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "Organizer roles only apply to shared drives."');
|
|
138649
138649
|
if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
|
|
@@ -138682,15 +138682,15 @@ function updatePermission(call3) {
|
|
|
138682
138682
|
if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner") unsupported11(`permission field ${key3}`);
|
|
138683
138683
|
if (key3 !== "role" && key3 !== "allowFileDiscovery") throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
|
|
138684
138684
|
}
|
|
138685
|
-
const { file: file3, access:
|
|
138686
|
-
if (!canShare(file3,
|
|
138685
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
|
|
138686
|
+
if (!canShare(file3, access8.role)) throw forbidden();
|
|
138687
138687
|
const entry3 = findGrant(ctx, file3, call3.ids[1]);
|
|
138688
138688
|
if (entry3.grant.role === "owner") throw new DriveError(403, "cannotModifyOwnerPermission", "The owner of a file cannot be changed with this request.");
|
|
138689
138689
|
if (entry3.inherited) unsupported11("changing a permission inherited from a parent folder");
|
|
138690
138690
|
const role3 = body6.role === void 0 ? entry3.grant.role : body6.role;
|
|
138691
138691
|
if (role3 === "owner") {
|
|
138692
138692
|
if (entry3.grant.type !== "user") unsupported11(`the owner role for a ${entry3.grant.type} permission`);
|
|
138693
|
-
return transferOwnership(call3, file3,
|
|
138693
|
+
return transferOwnership(call3, file3, access8, entry3.grant.email, params9);
|
|
138694
138694
|
}
|
|
138695
138695
|
if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
|
|
138696
138696
|
ctx.store.db.prepare("UPDATE gdrive_permissions SET role = ? WHERE file_id = ? AND id = ?").run(role3, file3.id, entry3.grant.id);
|
|
@@ -138701,10 +138701,10 @@ function deletePermission(call3) {
|
|
|
138701
138701
|
const { ctx, caller: caller2 } = call3;
|
|
138702
138702
|
const params9 = parameters(call3.url, ["useDomainAdminAccess", "enforceExpansiveAccess"]);
|
|
138703
138703
|
if (booleanParameter(params9, "useDomainAdminAccess", false)) unsupported11("useDomainAdminAccess");
|
|
138704
|
-
const { file: file3, access:
|
|
138704
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
|
|
138705
138705
|
const entry3 = findGrant(ctx, file3, call3.ids[1]);
|
|
138706
138706
|
const self2 = entry3.grant.email === caller2.email;
|
|
138707
|
-
if (!self2 && !canShare(file3,
|
|
138707
|
+
if (!self2 && !canShare(file3, access8.role)) throw forbidden();
|
|
138708
138708
|
if (entry3.grant.role === "owner") throw new DriveError(403, "cannotRemoveOwner", "The owner of a file cannot be removed.");
|
|
138709
138709
|
if (entry3.inherited) unsupported11("removing a permission inherited from a parent folder");
|
|
138710
138710
|
ctx.store.db.prepare("DELETE FROM gdrive_permissions WHERE file_id = ? AND id = ?").run(file3.id, entry3.grant.id);
|
|
@@ -138788,9 +138788,9 @@ function updateComment(call3) {
|
|
|
138788
138788
|
function deleteComment(call3) {
|
|
138789
138789
|
const { ctx, caller: caller2 } = call3;
|
|
138790
138790
|
parameters(call3.url, []);
|
|
138791
|
-
const { file: file3, access:
|
|
138791
|
+
const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0], "commenter");
|
|
138792
138792
|
const comment8 = getComment(ctx, file3, call3.ids[1], false);
|
|
138793
|
-
if (comment8.author !== caller2.email &&
|
|
138793
|
+
if (comment8.author !== caller2.email && access8.role !== "owner") throw new DriveError(403, "insufficientPermissions", "The user does not have sufficient permissions for this comment.");
|
|
138794
138794
|
ctx.store.db.prepare("UPDATE gdrive_comments SET deleted = 1, modified_ms = ? WHERE id = ?").run(ctx.clock.nowMs(), comment8.id);
|
|
138795
138795
|
return new Response(null, { status: 204 });
|
|
138796
138796
|
}
|
|
@@ -138865,8 +138865,8 @@ function listChanges(call3) {
|
|
|
138865
138865
|
const file3 = row.removed ? void 0 : getFile(ctx, row.file_id);
|
|
138866
138866
|
let change = null;
|
|
138867
138867
|
if (file3) {
|
|
138868
|
-
const
|
|
138869
|
-
if (
|
|
138868
|
+
const access8 = accessTo(ctx, caller2, file3);
|
|
138869
|
+
if (access8.role !== null && access8.listed && (!myDrive || file3.owner === caller2.email)) change = { file: fileResource(ctx, caller2, file3, access8), removed: false };
|
|
138870
138870
|
} else if (includeRemoved && row.owner === caller2.email) change = { removed: true };
|
|
138871
138871
|
if (!change) continue;
|
|
138872
138872
|
if (visible5.length === pageSize2) {
|
|
@@ -138933,8 +138933,8 @@ async function handle7(c) {
|
|
|
138933
138933
|
try {
|
|
138934
138934
|
const body6 = method2 === "GET" || method2 === "DELETE" ? void 0 : new Uint8Array(await c.req.arrayBuffer());
|
|
138935
138935
|
const ids2 = (route11.pattern.exec(url3.pathname) ?? []).slice(1).map((value5) => decodeURIComponent(value5));
|
|
138936
|
-
const
|
|
138937
|
-
return
|
|
138936
|
+
const access8 = route11.write ? withMutation : withRead;
|
|
138937
|
+
return access8(ctx, () => {
|
|
138938
138938
|
const token2 = tokenOf2(c, url3);
|
|
138939
138939
|
const caller2 = callerFor(ctx, token2);
|
|
138940
138940
|
if (!caller2) {
|
|
@@ -150142,10 +150142,10 @@ function linkSettings(call3, settings) {
|
|
|
150142
150142
|
if (!["public", "team", "no_one"].includes(audience)) unsupported19(`shared link audience ${audience}`);
|
|
150143
150143
|
out.audience = audience;
|
|
150144
150144
|
}
|
|
150145
|
-
const
|
|
150146
|
-
if (
|
|
150147
|
-
if (!["viewer", "editor", "max"].includes(
|
|
150148
|
-
out.access =
|
|
150145
|
+
const access8 = tag3(value5.access);
|
|
150146
|
+
if (access8 !== void 0) {
|
|
150147
|
+
if (!["viewer", "editor", "max"].includes(access8)) throw new DropboxError(400, `Error in call to API function "${call3.route}": settings.access: unknown tag '${access8}'`);
|
|
150148
|
+
out.access = access8 === "max" ? "editor" : access8;
|
|
150149
150149
|
}
|
|
150150
150150
|
if (value5.expires !== void 0) {
|
|
150151
150151
|
const at3 = Date.parse(String(value5.expires));
|
|
@@ -150254,10 +150254,10 @@ function addMembers(call3) {
|
|
|
150254
150254
|
}
|
|
150255
150255
|
const email10 = String(member4.email ?? "").trim().toLowerCase();
|
|
150256
150256
|
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw endpoint("bad_member/invalid_email", { ".tag": "bad_member", bad_member: { ".tag": "invalid_email", invalid_email: email10 } });
|
|
150257
|
-
const
|
|
150258
|
-
if (!["editor", "viewer", "viewer_no_comment"].includes(
|
|
150257
|
+
const access8 = typeof raw3.access_level === "string" ? raw3.access_level : raw3.access_level?.[".tag"] ?? "viewer";
|
|
150258
|
+
if (!["editor", "viewer", "viewer_no_comment"].includes(access8)) throw new DropboxError(400, `Error in call to API function "sharing/add_folder_member": access_level: unknown tag '${access8}'`);
|
|
150259
150259
|
if (email10 === account5(call3.ctx).email) throw endpoint("bad_member/cant_share_with_self", { ".tag": "bad_member", bad_member: { ".tag": "cant_share_with_self" } });
|
|
150260
|
-
call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10,
|
|
150260
|
+
call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10, access8, now10);
|
|
150261
150261
|
}
|
|
150262
150262
|
return json15(null);
|
|
150263
150263
|
}
|
|
@@ -157128,11 +157128,11 @@ async function token(c) {
|
|
|
157128
157128
|
if (!known2) return Response.json({ error: "invalid_client", error_description: "Client Authentication failed" }, { status: 401 });
|
|
157129
157129
|
const grant = form.get("grant_type");
|
|
157130
157130
|
if (grant !== "client_credentials") return Response.json({ error: "unsupported_grant_type", error_description: grant ? "unsupported grant_type" : "Grant Type is NULL" }, { status: 400 });
|
|
157131
|
-
const now10 = ctx.clock.nowMs(),
|
|
157132
|
-
ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(
|
|
157131
|
+
const now10 = ctx.clock.nowMs(), access8 = `A21AA${ctx.secrets.alnumUpper(92)}`;
|
|
157132
|
+
ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(access8, now10 + 324e5);
|
|
157133
157133
|
return Response.json({
|
|
157134
157134
|
scope: "https://uri.paypal.com/services/payments/payment https://uri.paypal.com/services/payments/refund https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/reporting/search/read",
|
|
157135
|
-
access_token:
|
|
157135
|
+
access_token: access8,
|
|
157136
157136
|
token_type: "Bearer",
|
|
157137
157137
|
app_id: "APP-80W284485P519543T",
|
|
157138
157138
|
expires_in: 32400,
|
|
@@ -177678,9 +177678,9 @@ function writeTar(entries2, mtimeMs) {
|
|
|
177678
177678
|
}
|
|
177679
177679
|
|
|
177680
177680
|
// packages/cli/src/run-upload.ts
|
|
177681
|
-
async function uploadWorkspace(ctx) {
|
|
177681
|
+
async function uploadWorkspace(ctx, missing6 = { message: "--upload needs a workspace", hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" }) {
|
|
177682
177682
|
const url3 = ctx.globals().local ? (await ctx.loadConfig()).server?.url || ctx.io.env.ANCHA_SERVER_URL || await defaultServerUrl(ctx.io.env) : (await serverChoice(ctx)).url;
|
|
177683
|
-
if (url3 === void 0) throw new AnchaError("USAGE",
|
|
177683
|
+
if (url3 === void 0) throw new AnchaError("USAGE", missing6.message, { hint: missing6.hint });
|
|
177684
177684
|
try {
|
|
177685
177685
|
return normalizeServerUrl(url3);
|
|
177686
177686
|
} catch {
|
|
@@ -177745,7 +177745,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir) {
|
|
|
177745
177745
|
return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
|
|
177746
177746
|
});
|
|
177747
177747
|
const failedThere = checks.filter((c) => c.production === "failed");
|
|
177748
|
-
const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : "matches";
|
|
177748
|
+
const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
|
|
177749
177749
|
const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
|
|
177750
177750
|
const counts = {};
|
|
177751
177751
|
for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
|
|
@@ -177758,7 +177758,8 @@ var SAY = {
|
|
|
177758
177758
|
partly: "production's failure happens here in part",
|
|
177759
177759
|
"not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
|
|
177760
177760
|
matches: "this run matches production, which passed these checks",
|
|
177761
|
-
differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)"
|
|
177761
|
+
differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
|
|
177762
|
+
unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
|
|
177762
177763
|
};
|
|
177763
177764
|
function renderReproduction(reproductions) {
|
|
177764
177765
|
return reproductions.map((r) => {
|
|
@@ -177770,6 +177771,8 @@ function renderReproduction(reproductions) {
|
|
|
177770
177771
|
...rows33,
|
|
177771
177772
|
`=> ${SAY[r.verdict]}`,
|
|
177772
177773
|
...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
|
|
177774
|
+
// A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
|
|
177775
|
+
...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
|
|
177773
177776
|
...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
|
|
177774
177777
|
// How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
|
|
177775
177778
|
...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
|
|
@@ -202787,7 +202790,7 @@ async function interruptible(ctx, fn) {
|
|
|
202787
202790
|
}
|
|
202788
202791
|
}
|
|
202789
202792
|
function registerRun(program2, ctx) {
|
|
202790
|
-
program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer)
|
|
202793
|
+
program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer) or docker (a sealed container; needs agent.execution with an image in ancha.yaml). Default: what ancha.yaml says. To run in your workspace, start a saved world's task with ancha runs start").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").option("--dry-run", "check ancha.yaml and every scene, print what would run, and stop: no server, no agent, no trial").option("--allow-unwrapped <tools>", "in a test made from a trace, let the agent call these tools for real instead of stopping because it does not wrap them (comma-separated, repeatable)", (value5, all8 = []) => [...all8, ...value5.split(",").map((s) => s.trim()).filter(Boolean)]).action(async (sceneArgs, opts, command) => {
|
|
202791
202794
|
const { cwd } = ctx.io;
|
|
202792
202795
|
if (opts.agent === void 0 && opts.agentUrl === void 0 && ctx.globals().config === void 0 && !await access4(resolve23(cwd, "ancha.yaml")).then(() => true, () => false)) {
|
|
202793
202796
|
throw new AnchaError("USAGE", "no ancha.yaml here", { hint: 'run `ancha init` in your agent\'s project, or pass --agent "<command>"' });
|
|
@@ -202866,9 +202869,9 @@ function registerRun(program2, ctx) {
|
|
|
202866
202869
|
const workspace3 = workspaceOf(choice4.url, cwd);
|
|
202867
202870
|
let relay;
|
|
202868
202871
|
if (serverUrl3 === void 0 && scenes.some((scene2) => (scene2.people?.length ?? 0) > 0 || Object.keys(scene2.tools ?? {}).length > 0)) {
|
|
202869
|
-
const
|
|
202870
|
-
if (
|
|
202871
|
-
relay = { baseUrl:
|
|
202872
|
+
const access8 = await modelAccess(ctx.io.env);
|
|
202873
|
+
if (access8.kind === "relay") {
|
|
202874
|
+
relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
|
|
202872
202875
|
ctx.out.info(RELAY_NOTICE);
|
|
202873
202876
|
}
|
|
202874
202877
|
}
|
|
@@ -203511,9 +203514,9 @@ function registerReplay(program2, ctx) {
|
|
|
203511
203514
|
let relay;
|
|
203512
203515
|
let canAnswer = choice4.url !== void 0;
|
|
203513
203516
|
if (choice4.url === void 0 && hasPeople) {
|
|
203514
|
-
const
|
|
203515
|
-
canAnswer =
|
|
203516
|
-
if (
|
|
203517
|
+
const access8 = await modelAccess(ctx.io.env);
|
|
203518
|
+
canAnswer = access8.kind !== "none";
|
|
203519
|
+
if (access8.kind === "relay") relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
|
|
203517
203520
|
}
|
|
203518
203521
|
if (opts.people === "live" && hasPeople && !canAnswer) {
|
|
203519
203522
|
throw new AnchaError("USAGE", "people can't answer live here: there is no model for them", { hint: "run ancha login, set OPENROUTER_API_KEY, or replay with --people strict" });
|
|
@@ -204577,11 +204580,11 @@ import { dirname as dirname15, join as join40, relative as relative9, resolve as
|
|
|
204577
204580
|
async function model(ctx) {
|
|
204578
204581
|
const env2 = ctx.io.env;
|
|
204579
204582
|
if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
|
|
204580
|
-
const
|
|
204581
|
-
if (
|
|
204582
|
-
if (
|
|
204583
|
+
const access8 = await modelAccess(env2);
|
|
204584
|
+
if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
|
|
204585
|
+
if (access8.kind === "relay") {
|
|
204583
204586
|
ctx.out.info(RELAY_NOTICE);
|
|
204584
|
-
return { client: gen_exports.openRouterClient({ apiKey:
|
|
204587
|
+
return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
|
|
204585
204588
|
}
|
|
204586
204589
|
throw new AnchaError("CONFIG_INVALID", "world gen needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
|
|
204587
204590
|
}
|
|
@@ -204903,11 +204906,11 @@ ${(0, import_yaml11.stringify)(sorted2, { lineWidth: 0 })}`;
|
|
|
204903
204906
|
async function draftingModel(ctx) {
|
|
204904
204907
|
const env2 = ctx.io.env;
|
|
204905
204908
|
if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
|
|
204906
|
-
const
|
|
204907
|
-
if (
|
|
204908
|
-
if (
|
|
204909
|
+
const access8 = await modelAccess(env2);
|
|
204910
|
+
if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
|
|
204911
|
+
if (access8.kind === "relay") {
|
|
204909
204912
|
ctx.out.info(RELAY_NOTICE);
|
|
204910
|
-
return { client: gen_exports.openRouterClient({ apiKey:
|
|
204913
|
+
return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
|
|
204911
204914
|
}
|
|
204912
204915
|
throw new AnchaError("CONFIG_INVALID", "test new needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
|
|
204913
204916
|
}
|
|
@@ -226290,7 +226293,7 @@ function registerRuns(program2, ctx) {
|
|
|
226290
226293
|
|
|
226291
226294
|
// packages/cli/src/commands/traces.ts
|
|
226292
226295
|
import { createHash as createHash68 } from "node:crypto";
|
|
226293
|
-
import { readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
|
|
226296
|
+
import { access as access7, readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
|
|
226294
226297
|
import { basename as basename12, dirname as dirname17, join as join55, relative as relative12, resolve as resolve40 } from "node:path";
|
|
226295
226298
|
var import_yaml16 = __toESM(require_dist(), 1);
|
|
226296
226299
|
init_src();
|
|
@@ -226489,8 +226492,8 @@ function workspaceError(status5, body6, path6) {
|
|
|
226489
226492
|
function notInWorkspace(error64) {
|
|
226490
226493
|
return error64 instanceof WorkspaceError && error64.status === 404 && !error64.noTraces;
|
|
226491
226494
|
}
|
|
226492
|
-
async function workspaceApi(ctx) {
|
|
226493
|
-
const workspace3 = await uploadWorkspace(ctx);
|
|
226495
|
+
async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY") {
|
|
226496
|
+
const workspace3 = await uploadWorkspace(ctx, { message: "not logged in to a workspace", hint });
|
|
226494
226497
|
const key3 = await apiKeyFor(workspace3, ctx.io.env);
|
|
226495
226498
|
if (key3 === void 0) throw authError(workspace3, { keySent: false });
|
|
226496
226499
|
const origin = new URL(workspace3).origin;
|
|
@@ -226648,6 +226651,14 @@ async function report6(ctx, world5, written) {
|
|
|
226648
226651
|
].join("\n")
|
|
226649
226652
|
);
|
|
226650
226653
|
}
|
|
226654
|
+
async function nextLines(ctx, paths2, dest) {
|
|
226655
|
+
const folder = relative12(ctx.io.cwd, resolve40(ctx.io.cwd, dest)) || ".", where2 = paths2.length === 1 ? relative12(ctx.io.cwd, paths2[0]) : `${folder}/*/scene.yaml`;
|
|
226656
|
+
const configured = ctx.globals().config !== void 0 || await access7(resolve40(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
|
|
226657
|
+
if (!configured) return [`next: ancha init (it writes ancha.yaml; set agent.command to the command that starts your agent), then ancha run ${where2}`];
|
|
226658
|
+
const globs = await ctx.loadConfig().then((config9) => config9.scenes, () => void 0);
|
|
226659
|
+
const found = globs === void 0 ? void 0 : new Set(await glob3(globs, { cwd: ctx.io.cwd, absolute: true, onlyFiles: true }));
|
|
226660
|
+
return [`next: ancha run ${where2}`, ...!found || paths2.every((path6) => found.has(path6)) ? [] : [`note: scenes: in ancha.yaml does not include ${where2}; add ${folder}/**/scene.yaml to run them with the rest`]];
|
|
226661
|
+
}
|
|
226651
226662
|
var when12 = (iso19) => iso19 ? `${new Date(iso19).toISOString().replace("T", " ").slice(0, 16)} UTC` : "-";
|
|
226652
226663
|
var plural5 = (n, one7, many = `${one7}s`) => `${n} ${n === 1 ? one7 : many}`;
|
|
226653
226664
|
function production2(trace) {
|
|
@@ -226759,7 +226770,7 @@ function registerTraces(program2, ctx) {
|
|
|
226759
226770
|
ctx.out.result(made.result, () => made.text);
|
|
226760
226771
|
return;
|
|
226761
226772
|
}
|
|
226762
|
-
const api3 = await workspaceApi(ctx);
|
|
226773
|
+
const api3 = await workspaceApi(ctx, `ancha import --offline ${options3.from ? `--from ${options3.from} ` : ""}${trace} makes the tests on this computer; ancha login sends traces to your workspace`);
|
|
226763
226774
|
const { traces: imported } = await api3(`/v1/imports?name=${encodeURIComponent(source.name)}`, { method: "POST", headers: { "content-type": options3.from ? "application/json" : "application/x-ndjson" }, body: source.text });
|
|
226764
226775
|
for (const { id: id12 } of imported) {
|
|
226765
226776
|
const changes = await guard(ctx, resolve40(ctx.io.cwd, options3.dest, `trace-${id12.slice(0, 8)}`), options3.force);
|
|
@@ -226951,6 +226962,7 @@ async function importLocally(ctx, source, options3) {
|
|
|
226951
226962
|
" the test has them only if the app makes them when it starts, or the start script or an app_calls entry does (ancha docs apps)"
|
|
226952
226963
|
);
|
|
226953
226964
|
}
|
|
226965
|
+
lines2.push(...await nextLines(ctx, [path6], options3.dest));
|
|
226954
226966
|
return { result: { scene: relative12(ctx.io.cwd, path6), summary: m.made.summary, questions: m.made.questions, setup: setup2 }, text: lines2.join("\n") };
|
|
226955
226967
|
}
|
|
226956
226968
|
const questions = [...new Map(made.flatMap((m) => m.made.questions).reverse().map((q) => [q.id, q])).values()].reverse();
|
|
@@ -226965,6 +226977,7 @@ async function importLocally(ctx, source, options3) {
|
|
|
226965
226977
|
];
|
|
226966
226978
|
const setups = made.filter((m) => m.made.setup.length).length;
|
|
226967
226979
|
if (setups) lines.push(` warning: in ${plural5(setups, "test")}, calls came before the first event the test replays, the app's own setup (provenance.json lists them; ancha docs apps)`);
|
|
226980
|
+
lines.push(...await nextLines(ctx, paths2, options3.dest));
|
|
226968
226981
|
return { result: { scenes: made.map((m, i) => ({ scene: relative12(ctx.io.cwd, paths2[i]), conversation: m.conversation.id, traces: m.conversation.traces, summary: m.made.summary, setup: setupOf(m) })), questions, skipped }, text: lines.join("\n") };
|
|
226969
226982
|
}
|
|
226970
226983
|
|
|
@@ -226974,15 +226987,16 @@ function processIO() {
|
|
|
226974
226987
|
return { stdout: process.stdout, stderr: process.stderr, cwd: process.cwd(), env: process.env };
|
|
226975
226988
|
}
|
|
226976
226989
|
var HELP_GROUPS = {
|
|
226977
|
-
"Start:": ["init", "run", "explain", "baseline", "docs"],
|
|
226990
|
+
"Start:": ["init", "import", "run", "explain", "baseline", "docs"],
|
|
226978
226991
|
"Cloud:": ["login", "whoami", "secrets", "traces"],
|
|
226979
|
-
"Inspect:": ["world", "test", "twins", "connect", "doctor"
|
|
226992
|
+
"Inspect:": ["world", "test", "twins", "connect", "doctor"],
|
|
226980
226993
|
"More:": ["completion"]
|
|
226981
226994
|
};
|
|
226982
|
-
var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "
|
|
226995
|
+
var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "pull", "schema", "logout"]);
|
|
226983
226996
|
var START = [
|
|
226984
226997
|
"Ancha: simulation playgrounds for agents. Start here:",
|
|
226985
226998
|
" ancha init set up this project: ancha.yaml, a starter scene, coding-agent instructions",
|
|
226999
|
+
" ancha import --offline <trace file> turn production traces into tests on this computer, one per conversation",
|
|
226986
227000
|
" ancha run run your agent against fresh worlds and grade it",
|
|
226987
227001
|
" ancha explain latest why it failed: each check, expected vs actual, the calls behind it",
|
|
226988
227002
|
" ancha login use your hosted workspace at app.ancha.io (one browser approval)",
|
package/lib/worker.mjs
CHANGED
|
@@ -161657,7 +161657,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir) {
|
|
|
161657
161657
|
return here === void 0 ? [] : [{ check: check3, production: result, failed: here.total - here.passed, total: here.total }];
|
|
161658
161658
|
});
|
|
161659
161659
|
const failedThere = checks.filter((c) => c.production === "failed");
|
|
161660
|
-
const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : "matches";
|
|
161660
|
+
const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
|
|
161661
161661
|
const added = Object.keys(scene2.checks).filter((check3) => !(check3 in production2.checks));
|
|
161662
161662
|
const counts = {};
|
|
161663
161663
|
for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
|
|
@@ -161670,7 +161670,8 @@ var SAY = {
|
|
|
161670
161670
|
partly: "production's failure happens here in part",
|
|
161671
161671
|
"not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
|
|
161672
161672
|
matches: "this run matches production, which passed these checks",
|
|
161673
|
-
differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)"
|
|
161673
|
+
differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
|
|
161674
|
+
unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
|
|
161674
161675
|
};
|
|
161675
161676
|
function renderReproduction(reproductions) {
|
|
161676
161677
|
return reproductions.map((r) => {
|
|
@@ -161682,6 +161683,8 @@ function renderReproduction(reproductions) {
|
|
|
161682
161683
|
...rows7,
|
|
161683
161684
|
`=> ${SAY[r.verdict]}`,
|
|
161684
161685
|
...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
|
|
161686
|
+
// A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
|
|
161687
|
+
...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
|
|
161685
161688
|
...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
|
|
161686
161689
|
// How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
|
|
161687
161690
|
...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ancha-labs/cli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, locally or hosted at app.ancha.io.",
|
|
6
6
|
"bugs": {
|