@agency-tbd/cli 0.4.0 → 0.5.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/README.md CHANGED
@@ -77,7 +77,7 @@ influmode support list
77
77
 
78
78
  The draft adds only CLI version, Node.js version, OS identifier and CPU architecture. The server associates the report with your authenticated account and tenant IDs. **No files, logs, environment variables, tokens or cookies are collected automatically.** Remove credentials and unnecessary personal/customer data from the text yourself. Recognizable credentials and extra diagnostics are rejected; this check cannot detect every possible secret. The draft contains your report text: keep it private, and delete it when you no longer need its recovery key. POSIX files are created with mode 0600; on Windows, use a directory private to your OS account.
79
79
 
80
- Submission returns `receipt.reference`, `receipt.submitted`, `receipt.state` and recovery instructions. Only `submitted:true` confirms that GitHub accepted an issue. Unconfirmed or failed submission returns `ok:false` and a nonzero exit status while preserving the receipt. `pending` is uncertain delivery; keep the original draft and check status. `failed` means screenshot storage failed before contacting GitHub or GitHub definitively rejected the send; the receipt explains what to do. A closed issue indicates closure, not necessarily that a fix was released or a request accepted. `status` retains its delivery/open/closed compatibility contract. CLI 0.4.0 adds `get`, chronological `history`, paginated `list`, replies, explicit read receipts and incremental changes. Only your reports, your own replies and explicitly published team replies are visible; internal staff notes, repository URLs, code and other accounts stay private.
80
+ Submission returns `receipt.shortReference` (for example `INF-123`), the original UUID `receipt.reference`, `receipt.priority` (nullable), `receipt.submitted`, `receipt.state` and recovery instructions. Only `submitted:true` confirms that GitHub accepted an issue. Unconfirmed or failed submission returns `ok:false` and a nonzero exit status while preserving the receipt. `pending` is uncertain delivery; keep the original draft and check status. `failed` means screenshot storage failed before contacting GitHub or GitHub definitively rejected the send; the receipt explains what to do. A closed issue indicates closure, not necessarily that a fix was released or a request accepted. `status` retains its delivery/open/closed compatibility contract. CLI 0.4.0 adds `get`, chronological `history`, paginated `list`, replies, explicit read receipts and incremental changes. Only your reports, your own replies and explicitly published team replies are visible; internal staff notes, repository URLs, code and other accounts stay private.
81
81
 
82
82
  After any interrupted send, use `support status --input @support-draft.json`. A missing receipt means no reservation exists yet; retry only the **exact same saved draft**, after correcting any reported login/configuration/input issue. Concurrent or repeated submissions of the same draft create at most one issue; changed content under the same request ID is a conflict. Never create a new draft to retry an uncertain send. If delivery remains pending, give the support reference to your InfluMode administrator for reconciliation. The CLI never automatically repeats an issue creation.
83
83
 
@@ -127,7 +127,15 @@ Cursor pagination uses `--max-pages N`, optionally `--cursor-field nextCursor --
127
127
 
128
128
  `batch --input @operations.json` takes an array of `{ "resource": "clients", "path": ["list"], "input": { "limit": 1 } }` entries. Execution is sequential and non-atomic, stops at the first failure, and reports completed/remaining entries. `--dry-run` validates entries without executing their business handlers. Never rerun an entire partially completed batch blindly.
129
129
 
130
- Use `files routes` before `files upload <route> <file...> --type MIME`; inspect required metadata and supply it with `--input`. Downloads use `files download <key> --output new-file`. Provider OAuth and device approval require browser consent. Provider credentials and provider readiness remain separate constraints.
130
+ Use `files routes` before `files upload <route> <file...> --type MIME` to see each route's accepted types and size limits. File uploads are not API operations: `operations file-uploads` only lists and deletes existing files. Downloads use `files download <key> --output new-file`.
131
+
132
+ To attach a receipt, upload it to the `paymentDocument` route (images and PDF, 4 MB each), which needs permission to edit campaigns. Each result has a `key` and a `reference`. Save the `reference`, such as `/api/files/<key>`, as `receiptUrl` with `financial recordPayment`, or with `financial updatePaymentMetadata` when the payment is already recorded; a bare key is rejected. Uploading never records or settles a payment.
133
+
134
+ After an uncertain link, read the payment back before repeating anything. An uncertain upload changes no payment, and repeating it stores a new file. `file-uploads list` needs user-management permission and does not show which payment uses a file.
135
+
136
+ Upload failures name the server's reason, such as `FILE_TOO_LARGE`, and list any files already completed. `INCOMPATIBLE_SERVER` means the installed CLI and the server have diverged: update the CLI rather than guessing another endpoint. CLI 0.5.0 cannot upload files or list upload routes, because it calls a route the server no longer has; use 0.5.1 or later.
137
+
138
+ Provider OAuth and device approval require browser consent. Provider credentials and provider readiness remain separate constraints.
131
139
 
132
140
  `http` is an advanced same-origin escape hatch. The route inventory contains internal-service routes, provider callbacks and webhooks as well as ordinary app endpoints. Listing does not imply bearer-token support or permission; follow the existing application flow and never invoke callbacks or webhooks as substitutes for it. Raw HTTP has no generic dry-run. See [HTTP transport](src/transport.ts) and [file transport](src/files.ts).
133
141
 
@@ -173,7 +181,24 @@ For repository development, install dependencies with `pnpm install --frozen-loc
173
181
 
174
182
  Before publishing, run `pnpm --filter @agency-tbd/cli release:check` on a supported Node.js release. It runs type checks, CLI tests, catalog validation and an isolated npm installation of the actual packed archive. Package contents are limited to compiled JavaScript, the README and package metadata; repository source, tests, source maps and local configuration are excluded. `pnpm pack` replaces workspace catalog references with installable dependency versions.
175
183
 
