@agency-tbd/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,7 +38,7 @@ To have an AI assistant handle setup, give it this prompt:
38
38
 
39
39
  > Install or update the public npm package @agency-tbd/cli to its latest release using pnpm or npm. Ensure Node.js meets the package's engines requirement and make the influmode command available in future terminals. Handle terminal commands yourself; repository access is not needed. Run influmode guide --json, then influmode auth login --url https://www.influmode.com and let me approve access in my browser with my own account. Never ask me to paste passwords, tokens or cookies into chat. Verify the connection with influmode capabilities, then stop without changing application data.
40
40
 
41
- Login opens a browser to approve the matching terminal code. `--no-browser` prints the approval URL instead. Login remembers the selected origin. Sessions last up to 24 hours; `auth logout` revokes the current CLI session. Tokens stay in origin-specific private files under `~/.config/influmode`, or `INFLUMODE_CONFIG_DIR`. An injected `INFLUMODE_TOKEN` takes precedence; never print it. `--url` overrides `INFLUMODE_URL` and the remembered origin. See [authentication](src/auth.ts) and [credential storage](src/config.ts).
41
+ Login opens a browser to approve the matching terminal code. `--no-browser` prints the approval URL instead. Login remembers the selected origin. New sessions default to 30 days. Choose “Until revoked” on the browser approval screen for no scheduled expiry. Manage and revoke terminal sessions in Settings → Account; `auth logout` revokes the current CLI session. Tokens stay in origin-specific private files under `~/.config/influmode`, or `INFLUMODE_CONFIG_DIR`. An injected `INFLUMODE_TOKEN` takes precedence; never print it. `--url` overrides `INFLUMODE_URL` and the remembered origin. See [authentication](src/auth.ts) and [credential storage](src/config.ts).
42
42
 
43
43
  ## Support without GitHub access
44
44
 
@@ -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 exposes only your own reports and their open/closed state; repository URLs, source code, other users' reports and staff comments stay private. `support list` shows your 20 most recent receipts; use `support status <reference>` for current status.
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.
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
 
