Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/3689-dashed-apify-references.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain": patch
---

`brain apify inspect`, `prepare`, `run`, `status`, `results` and `abort` now accept an Apify reference or run handle that starts with `--` in the documented positional form (#3689). These are random base64url values, and about one in 4,096 began with `--`. Until now the CLI refused those as `Unknown flag`. References keep their shape and entropy, stored values need no migration, and the `--` separator form still works.
24 changes: 23 additions & 1 deletion packages/core/src/cli/commands/apify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,28 @@ export const apifyCommandDeps: { create: (root: string) => StandaloneApify } = {
create: root => createStandaloneApify({ root }),
};

/**
* A consent reference or run handle that starts with `--`. Both are 32 random
* bytes in base64url, 43 characters (`reference`,
* packages/common/src/apify/consent.ts:412; the run handle,
* packages/common/src/apify/ledger.ts:390), and about one in 4,096 begins with
* `--`. No flag has this shape, so it is the positional value (#3689).
*/
const DASHED_REFERENCE = /^--[A-Za-z0-9_-]{41}$/u;

/**
* The arguments with each dashed reference before a bare `--` moved after one,
* where the shared parser keeps it positional verbatim. Everything else keeps
* its order, and values already after a separator are untouched.
*/
function referencesAsPositional(args: string[]): string[] {
const separator = args.indexOf("--");
const options = separator === -1 ? args : args.slice(0, separator);
const dashed = options.filter(arg => DASHED_REFERENCE.test(arg));
if (!dashed.length) return args;
return [...options.filter(arg => !DASHED_REFERENCE.test(arg)), "--", ...dashed, ...(separator === -1 ? [] : args.slice(separator + 1))];
}

function number(flag: string, value: string | boolean | undefined): number | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string" || !/^-?\d+(\.\d+)?$/u.test(value.trim())) throw new UsageError(`--${flag} needs a number.`);
Expand Down Expand Up @@ -94,7 +116,7 @@ export const apifyCommand: CoreCommand = {
summary: "Discover, inspect and run Apify Actors under the governance policy",
helpBlock: USAGE,
async run(args, cli) {
const { args: positional, flags } = parseArgs(args);
const { args: positional, flags } = parseArgs(referencesAsPositional(args));
const [word, ...rest] = positional;
if (!word) throw new UsageError(`Usage: ${USAGE.split("\n")[0]}`);
const common = ["json", "human", "session"];
Expand Down
31 changes: 31 additions & 0 deletions packages/ui-server/tests/apify-front-doors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* account, prices and origins are fictional.
*/
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import * as crypto from "node:crypto";
import { mkdtempSync, rmSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
Expand Down Expand Up @@ -221,6 +222,36 @@ describe("one implementation behind every front door", () => {
expect(fake.seen.every(entry => !entry.path.includes(APIFY_SENTINEL))).toBe(true);
});

test("references and run handles that start with -- work in the direct positional form (#3689)", async () => {
// Every 32-byte draw encodes to a distinct base64url value with a leading `--`, as one in 4,096
// real references and handles does: the consent reference and the ledger's run handle alike.
const real = crypto.randomBytes;
let draws = 0;
const forced = spyOn(crypto, "randomBytes").mockImplementation(((size: number, ...rest: unknown[]) => size === 32
? Buffer.from(`--odysseus${(++draws).toString(36)}`.padEnd(43, "A"), "base64url")
: (real as (...args: unknown[]) => Buffer)(size, ...rest)) as typeof crypto.randomBytes);
try {
apifyPolicy(brain, { enabled: true, discovery: "allow", actors: "allow", actor_grants: [apifyGrant()], limits: APIFY_LIMITS });
const approvals = openApifyLedger(ledgerPath);
approvals.setActorApproval({ brain_id: (await import("@schlessera/brain-common/internal/apify")).apifyBrainId(brain), principal_id: "local", account_id: "IthacaHousehold01" },
{ actor_id: "SeaCharts01", actor: "odysseus/sea-charts", approved_at: Date.now() }, true);
approvals.close();
const candidate = data<Array<{ candidate: string }>>((await cli(["approvals"])).envelope)[0]!.candidate;
expect(candidate, "APIFY_FORCED_DASHED_REFERENCE").toMatch(/^--[A-Za-z0-9_-]{41}$/u);
expect((await cli(["inspect", candidate])).envelope, "APIFY_DASHED_INSPECT").toMatchObject({ ok: true, operation: "inspect" });
// An existing stored value still resolves through the separator form, options before it.
expect((await cli(["inspect", "--", candidate])).envelope, "APIFY_DASHED_SEPARATOR").toMatchObject({ ok: true, operation: "inspect" });
const prepared = data<{ proposal: string }>((await cli(["prepare", candidate, "--input", JSON.stringify(APIFY_INPUT), "--max-charge-usd", "2"])).envelope);
expect(prepared.proposal, "APIFY_FORCED_DASHED_PROPOSAL").toMatch(/^--/u);
const started = data<{ run: string; state: string }>((await cli(["run", prepared.proposal])).envelope);
expect(started.run, "APIFY_FORCED_DASHED_HANDLE").toMatch(/^--[A-Za-z0-9_-]{41}$/u);
expect(code((await cli(["status", started.run])).envelope), "APIFY_DASHED_STATUS").toBe("ok");
expect(data<{ items: unknown[] }>((await cli(["results", started.run, "--limit", "2"])).envelope).items, "APIFY_DASHED_RESULTS").toHaveLength(2);
expect(data<{ outcome: string }>((await cli(["abort", started.run])).envelope).outcome, "APIFY_DASHED_ABORT").toBe("not_needed");
expect(fake.starts()).toBe(1);
} finally { forced.mockRestore(); }
});

test("the MCP wrappers keep a fixed roster and return discovered schemas as data", async () => {
apifyPolicy(brain, { enabled: true, discovery: "allow", actors: "allow", actor_grants: [apifyGrant()], limits: APIFY_LIMITS });
const door = await mcp();
Expand Down
Loading