176
- Publish reviewed, merged releases with the manually dispatched [Publish CLI workflow](../../.github/workflows/publish-cli.yml). Select `main` and supply the full reviewed commit SHA, the CLI version and confirmation that required backend migrations/deployment have been verified. The workflow requires passing main CI for that exact source, repeats package qualification, and publishes the same archived bytes using npm's short-lived GitHub identity. A separate job with no publishing permission verifies registry integrity, the `latest` tag and an anonymous installation. Only readback requests may be retried for bounded registry propagation; the publish command is never retried automatically. It has no npm token and requires no per-release security-key challenge. A failed or timed-out publication must be reconciled against the registry before another dispatch; an existing version is rejected rather than republished.
184
+ [`published-http-routes.json`](published-http-routes.json) names the oldest supported CLI release and lists every route and named resource that supported releases need. Tests fail if the CLI calls something undeclared or the server removes something listed. Add new calls when you write them. Remove an entry only after a CLI without it is on npm, and only with the version raised to that release. Tests cannot see npm, so reviewers must check that step. Merging does not publish: until the release is on npm, `@latest` keeps the old behavior.
185
+
186
+ Hosted Actions cannot currently start jobs, so publish from this Mac with the [release script](../../scripts/cli-release.mjs). Log in with `npm login` as a package maintainer, check out the latest `main`, and first confirm that required backend migrations and deployment are done:
187
+
188
+ ```sh
189
+ corepack pnpm cli:publish --sha <main-commit> --version <version> --dry-run
190
+ corepack pnpm cli:publish --sha <main-commit> --version <version> --backend-ready
191
+ ```
192
+
193
+ The command requires that the commit is the latest `main`, is the merge of a pull request whose identical source passed `local-gate/ci:check` with the service suites, and has that unpublished version. It builds and qualifies a fresh copy of the commit with a frozen install, publishes once using npm's own authentication prompts, then checks the registry archive, the `latest` tag and an anonymous installation. `--dry-run` needs no login and writes nothing to the registry: it stops at `npm publish --dry-run`, then runs the anonymous-install check against the current `latest`. Unknown flags are refused.
194
+
195
+ If you interrupt a run, its temporary copy stays registered; `git worktree prune` clears it once the folder is gone.
196
+
197
+ `npm publish` is never retried. After an uncertain result the archive is kept, its path and integrity are printed, and `node scripts/cli-release.mjs verify-published <version> <integrity>` rechecks the registry.
198
+
199
+ Publishing this way gives up safeguards the workflow has: npm's short-lived trusted identity, the environment's `main`-only rule, separate jobs for publishing and verifying, and pinned Node.js and npm versions. The gate status is reported by a local machine, so it is only as strong as the accounts that can write commit statuses.
200
+
201
+ If Actions runs again, the manually dispatched [Publish CLI workflow](../../.github/workflows/publish-cli.yml) applies the same source check. Select `main` and supply the full reviewed commit SHA, the CLI version and confirmation that required backend migrations/deployment have been verified. The workflow repeats package qualification, and publishes the same archived bytes using npm's short-lived GitHub identity. A separate job with no publishing permission verifies registry integrity, the `latest` tag and an anonymous installation. Readback waits up to ten minutes for the version, latest tag and npm installation metadata to agree, then installs with a fresh anonymous cache. Only readback requests may be retried; the publish command is never retried automatically. It has no npm token and requires no per-release security-key challenge. A failed or timed-out publication must be reconciled against the registry before another dispatch; an existing version is rejected rather than republished.
177
202
 
178
203
  One-time setup by a package maintainer:
179
204
 