@@ -173,7 +173,18 @@ For repository development, install dependencies with `pnpm install --frozen-loc
173
173
 
174
174
  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
175
 
176
- Publish a reviewed release from a clean, merged checkout with `pnpm --filter @agency-tbd/cli release:publish`, using an npm account authorized to publish under the `@agency-tbd` scope. The first publication requires that scope to exist and the account to complete npm's authentication/2FA requirements. 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.
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.
177
+
178
+ One-time setup by a package maintainer:
179
+
180
+ 1. Restore GitHub Actions availability if account billing or spending limits prevent hosted jobs from starting. npm trusted publishing does not support self-hosted runners.
181
+ 2. Create a GitHub environment named `npm-publish` with a deployment branch policy allowing only `main` (no tag rule). That policy also prevents a modified release workflow on another branch from acquiring the trusted publishing identity.
182
+ 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
+ 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
+
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/).
186
+
187
+ 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.
177
188
 
178
189
  This evergreen reference owns `apps/cli/src/**` command behavior. Run `pnpm --filter @agency-tbd/cli test`, `check-types`, and `catalog:check` after changes. The subprocess integration tests exercise discovery, help without side effects, account context, forbidden-operation recovery, writes, pagination, polling and partial batch failure against a real local HTTP transport.
179
190
 
@@ -194,3 +205,41 @@ influmode support status --input @support-draft.json
194
205
  Up to five PNG, JPEG or WebP files are accepted: 4 MiB per file, 10 MiB total. Draft and preview are offline. The private draft contains a snapshot of each image, so moving or editing the source screenshot cannot change the approved submission. Preview shows the filename, detected type, byte count and SHA-256 hash without printing image contents. Review the selected images for private information before sharing; image text is not automatically redacted. Only submit uploads the selected screenshots.
195
206
 
196
207
  The private GitHub issue links to authenticated InfluMode file access. Investigators need an authorized session in the reporting tenant; GitHub access alone is insufficient. Storage objects are private, and signed storage URLs are never placed in the issue. All screenshots must be stored before the issue is sent. Keep the same draft after a timeout and check status before retrying; an uncertain submission must never be recreated with a new request ID.
208
+
209
+ ## Follow and reply to the same support request
210
+
211
+ CLI **0.4.0** requires the matching backend and additive conversation migration. `support info` must return `conversationVersion:1`; incompatible servers fail clearly before a conversation write. Publishing the CLI and deploying the backend are separate release steps.
212
+
213
+ ```sh
214
+ influmode support get <reference>
215
+ influmode support history <reference> --input '{"limit":25}'
216
+ influmode support list --input '{"category":"bug","state":"open","search":"Windows","limit":25}'
217
+ ```
218
+
219
+ `list` accepts `reference`, `search` (title/description), `category`, `state`, `limit` and `cursor`; results are sorted by recent activity. Follow `nextCursor` until null. List uses the stored public state; `get`, `history` and `changes` refresh a request. `history` returns chronological pages at a fixed revision: pass its `nextCursor` as `cursor`. State events use the time the change was observed. New reads never silently acknowledge updates. Legacy descriptions are recovered only from the strictly delimited original report section; if unavailable, they remain explicitly null.
220
+
221
+ To answer the team or supply new evidence, create `reply.json` containing `{"text":"Your exact response","kind":"reply"}`. Use `kind:"resolved"` to confirm that you verified the resolution, or `kind:"persists"` to request review/reopening. Both remain in the same conversation. The requester does not receive administrative reopening powers: the receipt explicitly says `reopening:"not_applied"`. Only the team can change the issue state.
222
+
223
+ ```sh
224
+ influmode support draft-reply <reference> --input @reply.json --attach erro.png --output reply-draft.json
225
+ influmode support preview --input @reply-draft.json
226
+ # Show the exact text, reference and screenshot preview; obtain approval.
227
+ influmode support reply --input @reply-draft.json --confirm
228
+ influmode support operation --input @reply-draft.json
229
+ ```
230
+
231
+ Reply drafts are offline private files. Screenshot snapshots, preview, limits and secret/file protections match the initial report. Submission preserves all earlier text and attachments. `--dry-run` validates only text metadata; it never uploads screenshots. The receipt distinguishes locally `saved:true` from delivery `sent`, `pending`, `failed` or `local`. `pending` may follow a successful provider write. Keep the exact original draft/requestId, recover with `operation`, and replay only that same operation; it never creates a second comment. Changed content or target under the same key is a conflict. A definite failure needs administrator reconciliation before any replacement draft. Read acknowledgements use the same recovery endpoint.
232
+
233
+ `get` shows communicated progress, blocking reason, outcome, resolution, next step and release version. Unknown fields remain null. Closing a request does not imply `fix_delivered`; duplicates, declined requests and answered questions have distinct outcomes when the team publishes them. No delivery forecast is inferred.
234
+
235
+ ```sh
236
+ influmode support changes <reference> --input '{"after":0,"limit":25}'
237
+ # Persist nextCursor with this reference/account; pass it as after on the next query.
238
+ # Follow hasMore until false. since may additionally filter by ISO timestamp.
239
+ influmode support draft-read <reference> --input '{"through":25}' --output read-draft.json
240
+ influmode support preview --input @read-draft.json
241
+ influmode support read --input @read-draft.json --confirm
242
+ influmode support operation --input @read-draft.json
243
+ ```
244
+
245
+ 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.
package/dist/agent.js CHANGED
@@ -35,9 +35,17 @@ export const agentGuide = {
35
35
  approval: "Show the exact saved report, diagnostics and destination to the user. Remove secrets and private customer data. Obtain approval before submitting.",
36
36
  send: "influmode support submit --input @support-draft.json --confirm",
37
37
  recover: "influmode support status --input @support-draft.json",
38
- list: "influmode support list",
38
+ list: "influmode support list --input with cursor, reference, search, category, state and limit; exhaust nextCursor",
39
+ details: "influmode support get <reference>",
40
+ history: "influmode support history <reference>; paginate cursor chronologically",
41
+ 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
+ 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
+ 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.",
44
+ 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
+ operationRecovery: "support operation --input @original-reply-or-read-draft.json; reuse exact requestId/payload only",
46
+ notification: "Incremental queries are active reads. Background alerts need separately configured and authorized scheduling, channel and user preferences. Do not promise background monitoring.",
39
47
  delivery: "Check receipt.submitted and receipt.state. Pending is uncertain delivery; reuse the saved draft to reconcile. Never generate a new requestId after an uncertain send.",
40
- privacy: "Only the approved report, CLI/Node/OS/architecture and authenticated account/tenant IDs are sent. No automatic logs, environment, files or credentials. Status exposes only your own report and open/closed state, never private staff comments or repository access.",
48
+ privacy: "Only the approved report, CLI/Node/OS/architecture and authenticated account/tenant IDs are sent. No automatic logs, environment, files or credentials. Conversations expose only your reports, own replies and deliberately published staff replies. Internal notes, repository links and code stay private.",
41
49
  },
42
50
  recordUpdates: {
43
51
  resources: ["leads", "deals", "campaigns"],
@@ -94,7 +102,7 @@ export const agentGuide = {
94
102
  export: "--output new-file.json (never overwrites)",
95
103
  },
96
104
  recovery: {
97
- authentication: "Run auth login --url <origin>; approval lasts up to 24 hours. Never print tokens.",
105
+ authentication: "Run auth login --url <origin>; sessions default to 30 days; choose Until revoked during browser approval. Never print tokens.",
98
106
  forbidden: "Stop. Ask an authorized owner; do not switch tenants, accounts or transport to bypass denial.",
99
107
  invalidInput: "Inspect error.details and live operation help; correct input before retrying.",
100
108
  ambiguousWrite: "Inspect saved state or ask an owner to reconcile; do not repeat the write.",
package/dist/auth.js CHANGED
@@ -3,10 +3,14 @@ import { setTimeout as delay } from "node:timers/promises";
3
3
  import { clearCredentials, saveCredentials, selectOrigin } from "./config.js";
4
4
  import { CliError } from "./errors.js";
5
5
  import { http } from "./transport.js";
6
+ import { cliVersion } from "./version.js";
6
7
  async function authRequest(origin, path, body) {
7
8
  const response = await fetch(`${origin}/api/auth/${path}`, {
8
9
  method: "POST",
9
- headers: { "content-type": "application/json" },
10
+ headers: {
11
+ "content-type": "application/json",
12
+ "user-agent": `Influmode CLI/${cliVersion} (${process.platform}; ${process.arch})`,
13
+ },
10
14
  body: JSON.stringify(body),
11
15
  redirect: "error",
12
16
  signal: AbortSignal.timeout(30_000),
@@ -60,11 +64,17 @@ export async function login(origin, noBrowser) {
60
64
  });
61
65
  if (result["access_token"]) {
62
66
  const token = textField(result, "access_token");
63
- const expiresAt = Date.now() +
64
- (typeof result["expires_in"] === "number" ? result["expires_in"] : 86_400) * 1000;
67
+ const expiresAt = result["scope"] === "influmode:until-revoked"
68
+ ? null
69
+ : Date.now() +
70
+ (typeof result["expires_in"] === "number" ? result["expires_in"] : 86_400) * 1000;
65
71
  await saveCredentials(origin, { token, expiresAt });
66
72
  await selectOrigin(origin);
67
- return { authenticated: true, origin, expiresAt: new Date(expiresAt).toISOString() };
73
+ return {
74
+ authenticated: true,
75
+ origin,
76
+ expiresAt: expiresAt === null ? null : new Date(expiresAt).toISOString(),
77
+ };
68
78
  }
69
79
  if (result["error"] === "slow_down")
70
80
  interval += 5;
package/dist/config.js CHANGED
@@ -53,9 +53,9 @@ export async function loadToken(origin) {
53
53
  !("token" in data) ||
54
54
  typeof data.token !== "string" ||
55
55
  !("expiresAt" in data) ||
56
- typeof data.expiresAt !== "number")
56
+ (data.expiresAt !== null && typeof data.expiresAt !== "number"))
57
57
  throw new CliError("INVALID_CREDENTIALS", "Invalid credential file; run auth login", 3);
58
- if (Date.now() >= data.expiresAt)
58
+ if (data.expiresAt !== null && Date.now() >= data.expiresAt)
59
59
  throw new CliError("SESSION_EXPIRED", "Session expired; run auth login", 3);
60
60
  return data.token;
61
61
  }
package/dist/help.js CHANGED
@@ -5,9 +5,25 @@ influmode support info
5
5
  influmode support submit --input @support-draft.json --confirm [--dry-run]
6
6
  influmode support status <reference>
7
7
  influmode support status --input @support-draft.json
8
- influmode support list
8
+ influmode support list --input '{"limit":25,"category":"bug","state":"open"}'
9
+ influmode support get <reference>
10
+ influmode support history <reference> --input '{"limit":25}'
11
+ influmode support changes <reference> --input '{"after":0,"limit":25}'
12
+ influmode support draft-reply <reference> --input @reply.json --output reply-draft.json [--attach screenshot.png]
13
+ influmode support preview --input @reply-draft.json
14
+ influmode support reply --input @reply-draft.json --confirm [--dry-run]
15
+ influmode support draft-read <reference> --input '{"through":25}' --output read-draft.json
16
+ influmode support read --input @read-draft.json --confirm
17
+ influmode support operation --input @reply-draft.json
18
+ Reply JSON: {"text":"Your exact reply","kind":"reply|resolved|persists"}.
19
+ List filters: cursor, reference, search, category, state, limit. Follow nextCursor until null.
20
+ 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
+ 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
+ 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
+ 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
+ Conversation commands require backend conversationVersion:1 (matching migration/deployment). No repository access is needed.
9
25
  Report JSON: {"category":"bug|compatibility|feature|question","title":"Short summary","description":"Steps, expected and actual behavior; at least 20 characters"}.
10
- 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; no private repository links, code or staff comments are exposed. 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.`,
26
+ 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.`,
11
27
  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>.",
12
28
  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.",
13
29
  operations: "influmode operations <resource> [--search text]\nRead live operation names, descriptions and command syntax without running their handlers. Requires login. Follow with help <resource> <operation>.",
package/dist/main.js CHANGED
@@ -48,7 +48,8 @@ async function offlineCommand(parsed) {
48
48
  httpRoutes: httpRoutes.filter((item) => !values.search || item.includes(values.search)),
49
49
  },
50
50
  };
51
- if (command === "support" && ["draft", "preview"].includes(subcommand ?? ""))
51
+ if (command === "support" &&
52
+ ["draft", "draft-reply", "draft-read", "preview"].includes(subcommand ?? ""))
52
53
  return { handled: true, result: await offlineSupport(parsed) };
53
54
  return { handled: false };
54
55
  }
@@ -0,0 +1,138 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ORPCError } from "@orpc/client";
3
+ import { CliError } from "./errors.js";
4
+ import { readJson } from "./input.js";
5
+ import { saveOutput } from "./output.js";
6
+ import { snapshotAttachments, validateAttachments, attachmentPreview, } from "./support-attachments.js";
7
+ import { rpc } from "./transport.js";
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 object(value) {
10
+ return !!value && typeof value === "object" && !Array.isArray(value);
11
+ }
12
+ 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);
14
+ }
15
+ function conversationDraft(raw) {
16
+ if (!object(raw) ||
17
+ !["reply", "read"].includes(String(raw["operation"])) ||
18
+ typeof raw["requestId"] !== "string" ||
19
+ !uuid.test(raw["requestId"]) ||
20
+ typeof raw["reference"] !== "string" ||
21
+ !uuid.test(raw["reference"]))
22
+ return invalid();
23
+ const base = { requestId: raw["requestId"], reference: raw["reference"] };
24
+ if (raw["operation"] === "read") {
25
+ if (!Number.isSafeInteger(raw["through"]) ||
26
+ Number(raw["through"]) < 0 ||
27
+ Number(raw["through"]) > 2147483647 ||
28
+ raw["attachments"] !== undefined)
29
+ return invalid();
30
+ return { operation: "read", ...base, through: Number(raw["through"]) };
31
+ }
32
+ const kind = raw["kind"] ?? "reply";
33
+ if (typeof raw["text"] !== "string" ||
34
+ !raw["text"].trim() ||
35
+ raw["text"].trim().length > 12000 ||
36
+ typeof kind !== "string" ||
37
+ !["reply", "resolved", "persists"].includes(kind))
38
+ return invalid();
39
+ return {
40
+ operation: "reply",
41
+ ...base,
42
+ text: raw["text"].trim(),
43
+ kind,
44
+ ...(raw["attachments"] === undefined
45
+ ? {}
46
+ : { attachments: validateAttachments(raw["attachments"]) }),
47
+ };
48
+ }
49
+ export function conversationPreview(raw) {
50
+ const draft = conversationDraft(raw);
51
+ return {
52
+ destination: `InfluMode support, existing request ${draft.reference}`,
53
+ operation: attachmentPreview(draft),
54
+ sent: false,
55
+ privacy: "Only this approved operation and explicitly selected screenshots are sent. No logs, credentials, customer records or other files are automatically collected.",
56
+ next: `Show this exact destination and operation to the user. After approval run support ${draft.operation} --input @saved-draft.json --confirm. Keep this file and recover with support operation --input @saved-draft.json.`,
57
+ };
58
+ }
59
+ export async function offlineConversation({ values, positionals }) {
60
+ const [, action, reference] = positionals;
61
+ const raw = await readJson(values.input);
62
+ if (action === "preview" && object(raw) && raw["operation"] !== undefined)
63
+ return conversationPreview(raw);
64
+ if (!["draft-reply", "draft-read"].includes(action ?? ""))
65
+ return undefined;
66
+ if (!reference || !uuid.test(reference) || !object(raw) || !values.output)
67
+ return invalid();
68
+ if (values.attach?.length && action !== "draft-reply")
69
+ return invalid();
70
+ const value = conversationDraft({
71
+ ...raw,
72
+ reference,
73
+ requestId: randomUUID(),
74
+ operation: action === "draft-reply" ? "reply" : "read",
75
+ ...(values.attach?.length ? { attachments: await snapshotAttachments(values.attach) } : {}),
76
+ });
77
+ const saved = await saveOutput(values.output, () => Promise.resolve(value));
78
+ return { ...saved, ...conversationPreview(value) };
79
+ }
80
+ async function compatible(connection) {
81
+ const info = await rpc(connection, "support", ["info"], {}, "GET");
82
+ if (!object(info) || info["conversationVersion"] !== 1)
83
+ 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
+ }
85
+ export async function conversationCommand(connection, { values, positionals }) {
86
+ const [, action, reference] = positionals;
87
+ if (!["get", "history", "changes", "list", "reply", "read", "operation"].includes(action ?? ""))
88
+ return { handled: false };
89
+ if (values.attach?.length)
90
+ return invalid();
91
+ const raw = await readJson(values.input);
92
+ if (action === "reply" || action === "read") {
93
+ const draft = conversationDraft(raw);
94
+ if (draft.operation !== action)
95
+ return invalid();
96
+ if (!values.confirm && !values["dry-run"])
97
+ throw new CliError("SUPPORT_CONFIRM_REQUIRED", "Show the saved operation, destination and attachment preview; obtain approval, then pass --confirm.", 2);
98
+ await compatible(connection);
99
+ const { operation: _operation, ...input } = draft;
100
+ if (values["dry-run"]) {
101
+ const textInput = "attachments" in input ? { ...input, attachments: undefined } : input;
102
+ return {
103
+ handled: true,
104
+ result: {
105
+ ...conversationPreview(draft),
106
+ validation: await rpc(connection, "support", ["__cli", "validate"], {
107
+ path: [action],
108
+ input: textInput,
109
+ }),
110
+ },
111
+ };
112
+ }
113
+ try {
114
+ const receipt = await rpc(connection, "support", [action], input);
115
+ return {
116
+ handled: true,
117
+ result: {
118
+ ok: object(receipt) && ["sent", "local"].includes(String(receipt["delivery"])),
119
+ receipt,
120
+ },
121
+ };
122
+ }
123
+ catch (error) {
124
+ if (error instanceof ORPCError &&
125
+ ["UNAUTHORIZED", "FORBIDDEN", "BAD_REQUEST", "CONFLICT", "NOT_FOUND"].includes(String(error.code)))
126
+ throw error;
127
+ throw new CliError("SUPPORT_OPERATION_UNCONFIRMED", "Operation outcome is uncertain. Retain the original draft and run support operation --input @saved-draft.json. Never create a new ID to retry.", 1, { requestId: draft.requestId, reference: draft.reference });
128
+ }
129
+ }
130
+ await compatible(connection);
131
+ const input = action === "operation"
132
+ ? { requestId: conversationDraft(raw).requestId }
133
+ : action === "list"
134
+ ? (raw ?? {})
135
+ : { ...(object(raw) ? raw : {}), reference };
136
+ return { handled: true, result: await rpc(connection, "support", [action], input, "GET") };
137
+ }
138
+ //# sourceMappingURL=support-conversation.js.map
package/dist/support.js CHANGED
@@ -4,6 +4,7 @@ import { CliError } from "./errors.js";
4
4
  import { readJson } from "./input.js";
5
5
  import { saveOutput } from "./output.js";
6
6
  import { snapshotAttachments, validateAttachments, attachmentPreview, } from "./support-attachments.js";
7
+ import { conversationCommand, conversationPreview, offlineConversation, } from "./support-conversation.js";
7
8
  import { rpc } from "./transport.js";
8
9
  import { cliVersion } from "./version.js";
9
10
  const categories = new Set(["bug", "compatibility", "feature", "question"]);
@@ -56,10 +57,19 @@ function preview(value) {
56
57
  /** Draft and preview are offline and never need login or network access. */