@@ -182,7 +207,7 @@ One-time setup by a package maintainer:
182
207
  3. In the [npm package settings](https://www.npmjs.com/package/@agency-tbd/cli/access), add a GitHub Actions trusted publisher for owner `eternalwaitt`, repository `agency-tbd`, workflow filename `publish-cli.yml`, environment `npm-publish`, and direct `npm publish` permission. This configuration requires npm's security-key authorization once. Equivalently, use `npm trust github @agency-tbd/cli --repo eternalwaitt/agency-tbd --file publish-cli.yml --environment npm-publish --allow-publish` with a supported npm CLI and complete that one setup authorization. Preserve any existing publisher configurations.
183
208
  4. Run the workflow for the reviewed main SHA and inspect its registry/install verification. Trust setup alone does not prove a publication works. This repository is private, so npm provenance is disabled; the workflow still authenticates through OIDC and verifies the archive checksum.
184
209
 
185
- For a one-off interactive fallback, use `pnpm --filter @agency-tbd/cli release:publish` from a clean, merged checkout with an authorized npm account. npm may require a separate 2FA challenge for each publish even after login. Do not use repeated login/publish attempts as the normal release process. Direct-publish bypass tokens are being retired in January 2027; they are not the durable automation path. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) and [token policy](https://docs.npmjs.com/about-access-tokens/).
210
+ npm may require a separate 2FA challenge for each publish even after login. Do not use repeated login/publish attempts as the normal release process. Direct-publish bypass tokens are being retired in January 2027; they are not the durable automation path. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) and [token policy](https://docs.npmjs.com/about-access-tokens/).
186
211
 
187
212
  CLI-only releases need no application deployment. New server-backed features such as support require the matching backend migration, configuration and deployment before publishing the CLI that advertises them. For each subsequent release, increment `apps/cli/package.json`'s version before review and publication; the CLI version output and API compatibility header read that same version. Do not reuse a published version. Do not claim installation from the registry works until the release is visible and verified there.
188
213
 
@@ -243,3 +268,69 @@ influmode support operation --input @read-draft.json
243
268
  ```
244
269
 
245
270
  Use the observed `revision` as `through` after reviewing the desired history; do not guess it. `read` advances the read position monotonically and returns `acknowledgedThrough`; later arrivals remain unread. `changes` uses a per-request import cursor, while `history` sorts by authorship date. They are different cursors. Only `relevant:true` events (team replies and issue state changes) should trigger an alert; the reporter's own replies and read receipts do not. Incremental queries do not install monitoring. Background notices require a separately configured and authorized scheduler and the user's chosen channel/preferences. CLI use alone never promises background follow-up.
271
+
272
+ ## Short references and requester priority
273
+
274
+ CLI **0.5.0** requires the matching backend and support reference/priority migration.
275
+ Receipts, status, detail and list include a permanent `shortReference` such as
276
+ `INF-123` alongside the original UUID and title. Existing reports gain a number
277
+ without changing identity/history. Status/get/history/changes/reply/read/priority
278
+ and list reference filters accept either format; existing UUID drafts still work.
279
+ Numbers are global, but every query remains private to the authenticated tenant
280
+ **and reporter**. Neither reference reveals the private repository issue number.
281
+
282
+ `support info` advertises `short-references`, `requester-priority`, allowed priorities
283
+ and their authority. Priority is **requester-indicated impact**, not internal team
284
+ triage or a response/resolution SLA. Values are `low`, `normal`, `high`, `urgent`,
285
+ or `null` (undefined); old reports stay undefined. The report JSON may optionally
286
+ include priority. Never infer urgency from text or change it without authorization.
287
+
288
+ Read `support info` and `support get INF-123` first. Use the observed value as
289
+ `expectedPriority`; concurrent edits return a conflict rather than overwriting it:
290
+
291
+ ```sh
292
+ influmode support draft-priority INF-123 --input '{"expectedPriority":null,"priority":"high","reason":"Approved workflow impact"}' --output priority-draft.json
293
+ influmode support preview --input @priority-draft.json
294
+ # Show the exact change and obtain approval first.
295
+ influmode support priority --input @priority-draft.json --confirm
296
+ influmode support get INF-123
297
+ influmode support history INF-123
298
+ # Recover an uncertain response using the same file/requestId.
299
+ influmode support operation --input @priority-draft.json
300
+ ```
301
+
302
+ Changes preserve the report and record previous/new values, author, date and optional
303
+ reason atomically. Only the same reporter with support permission can edit this
304
+ field; it cannot impose internal team priority. Replaying the same saved operation
305
+ returns its receipt without duplicating history. No GitHub comment or label changes.
306
+
307
+ ```sh
308
+ influmode support list --input '{"priority":"high","order":"priority","limit":25}'
309
+ influmode support list --input '{"priority":null,"limit":25}'
310
+ ```
311
+
312
+ Priority order is urgent/high/normal/low/undefined; ties use updated time descending,
313
+ then UUID descending. Activity remains the default order. Follow `nextCursor` with
314
+ the same filters/order; restart when those change. Pagination is over a changing
315
+ list, so restart for a current inventory if reports change while paging. Deploy the
316
+ backend/migration before publishing the CLI; publishing is a separate action.
317
+
318
+ ## Externally signed participant contracts
319
+
320
+ For a final PDF already signed outside Influmode and retained in Google Drive, discover
321
+ `help contracts registerExternalDocument`. Use a new, untouched influencer contract draft
322
+ (with no versions, signers or signature invitations), the exact Drive file-view HTTPS URL,
323
+ filename and SHA-256 supplied by the operator, and `signedExternally:true` only after the
324
+ operator has confirmed external signing. This registers a reference; it does not upload or
325
+ fetch the PDF, verify its bytes/signatures, change Drive sharing, or send an invitation.
326
+ The contract becomes active with `signingSource:external`; its hash is operator-attested.
327
+ No signer records or signing timestamps are invented. The reference is immutable through
328
+ this operation and `addVersion`; repeating the identical registration is a no-op, and a
329
+ changed payload is rejected.
330
+
331
+ Read the contract back, then use `campaigns linkInfluencerContract` with the exact participant
332
+ and matching influencer contract. Read that participant back before proceeding to another.
333
+ The existing participant-link checks prevent cross-influencer and cross-tenant association;
334
+ replacing an existing link requires its previously read contract ID. These commands remain
335
+ subject to normal business-write approval. `contracts addVersion` continues to accept only
336
+ tenant-owned uploaded files and must not be used for a Drive reference.
package/dist/agent.js CHANGED
@@ -23,6 +23,11 @@ export const agentGuide = {
23
23
  retry: "Never automatically retry a mutation after an ambiguous failure; inspect saved state first.",
24
24
  coverage: "API access does not reproduce UI preparation or prove every workflow is executable.",
25
25
  },
26
+ files: {
27
+ upload: "File uploads are not API operations: run influmode files routes, then influmode files upload <route> <file> --type MIME. operations file-uploads only lists and deletes existing files.",
28
+ receipts: "Upload to the paymentDocument route, which needs permission to edit campaigns. Save the returned reference (not the key) as receiptUrl with financial recordPayment, or with financial updatePaymentMetadata when the payment is already recorded. Uploading never records or settles a payment.",
29
+ recovery: "After an uncertain link, read the payment back before repeating anything. An uncertain upload changes no payment; a repeat stores a new file. file-uploads list needs user-management permission and does not show which payment uses a file.",
30
+ },
26
31
  support: {
27
32
  purpose: "Report bugs, compatibility problems, missing platform features or questions to the InfluMode team without GitHub access.",
28
33
  help: "influmode support --help",
@@ -41,6 +46,8 @@ export const agentGuide = {
41
46
  reply: "support draft-reply <reference> --input @reply.json --output reply-draft.json; preview, show destination/text, obtain approval, then support reply --input @reply-draft.json --confirm",
42
47
  resolution: "kind:resolved confirms verification; kind:persists requests review/reopening without applying administrative reopening. get shows communicated outcome/releaseVersion, never infers delivered from closed.",
43
48
  changes: "support changes <reference> --input with after/limit or since; persist nextCursor with the same reference/account and exhaust hasMore. Notify only for relevant:true events.",
49
+ references: "Use receipt.shortReference (INF-N) and title in confirmations. UUID remains valid. Every operation accepts INF-N; scope remains the current tenant and reporter.",
50
+ priority: "Read support info and get first. Priority is requester-indicated impact only, never team triage/SLA. Do not infer urgency. With explicit authorization, prepare draft-priority with expectedPriority, priority and optional reason; preview and confirm, recover via operation using the same saved draft. Null is undefined; old reports stay undefined. List accepts priority and order:priority.",
44
51
  read: "Reads do not acknowledge. Prepare support draft-read with through:observedRevision, then support read --confirm. Receipt acknowledgedThrough is idempotent; later updates remain unread.",
45
52
  operationRecovery: "support operation --input @original-reply-or-read-draft.json; reuse exact requestId/payload only",
46
53
  notification: "Incremental queries are active reads. Background alerts need separately configured and authorized scheduling, channel and user preferences. Do not promise background monitoring.",
package/dist/catalog.js CHANGED
@@ -57,6 +57,7 @@ export const resources = [
57
57
  export const httpRoutes = [
58
58
  "/api/auth/[...all]",
59
59
  "/api/contact",
60
+ "/api/cron/sponsorship-workbooks",
60
61
  "/api/email/oauth",
61
62
  "/api/email/oauth/callback",
62
63
  "/api/files/[fileKey]",
@@ -82,8 +83,8 @@ export const httpRoutes = [
82
83
  "/api/social-auth/instagram/deletion-status/[code]",
83
84
  "/api/status",
84
85
  "/api/status/source",
85
- "/api/uploadthing",
86
- "/api/uploadthing/webhook",
86
+ "/api/uploads",
87
+ "/api/uploads/[slug]",
87
88
  "/api/v1/analytics/influencer-report/export",
88
89
  "/api/v1/analytics/network-cash-lane-details/export",
89
90
  "/api/v1/contract-generation/download",
package/dist/commands.js CHANGED
@@ -3,7 +3,7 @@ import { positive } from "./args.js";
3
3
  import { logout, status } from "./auth.js";
4
4
  import { CliError } from "./errors.js";
5
5
  import { batch, call } from "./execute.js";
6
- import { download, upload } from "./files.js";
6
+ import { download, routes, upload } from "./files.js";
7
7
  import { readJson } from "./input.js";
8
8
  import { saveOutput } from "./output.js";
9
9
  import { describe } from "./schema.js";
@@ -79,9 +79,9 @@ async function callOptions(values) {
79
79
  async function fileCommand(connection, { values, positionals }) {
80
80
  const [, subcommand, ...rest] = positionals;
81
81
  if (subcommand === "routes")
82
- return (await http(connection, "/api/uploadthing")).json();
82
+ return routes(connection);
83
83
  if (subcommand === "upload" && rest[0])
84
- return upload(connection, rest[0], rest.slice(1), values.type ?? "application/octet-stream", await readJson(values.input), values["dry-run"] ?? false);
84
+ return upload(connection, rest[0], rest.slice(1), values.type ?? "application/octet-stream", values["dry-run"] ?? false);
85
85
  if (subcommand === "download" && rest[0] && values.output)
86
86
  return download(connection, rest[0], values.output);
87
87
  throw new CliError("USAGE", "Use files routes, upload <route> <file...> --type MIME, or download <key> --output file", 2);
package/dist/files.js CHANGED
@@ -1,82 +1,111 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { readFile } from "node:fs/promises";
2
3
  import { basename } from "node:path";
3
4
  import { CliError } from "./errors.js";
4
5
  import { saveOutput } from "./output.js";
5
- import { http } from "./transport.js";
6
- /** Uses the same tenant-authorized UploadThing handshake and completion callback as the UI. */
7
- export async function upload(connection, slug, filenames, type, input, dryRun) {
6
+ import { apiPath, http } from "./transport.js";
7
+ import { cliVersion } from "./version.js";
8
+ /** Failures whose own code tells the caller what to do next, unlike a generic upload failure. */
9
+ const SELF_EXPLAINING_CODES = new Set(["INCOMPATIBLE_SERVER", "UNKNOWN_UPLOAD_ROUTE"]);
10
+ function isRecord(value) {
11
+ return typeof value === "object" && value !== null;
12
+ }
13
+ /** A route that should exist returned 404: the installed CLI and this server have diverged. */
14
+ function incompatibleServer(pathname) {
15
+ return new CliError("INCOMPATIBLE_SERVER", `CLI ${cliVersion} and this server do not match: ${pathname} does not exist. Update with npm install --global @agency-tbd/cli@latest; if it is already the latest, report it with influmode support.`, 5, { cliVersion, path: pathname, status: 404 });
16
+ }
17
+ /** Lists the upload routes with their accepted types and size limits. */
18
+ export async function routes(connection) {
19
+ try {
20
+ return (await (await http(connection, "/api/uploads")).json());
21
+ }
22
+ catch (error) {
23
+ if (error instanceof CliError &&
24
+ error.code === "HTTP_ERROR" &&
25
+ isRecord(error.details) &&
26
+ error.details["status"] === 404)
27
+ throw incompatibleServer("/api/uploads");
28
+ throw error;
29
+ }
30
+ }
31
+ /** A system code or error type only: a transport message may repeat local or request details. */
32
+ function transportCause(error) {
33
+ const code = isRecord(error.cause) ? error.cause["code"] : undefined;
34
+ return typeof code === "string" ? code : error.name;
35
+ }
36
+ /** Keeps the reason a file failed alongside the files that were already stored. */
37
+ function batchFailure(error, completed, failedIndex) {
38
+ const failed = error instanceof CliError ? error : null;
39
+ return new CliError(failed && SELF_EXPLAINING_CODES.has(failed.code) ? failed.code : "UPLOAD_FAILED", `${failed?.message ?? "File upload failed"}; inspect completed files before retrying`, failed?.exitCode ?? 1, {
40
+ completed,
41
+ failedIndex,
42
+ ...(failed?.details ? { failure: failed.details } : {}),
43
+ ...(!failed && error instanceof Error ? { failure: { cause: transportCause(error) } } : {}),
44
+ });
45
+ }
46
+ /** Sends each file to the same tenant-authorized private upload route the UI uses. */
47
+ export async function upload(connection, slug, filenames, type, dryRun) {
8
48
  if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(slug) || !filenames.length)
9
49
  throw new CliError("USAGE", "Use files upload <route> <file...> --type <mime>", 2);
10
50
  const files = await Promise.all(filenames.map(async (name) => new File([await readFile(name)], basename(name), { type })));
11
- const body = {
12
- input: input ?? null,
13
- files: files.map((file) => ({
14
- name: file.name,
15
- size: file.size,
16
- type: file.type,
17
- lastModified: file.lastModified,
18
- })),
19
- };
51
+ const described = files.map((file) => ({ name: file.name, size: file.size, type: file.type }));
20
52
  if (dryRun)
21
- return { executed: false, validated: false, route: slug, files: body.files };
22
- const response = await http(connection, `/api/uploadthing?actionType=upload&slug=${encodeURIComponent(slug)}`, "POST", body, { "x-uploadthing-version": "7.7.4", "x-uploadthing-package": "influmode-cli" });
23
- const data = await response.json();
24
- if (!Array.isArray(data) || data.length !== files.length)
25
- throw new CliError("UPLOAD_PROTOCOL_ERROR", "Invalid upload allocation", 1);
53
+ return { executed: false, validated: false, route: slug, files: described };
26
54
  const results = [];
27
- for (const [index, raw] of data.entries()) {
28
- const file = files[index];
29
- if (!file)
30
- throw new CliError("UPLOAD_PROTOCOL_ERROR", "Missing upload file", 1);
55
+ for (const [index, file] of files.entries()) {
31
56
  try {
32
- results.push(await uploadAllocated(connection, raw, file));
57
+ results.push(await uploadOne(connection, slug, file));
33
58
  }
34
- catch {
35
- throw new CliError("UPLOAD_FAILED", "File upload failed; inspect completed files before retrying", 1, { completed: results, failedIndex: index });
59
+ catch (error) {
60
+ throw batchFailure(error, results, index);
36
61
  }
37
62
  }
38
63
  return { files: results };
39
64
  }
40
- function uploadTarget(raw) {
41
- if (!raw ||
42
- typeof raw !== "object" ||
43
- !("url" in raw) ||
44
- typeof raw.url !== "string" ||
45
- !("key" in raw) ||
46
- typeof raw.key !== "string")
47
- throw new CliError("UPLOAD_PROTOCOL_ERROR", "Invalid upload target", 1);
48
- const url = new URL(raw.url);
49
- if (url.protocol !== "https:" ||
50
- url.username ||
51
- url.password ||
52
- !url.hostname.endsWith(".ingest.uploadthing.com"))
53
- throw new CliError("UPLOAD_PROTOCOL_ERROR", "Untrusted upload target", 1);
54
- return { url, key: raw.key };
55
- }
56
- async function uploadAllocated(connection, raw, file) {
57
- const { url, key } = uploadTarget(raw);
58
- const form = new FormData();
59
- form.append("file", file);
60
- // Bearer credentials are sent only to Influmode, never to storage.
61
- const uploaded = await fetch(url, {
62
- method: "PUT",
63
- body: form,
64
- headers: { Range: "bytes=0-", "x-uploadthing-version": "7.7.4" },
65
- redirect: "error",
65
+ async function uploadOne(connection, slug, file) {
66
+ const response = await fetch(apiPath(connection.origin, `/api/uploads/${slug}`), {
67
+ method: "POST",
68
+ body: new Uint8Array(await file.arrayBuffer()),
69
+ headers: {
70
+ Authorization: `Bearer ${connection.token}`,
71
+ "content-type": file.type || "application/octet-stream",
72
+ // The upload route accepts only requests that name the app's own origin.
73
+ origin: connection.origin,
74
+ "x-correlation-id": connection.requestId ?? randomUUID(),
75
+ "x-upload-file-name": encodeURIComponent(file.name),
76
+ },
77
+ redirect: "manual",
66
78
  signal: AbortSignal.timeout(connection.timeout),
67
79
  });
68
- if (!uploaded.ok)
69
- throw new CliError("UPLOAD_FAILED", `Upload failed with HTTP ${uploaded.status}; inspect completed files before retrying`, 1);
70
- const result = await uploaded.json();
71
- if (!result || typeof result !== "object" || "error" in result)
72
- throw new CliError("UPLOAD_FAILED", "Upload completion failed", 1);
80
+ if (!response.ok)
81
+ throw await uploadFailure(response, slug);
82
+ const result = await response.json();
83
+ if (!isRecord(result) || typeof result["key"] !== "string")
84
+ throw new CliError("UPLOAD_PROTOCOL_ERROR", "Invalid upload response", 1);
85
+ const reference = isRecord(result["serverData"]) ? result["serverData"]["fileUrl"] : undefined;
73
86
  return {
74
- key,
87
+ key: result["key"],
75
88
  name: file.name,
76
89
  size: file.size,
77
- ...("serverData" in result ? { serverData: result.serverData } : {}),
90
+ // The form receiptUrl and other file fields accept; a bare key is rejected there.
91
+ ...(typeof reference === "string" ? { reference } : {}),
92
+ ...("serverData" in result ? { serverData: result["serverData"] } : {}),
78
93
  };
79
94
  }
95
+ /** The server's stable failure code, when the response carries one. */
96
+ async function failureCode(response) {
97
+ const body = await response.json().catch(() => null);
98
+ const code = isRecord(body) ? body["code"] : null;
99
+ return typeof code === "string" && /^[A-Z_]{1,64}$/u.test(code) ? code : null;
100
+ }
101
+ async function uploadFailure(response, slug) {
102
+ const code = await failureCode(response);
103
+ if (code === "UNKNOWN_UPLOAD_ROUTE")
104
+ return new CliError(code, `Unknown upload route ${slug}; run influmode files routes`, 2);
105
+ if (response.status === 404)
106
+ return incompatibleServer(`/api/uploads/${slug}`);
107
+ return new CliError("UPLOAD_FAILED", `Upload failed with HTTP ${response.status}${code ? ` (${code})` : ""}`, response.status === 401 ? 3 : response.status === 403 ? 4 : 1, { status: response.status, ...(code ? { code } : {}) });
108
+ }
80
109
  export async function download(connection, key, output) {
81
110
  return saveOutput(output, () => http(connection, `/api/files/${encodeURIComponent(key)}`));
82
111
  }
package/dist/help.js CHANGED
@@ -14,15 +14,19 @@ influmode support preview --input @reply-draft.json
14
14
  influmode support reply --input @reply-draft.json --confirm [--dry-run]
15
15
  influmode support draft-read <reference> --input '{"through":25}' --output read-draft.json
16
16
  influmode support read --input @read-draft.json --confirm
17
+ influmode support draft-priority INF-123 --input '{"expectedPriority":null,"priority":"high","reason":"Blocked workflow"}' --output priority-draft.json
18
+ influmode support priority --input @priority-draft.json --confirm [--dry-run]
17
19
  influmode support operation --input @reply-draft.json
18
20
  Reply JSON: {"text":"Your exact reply","kind":"reply|resolved|persists"}.
19
- List filters: cursor, reference, search, category, state, limit. Follow nextCursor until null.
21
+ References accept INF-N or the original UUID for status/get/history/changes/reply/read/priority/list. shortReference is stable globally; access remains restricted to your authenticated tenant and reporter. Older drafts and UUIDs remain valid.
22
+ Priority is optional requester-indicated impact: low, normal, high, urgent or null (undefined). Old requests stay undefined. Read support info for allowed options and support get for the current value before preparing a change; expectedPriority prevents overwriting another change. Never infer urgency or change it without authorization. This does not change internal triage or promise a deadline/SLA. History records previous/new priority, reason, author and date; recover uncertain changes with the exact saved requestId.
23
+ List filters: cursor, reference, search, category, state, priority (including null), order (activity|priority), limit. Priority order is urgent/high/normal/low/undefined, ties by activity descending then UUID descending. Cursors belong to the same filters/order; restart when those change. Follow nextCursor until null.
20
24
  History is chronological; pass its nextCursor as cursor. Changes are incremental in import order; persist nextCursor as after with the same reference/account. since accepts an ISO date. hasMore means another page remains.
21
25
  Only explicitly published team responses appear; internal GitHub discussion stays private. Reading never clears unread updates. Explicit read acknowledges through the observed revision; its receipt includes acknowledgedThrough. operation recovers either a reply or read receipt by the saved requestId. After a timeout retain and reconcile the same draft; no automatic mutation retries.
22
26
  resolved confirms the requester verified the result; persists asks the team to review/reopen. Neither changes administrative issue state. Closure alone does not prove a fix; get shows only communicated progress, reason, outcome, resolution, nextStep and releaseVersion.
23
27
  Changes is a bounded incremental query, not background monitoring. Notify only when returned events have relevant:true. Background notices need a separately configured, authorized schedule and user-chosen channel/preferences.
24
28
  Conversation commands require backend conversationVersion:1 (matching migration/deployment). No repository access is needed.
25
- Report JSON: {"category":"bug|compatibility|feature|question","title":"Short summary","description":"Steps, expected and actual behavior; at least 20 characters"}.
29
+ Report JSON accepts optional priority (low|normal|high|urgent|null): {"category":"bug|compatibility|feature|question","title":"Short summary","description":"Steps, expected and actual behavior; at least 20 characters"}.
26
30
  Draft/preview are offline. Draft adds only CLI/Node/OS/architecture diagnostics and saves a private file. Review the exact report and destination, remove secrets/private customer data, obtain approval, then submit. Login uses your InfluMode account; no GitHub account or repository access is needed. Keep the same draft/requestId for recovery: an uncertain send must never be repeated with a new draft. Status and list show only your reports; private repository links, code and internal staff notes stay private. Repeat --attach for up to 5 PNG/JPEG/WebP screenshots (4 MiB each, 10 MiB total). Draft snapshots the exact bytes offline; preview shows names, sizes and SHA-256 hashes, never image bytes. Only confirmed submit uploads them. Screenshots stay private; the team must sign in to the reporting tenant to open them. No other files, logs or environment variables are automatically attached. Run help support <operation> for live API schemas; use call support <operation> for generic API access.`,
27
31
  auth: "influmode auth login --url <HTTPS_ORIGIN> [--no-browser]\ninflumode auth status\ninflumode auth logout\nBrowser approval is required for login. Status confirms identity, not effective operation permissions. Logout revokes the session.\nFor the auth API group, inspect help auth <operation> and execute with call auth <operation>.",
28
32
  resources: "influmode resources [--search text]\nOffline API group and HTTP route inventory. HTTP routes can require browser, provider or internal-service credentials; listing is not execution permission.",
@@ -30,7 +34,7 @@ Draft/preview are offline. Draft adds only CLI/Node/OS/architecture diagnostics
30
34
  capabilities: "influmode capabilities [resource] [--search text]\nRead current account context and explicit execution limits. Optional resource adds live operation summaries. Effective operation permissions are not evaluated.",
31
35
  schema: "influmode schema <resource> [operation.path]\nLive JSON input/output schemas. Requires login. Discovery does not evaluate permission or business state.",
32
36
  batch: 'influmode batch --input @operations.json [--dry-run]\nInput: [{"resource":"clients","path":["list"],"input":{"limit":1}}]\nSequential, non-atomic; stops at the first failure. Inspect completed results before resuming. Dry-run validates inputs only.',
33
- files: "influmode files routes\ninflumode files upload <route> <file...> --type MIME [--input @metadata.json]\ninflumode files download <key> --output new-file\nInspect routes and required metadata first. Upload writes to the configured storage provider. Downloads never overwrite files.",
37
+ files: "influmode files routes\ninflumode files upload <route> <file...> --type MIME\ninflumode files download <key> --output new-file\nInspect routes and their file limits first. Upload writes to Influmode private storage and returns a key and a reference. Use paymentDocument for receipts, then save that reference (not the key) in receiptUrl. Uploading never records or settles a payment. Downloads never overwrite files.",
34
38
  http: "influmode http <GET|POST|PUT|PATCH|DELETE> /api/path [--input @input.json] [--output new-file]\nAdvanced escape hatch, restricted to the selected origin. Inspect the existing application flow first. No generic dry-run support. Do not use it to bypass permissions.",
35
39
  call: "influmode call <resource> <operation.path> --input @input.json [--dry-run]\nEquivalent to influmode <resource> <operation.path>. Get the live schema first. Dry-run checks input only.",
36
40
  guide: "influmode guide [--json]\nOffline agent workflow, execution limits, input conventions and recovery. skill is an alias.",
package/dist/main.js CHANGED
@@ -49,7 +49,7 @@ async function offlineCommand(parsed) {
49
49
  },
50
50
  };
51
51
  if (command === "support" &&
52
- ["draft", "draft-reply", "draft-read", "preview"].includes(subcommand ?? ""))
52
+ ["draft", "draft-reply", "draft-read", "draft-priority", "preview"].includes(subcommand ?? ""))
53
53
  return { handled: true, result: await offlineSupport(parsed) };
54
54
  return { handled: false };
55
55
  }
@@ -6,21 +6,48 @@ import { saveOutput } from "./output.js";
6
6
  import { snapshotAttachments, validateAttachments, attachmentPreview, } from "./support-attachments.js";
7
7
  import { rpc } from "./transport.js";
8
8
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ function reference(value) {
10
+ return (uuid.test(value) ||
11
+ (/^INF-[1-9][0-9]{0,9}$/.test(value) && Number(value.slice(4)) <= 2147483647));
12
+ }
13
+ function priority(value) {
14
+ return (value === null ||
15
+ (typeof value === "string" && ["low", "normal", "high", "urgent"].includes(value)));
16
+ }
9
17
  function object(value) {
10
18
  return !!value && typeof value === "object" && !Array.isArray(value);
11
19
  }
12
20
  function invalid() {
13
- throw new CliError("SUPPORT_INPUT", 'Use support draft-reply <reference> --input with {"text":"Approved reply","kind":"reply|resolved|persists"}, or draft-read <reference> --input with {"through":25}. Save with --output and keep the same draft for recovery.', 2);
21
+ throw new CliError("SUPPORT_INPUT", 'Use support draft-reply <reference> --input with {"text":"Approved reply","kind":"reply|resolved|persists"}, or draft-read <reference> --input with {"through":25}. For priority, use draft-priority <reference> with {"expectedPriority":null,"priority":"high","reason":"Approved impact"}. Read support info and get first. Save with --output and keep the same draft for recovery.', 2);
22
+ }
23
+ function priorityDraft(raw, base) {
24
+ if (!priority(raw["priority"]) ||
25
+ !priority(raw["expectedPriority"]) ||
26
+ raw["attachments"] !== undefined ||
27
+ (raw["reason"] !== undefined &&
28
+ (typeof raw["reason"] !== "string" ||
29
+ !raw["reason"].trim() ||
30
+ raw["reason"].trim().length > 2000)))
31
+ return invalid();
32
+ return {
33
+ operation: "priority",
34
+ ...base,
35
+ priority: raw["priority"],
36
+ expectedPriority: raw["expectedPriority"],
37
+ ...(typeof raw["reason"] === "string" ? { reason: raw["reason"].trim() } : {}),
38
+ };
14
39
  }