57
58
  export async function offlineSupport({ values, positionals }) {
58
59
  const action = positionals[1];
60
+ if (["draft-reply", "draft-read"].includes(action ?? "")) {
61
+ const result = await offlineConversation({ values, positionals });
62
+ if (result !== undefined)
63
+ return result;
64
+ }
59
65
  if (values.attach?.length && action !== "draft")
60
66
  throw new CliError("SUPPORT_ATTACHMENTS", "Use --attach only with support draft; submit the saved draft after reviewing it.", 2);
61
- if (action === "preview")
62
- return preview(draft(await readJson(values.input)));
67
+ if (action === "preview") {
68
+ const raw = await readJson(values.input);
69
+ return object(raw) && raw["operation"] !== undefined
70
+ ? conversationPreview(raw)
71
+ : preview(draft(raw));
72
+ }
63
73
  if (!values.output)
64
74
  throw new CliError("SUPPORT_OUTPUT_REQUIRED", "Save a reusable draft: influmode support draft --input @report.json --output support-draft.json", 2);
65
75
  const input = await readJson(values.input);
@@ -82,13 +92,14 @@ export async function offlineSupport({ values, positionals }) {
82
92
  };
83
93
  }
84
94
  export async function supportCommand(connection, { values, positionals }) {
95
+ const conversation = await conversationCommand(connection, { values, positionals });
96
+ if (conversation.handled)
97
+ return conversation.result;
85
98
  const [, action, reference] = positionals;
86
99
  if (values.attach?.length)
87
100
  throw new CliError("SUPPORT_ATTACHMENTS", "Use --attach with support draft first; attachments cannot be added during submission.", 2);
88
101
  if (action === "info")
89
102
  return rpc(connection, "support", ["info"], {}, "GET");
90
- if (action === "list")
91
- return rpc(connection, "support", ["list"], {}, "GET");
92
103
  if (action === "status") {
93
104
  const input = reference
94
105
  ? { reference }
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "@agency-tbd/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
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
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/eternalwaitt/agency-tbd.git",
9
+ "directory": "apps/cli"
10
+ },
6
11
  "bin": {
7
12
  "influmode": "dist/main.js"
8
13
  },