15
40
  function conversationDraft(raw) {
16
41
  if (!object(raw) ||
17
- !["reply", "read"].includes(String(raw["operation"])) ||
42
+ !["reply", "read", "priority"].includes(String(raw["operation"])) ||
18
43
  typeof raw["requestId"] !== "string" ||
19
44
  !uuid.test(raw["requestId"]) ||
20
45
  typeof raw["reference"] !== "string" ||
21
- !uuid.test(raw["reference"]))
46
+ !reference(raw["reference"]))
22
47
  return invalid();
23
48
  const base = { requestId: raw["requestId"], reference: raw["reference"] };
49
+ if (raw["operation"] === "priority")
50
+ return priorityDraft(raw, base);
24
51
  if (raw["operation"] === "read") {
25
52
  if (!Number.isSafeInteger(raw["through"]) ||
26
53
  Number(raw["through"]) < 0 ||
@@ -57,21 +84,21 @@ export function conversationPreview(raw) {
57
84
  };
58
85
  }
59
86
  export async function offlineConversation({ values, positionals }) {
60
- const [, action, reference] = positionals;
87
+ const [, action, target] = positionals;
61
88
  const raw = await readJson(values.input);
62
89
  if (action === "preview" && object(raw) && raw["operation"] !== undefined)
63
90
  return conversationPreview(raw);
64
- if (!["draft-reply", "draft-read"].includes(action ?? ""))
91
+ if (!["draft-reply", "draft-read", "draft-priority"].includes(action ?? ""))
65
92
  return undefined;
66
- if (!reference || !uuid.test(reference) || !object(raw) || !values.output)
93
+ if (!target || !reference(target) || !object(raw) || !values.output)
67
94
  return invalid();
68
95
  if (values.attach?.length && action !== "draft-reply")
69
96
  return invalid();
70
97
  const value = conversationDraft({
71
98
  ...raw,
72
- reference,
99
+ reference: target,
73
100
  requestId: randomUUID(),
74
- operation: action === "draft-reply" ? "reply" : "read",
101
+ operation: action === "draft-reply" ? "reply" : action === "draft-priority" ? "priority" : "read",
75
102
  ...(values.attach?.length ? { attachments: await snapshotAttachments(values.attach) } : {}),
76
103
  });
77
104
  const saved = await saveOutput(values.output, () => Promise.resolve(value));
@@ -83,19 +110,26 @@ async function compatible(connection) {
83
110
  throw new CliError("SUPPORT_BACKEND_INCOMPATIBLE", "This backend does not support support conversations. Ask the team to deploy the matching backend/migration. No operation was sent.", 5);
84
111
  }
85
112
  export async function conversationCommand(connection, { values, positionals }) {
86
- const [, action, reference] = positionals;
87
- if (!["get", "history", "changes", "list", "reply", "read", "operation"].includes(action ?? ""))
113
+ const [, action, target] = positionals;
114
+ if (!["get", "history", "changes", "list", "reply", "read", "priority", "operation"].includes(action ?? ""))
88
115
  return { handled: false };
89
116
  if (values.attach?.length)
90
117
  return invalid();
91
118
  const raw = await readJson(values.input);
92
- if (action === "reply" || action === "read") {
119
+ if (action === "reply" || action === "read" || action === "priority") {
93
120
  const draft = conversationDraft(raw);
94
121
  if (draft.operation !== action)
95
122
  return invalid();
96
123
  if (!values.confirm && !values["dry-run"])
97
124
  throw new CliError("SUPPORT_CONFIRM_REQUIRED", "Show the saved operation, destination and attachment preview; obtain approval, then pass --confirm.", 2);
98
125
  await compatible(connection);
126
+ if (action === "priority") {
127
+ const info = await rpc(connection, "support", ["info"], {}, "GET");
128
+ if (!object(info) ||
129
+ !Array.isArray(info["features"]) ||
130
+ !info["features"].includes("requester-priority"))
131
+ throw new CliError("SUPPORT_BACKEND_INCOMPATIBLE", "Deploy the matching priority backend and migration first. No change was sent.", 5);
132
+ }
99
133
  const { operation: _operation, ...input } = draft;
100
134
  if (values["dry-run"]) {
101
135
  const textInput = "attachments" in input ? { ...input, attachments: undefined } : input;
@@ -132,7 +166,7 @@ export async function conversationCommand(connection, { values, positionals }) {
132
166
  ? { requestId: conversationDraft(raw).requestId }
133
167
  : action === "list"
134
168
  ? (raw ?? {})
135
- : { ...(object(raw) ? raw : {}), reference };
169
+ : { ...(object(raw) ? raw : {}), reference: target };
136
170
  return { handled: true, result: await rpc(connection, "support", [action], input, "GET") };
137
171
  }
138
172
  //# sourceMappingURL=support-conversation.js.map
package/dist/support.js CHANGED
@@ -7,11 +7,17 @@ import { snapshotAttachments, validateAttachments, attachmentPreview, } from "./
7
7
  import { conversationCommand, conversationPreview, offlineConversation, } from "./support-conversation.js";
8
8
  import { rpc } from "./transport.js";
9
9
  import { cliVersion } from "./version.js";
10
+ const priorities = new Set(["low", "normal", "high", "urgent"]);
10
11
  const categories = new Set(["bug", "compatibility", "feature", "question"]);
11
12
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
13
  function object(value) {
13
14
  return !!value && typeof value === "object" && !Array.isArray(value);
14
15
  }
16
+ function priority(value) {
17
+ if (value === null || (typeof value === "string" && priorities.has(value)))
18
+ return value;
19
+ throw new CliError("SUPPORT_INPUT", "Priority must be low, normal, high, urgent or null (undefined). Read support info; never infer urgency from text.", 2);
20
+ }
15
21
  function report(value) {
16
22
  if (!object(value) ||
17
23
  typeof value["category"] !== "string" ||
@@ -25,6 +31,7 @@ function report(value) {
25
31
  value["description"].trim().length > 12000)
26
32
  throw new CliError("SUPPORT_INPUT", 'Use --input with {"category":"bug|compatibility|feature|question","title":"Short summary","description":"Steps, expected and actual behavior; at least 20 characters"}. Remove passwords, tokens, cookies and private customer data.', 2);
27
33
  return {
34
+ ...(value["priority"] === undefined ? {} : { priority: priority(value["priority"]) }),
28
35
  category: value["category"],
29
36
  title: value["title"].trim(),
30
37
  description: value["description"].trim(),
@@ -57,7 +64,7 @@ function preview(value) {
57
64
  /** Draft and preview are offline and never need login or network access. */
58
65
  export async function offlineSupport({ values, positionals }) {
59
66
  const action = positionals[1];
60
- if (["draft-reply", "draft-read"].includes(action ?? "")) {
67
+ if (["draft-reply", "draft-read", "draft-priority"].includes(action ?? "")) {
61
68
  const result = await offlineConversation({ values, positionals });
62
69
  if (result !== undefined)
63
70
  return result;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agency-tbd/cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Operate InfluMode from your terminal or AI assistant using your own account and permissions",
5
5
  "homepage": "https://www.influmode.com",
6
6
  "repository": {
@@ -41,7 +41,6 @@
41
41
  "check-types": "tsc --noEmit",
42
42
  "dev": "tsx src/main.ts",
43
43
  "release:check": "pnpm check-types && pnpm test && node scripts/check-package.mjs",
44
- "release:publish": "pnpm release:check && pnpm publish --access public",
45
44
  "test": "pnpm build && vitest run --config vitest.config.ts"
46
45
  }
47
46
  }