@artifactshare/cli 0.12.0 → 0.13.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/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ For user-facing announcements, see https://artifactshare.com/updates?product=cli
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 0.13.1 - 2026-08-30
9
+
10
+ - Restore direct `npx @artifactshare/cli ...` invocation after adding the
11
+ Cursor preview executable by exposing `cli` as an alias of the main
12
+ `artifactshare` entrypoint.
13
+
14
+ ## 0.13.0 - 2026-08-30
15
+
16
+ - Continue local preview work in a managed Cursor ACP conversation, restoring
17
+ its session after a bridge restart and preserving batches while it is busy
18
+ or unavailable. The attended launcher asks before granting Cursor tool
19
+ permissions. Interactive Agent CLI foreground waits and ordinary IDE manual
20
+ pickup remain separate capabilities.
21
+
22
+ - Resume Claude Code preview work with a background `preview next --wait`
23
+ task, or retain the batch for manual pickup when background tasks are
24
+ unavailable.
25
+
26
+ - Wake an idle Codex preview session with a fixed `codex queue` batch-ready
27
+ notice while keeping annotation content in `preview next`; invalid targets
28
+ and ended sessions retain the batch and show manual resume guidance.
29
+
30
+ - Add a shared preview agent-notification contract: one trusted local registration per session, fixed metadata-only batch-ready events, explicit waiting/queued/processing/completed/failed/manual-required projections, atomic batch membership, single active long-poll delivery, and durable manual pickup when notification is unavailable or uncertain.
31
+
8
32
  ## 0.12.0 - 2026-08-29
9
33
 
10
34
  - Add `preview <file>` for local review: serve a `.md` or `.html` file with the product viewer look on `127.0.0.1` without authentication, print one ready JSON line, and let the user annotate elements and text selections in the browser as explicit batches. Agents collect batches with `preview next [--wait <sec>]` (non-claiming long poll; `timed_out` / `session_ended` are normal results), report generation-idempotent outcomes via `preview done --stdin` (`accepted` / `stale` / `already_reported` / `unknown_thread`), reply with `preview reply --thread --body`, and end with `preview stop` (with `--force` to clear a record once its process is gone; it refuses while the recorded process is alive) (annotations stay on disk). Previewing uploads nothing; sharing a snapshot happens only from the page's share dialog.
package/README.md CHANGED
@@ -11,39 +11,39 @@ Artifact Share hosts AI-built reports, documents, and static sites so you can sh
11
11
  Requires Node.js 22 or later.
12
12
 
13
13
  ```sh
14
- npx --yes @artifactshare/cli share ./report.html
14
+ npm exec --yes --package=@artifactshare/cli -- artifactshare share ./report.html
15
15
  ```
16
16
 
17
- `--yes` lets agents and CI fetch the package without stopping for an npx install prompt.
17
+ `--yes` lets agents and CI fetch the package without stopping for an npm install prompt.
18
18
 
19
19
  On the first run in an interactive terminal, the CLI prints a sign-in link — open it in your browser, and the share completes and prints the share URL. Folders work too:
20
20
 
21
21
  ```sh
22
- npx --yes @artifactshare/cli open <artifact-id-or-url> --json
23
- npx --yes @artifactshare/cli share ./dist --project 'Weekly Reports'
24
- npx --yes @artifactshare/cli projects create 'Client reports' --json
25
- npx --yes @artifactshare/cli projects edit <id> --add-email viewer@example.com --json
26
- npx --yes @artifactshare/cli edit <artifact-id-or-url> --project-id <id> --json
27
- npx --yes @artifactshare/cli edit <artifact-id-or-url> --visibility private --grant-email viewer@example.com --json
28
- npx --yes @artifactshare/cli share ./report.html --visibility link --link-expires-at '2026-08-01T00:00:00Z' --json
29
- npx --yes @artifactshare/cli edit <artifact-id-or-url> --visibility link --no-link-expiry --json
30
- npx --yes @artifactshare/cli update <artifact-id-or-url> ./dist
31
- npx --yes @artifactshare/cli append <artifact-id-or-url> ./new-section.md
32
- npx --yes @artifactshare/cli delete <artifact-id-or-url> --json
33
- npx --yes @artifactshare/cli logout --profile default --json
34
- npx --yes @artifactshare/cli config set home_audience private --scope user --json
35
- npx --yes @artifactshare/cli config get home_audience --scope effective --json
22
+ npm exec --yes --package=@artifactshare/cli -- artifactshare open <artifact-id-or-url> --json
23
+ npm exec --yes --package=@artifactshare/cli -- artifactshare share ./dist --project 'Weekly Reports'
24
+ npm exec --yes --package=@artifactshare/cli -- artifactshare projects create 'Client reports' --json
25
+ npm exec --yes --package=@artifactshare/cli -- artifactshare projects edit <id> --add-email viewer@example.com --json
26
+ npm exec --yes --package=@artifactshare/cli -- artifactshare edit <artifact-id-or-url> --project-id <id> --json
27
+ npm exec --yes --package=@artifactshare/cli -- artifactshare edit <artifact-id-or-url> --visibility private --grant-email viewer@example.com --json
28
+ npm exec --yes --package=@artifactshare/cli -- artifactshare share ./report.html --visibility link --link-expires-at '2026-08-01T00:00:00Z' --json
29
+ npm exec --yes --package=@artifactshare/cli -- artifactshare edit <artifact-id-or-url> --visibility link --no-link-expiry --json
30
+ npm exec --yes --package=@artifactshare/cli -- artifactshare update <artifact-id-or-url> ./dist
31
+ npm exec --yes --package=@artifactshare/cli -- artifactshare append <artifact-id-or-url> ./new-section.md
32
+ npm exec --yes --package=@artifactshare/cli -- artifactshare delete <artifact-id-or-url> --json
33
+ npm exec --yes --package=@artifactshare/cli -- artifactshare logout --profile default --json
34
+ npm exec --yes --package=@artifactshare/cli -- artifactshare config set home_audience private --scope user --json
35
+ npm exec --yes --package=@artifactshare/cli -- artifactshare config get home_audience --scope effective --json
36
36
  ```
37
37
 
38
38
  To keep an existing share URL, update it with
39
- `npx --yes @artifactshare/cli update <artifact-id-or-url> <path>` instead of
39
+ `npm exec --yes --package=@artifactshare/cli -- artifactshare update <artifact-id-or-url> <path>` instead of
40
40
  sharing again. For CI, scheduled reports, or other repeat jobs, use
41
41
  `share <path> --key <key>`: the first run creates the shared file, and later
42
42
  runs add versions to the same file.
43
43
 
44
44
  ## Authentication
45
45
 
46
- - **Interactive person**: run `npx --yes @artifactshare/cli login`.
46
+ - **Interactive person**: run `npm exec --yes --package=@artifactshare/cli -- artifactshare login`.
47
47
  - **Attended local agent**: use `login --preset agent` on the user's own machine to authorize one project. Add `--project <exact-name-or-id>` to make the browser confirm that fixed project; omit it to use the project picker. Device-login profiles renew expired CLI sessions automatically during normal use, and `login` / `whoami` distinguish the session expiry from the rotating refresh-credential expiry.
48
48
  - **CI / non-interactive**: issue a token at `https://artifactshare.com/settings/tokens`, then inject `ARTIFACTSHARE_TOKEN` (or pass `--token`). Without a token, non-interactive runs fail with `error.code: "auth_required"` instead of hanging.
49
49
  - **Shared agent platform**: use a workspace-managed bot credential in a trusted host service outside the model sandbox. Do not store a user's device-login profile or expose the bot credential to model shell commands.
@@ -102,19 +102,55 @@ an element or a text range, write a note, and send your notes to the agent as
102
102
  one explicit batch. Saving the file reloads the page.
103
103
 
104
104
  ```sh
105
- npx --yes @artifactshare/cli preview ./report.html
106
- npx --yes @artifactshare/cli preview next ./report.html --wait 90
107
- npx --yes @artifactshare/cli preview stop ./report.html
105
+ npm exec --yes --package=@artifactshare/cli -- artifactshare preview ./report.html
106
+ npm exec --yes --package=@artifactshare/cli -- artifactshare preview next ./report.html --wait 90
107
+ npm exec --yes --package=@artifactshare/cli -- artifactshare preview stop ./report.html
108
108
  ```
109
109
 
110
110
  The first command prints one ready JSON line (`url`, `session`,
111
- `share_origin`, `reused`) and keeps serving; pass `--no-open` to skip opening
111
+ `share_origin`, `reused`, and a sanitized `agent` notification projection) and keeps serving; pass `--no-open` to skip opening
112
112
  the browser. The agent collects submitted batches with `preview next`
113
113
  (long-polling with `--wait <sec>`; `timed_out` and `session_ended` are normal
114
114
  results, while `preview_session_not_found` means no session is live), fixes
115
115
  the file, and reports outcomes by piping
116
116
  `{"items":[{"thread":...,"generation":...,"outcome":"fixed"|"skipped","note":...}]}`
117
117
  into `preview done --stdin`. Reporting is idempotent per thread generation.
118
+ Only one long-poll may reserve a preview session at a time. The CLI returns
119
+ `preview_wait_conflict` to a competing poll; use the existing wait or
120
+ retry after it returns. Successful `next` and `done` results include the same
121
+ sanitized `agent` projection as the ready result. Submitted comments
122
+ stay in the local mode-`0600` store when notification fails or no waiter is
123
+ connected, and a later `preview next` retrieves the same batch. Provider
124
+ notifications carry only the event kind, preview session id, and batch id;
125
+ comment text and anchors are read through `preview next` instead.
126
+ When preview starts inside a current Codex session with a valid trusted thread
127
+ UUID, the ready and command results report `provider: codex`,
128
+ `transport: codex_queue`, and `capability: push`. Submitting a batch queues the
129
+ fixed notice to that thread. Queue acceptance remains `queued` until the agent
130
+ actually calls `preview next`; if the session has ended, reopen it with
131
+ `codex resume` and the saved batch remains available.
132
+
133
+ Inside Claude Code, the default transport is one background
134
+ `preview next --wait 3600` task. The bundled skill checks that Bash exposes
135
+ `run_in_background` and that starting the wait returns a task ID. It re-arms
136
+ after processing a batch and reporting `preview done`, but does not re-arm a
137
+ timed-out wait. Setting `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` to `1` or
138
+ `true` selects manual pickup.
139
+
140
+ For an Artifact Share-managed Cursor conversation, start the preview with
141
+ `npm exec --yes --package=@artifactshare/cli -- artifactshare-preview-cursor <file>`.
142
+ The launcher uses the existing Cursor CLI login, creates an ACP session on the
143
+ first run, and loads that same session for the workspace after a bridge
144
+ restart. Run one managed launcher per workspace. It sends only a fixed
145
+ batch-ready prompt to an idle managed session;
146
+ the agent reads comments with `preview next`. Keep the launcher attended:
147
+ Cursor tool permissions are rejected unless you explicitly approve them in
148
+ its terminal. A busy or unavailable session keeps the batch saved. In a normal
149
+ Cursor Agent CLI turn, explicitly set `ARTIFACTSHARE_CURSOR_FOREGROUND_WAIT=1`
150
+ when starting preview and keep one `preview next --wait 90` command in the
151
+ foreground. Ordinary Cursor IDE chats are manual pickup and are never reported
152
+ as automatically resumable.
153
+
118
154
  `preview reply --thread <id> --body <text>` adds a reply without changing
119
155
  thread state, and `preview stop` ends the session while keeping annotations
120
156
  saved on disk. Sharing a snapshot happens only from the page's own share
@@ -125,10 +161,10 @@ dialog, and local annotations are not included in what is shared.
125
161
  Posting to a project delivers to the audience defined by that project. With no destination, `share` posts to home. Choose the home audience by purpose:
126
162
 
127
163
  ```sh
128
- npx --yes @artifactshare/cli config set home_audience private --scope user --json
129
- npx --yes @artifactshare/cli config set home_audience workspace --scope repository --json
130
- npx --yes @artifactshare/cli share ./report.html --visibility private --json
131
- npx --yes @artifactshare/cli config get home_audience --scope effective --json
164
+ npm exec --yes --package=@artifactshare/cli -- artifactshare config set home_audience private --scope user --json
165
+ npm exec --yes --package=@artifactshare/cli -- artifactshare config set home_audience workspace --scope repository --json
166
+ npm exec --yes --package=@artifactshare/cli -- artifactshare share ./report.html --visibility private --json
167
+ npm exec --yes --package=@artifactshare/cli -- artifactshare config get home_audience --scope effective --json
132
168
  ```
133
169
 
134
170
  Use `--scope repository` only for a policy agreed by all repository participants, and pass `--visibility private|workspace|link` for a one-time home override. For link sharing, pass exactly one of `--link-expires-at <RFC3339 UTC>` or `--no-link-expiry`; omit both to use the workspace default. For project creation, pass `projects create <name> --visibility private|workspace`; persistent project defaults are documented in `projects create --help`. Pass `--no-slack-notify` to suppress the project Slack notification for one post.
@@ -142,7 +178,7 @@ For the complete settings reference, `home_audience` is the canonical home key.
142
178
  For first-time setup in a project, start here:
143
179
 
144
180
  ```sh
145
- npx --yes @artifactshare/cli init --json
181
+ npm exec --yes --package=@artifactshare/cli -- artifactshare init --json
146
182
  ```
147
183
 
148
184
  `init` detects Claude Code, Codex, or Cursor in the working directory, installs or updates the bundled skill in user scope, and reports the next steps (sign in, then share). With no agent detected, it installs user-scope Codex, Claude Code, and Cursor skills. Cursor project scope is not auto-installed; use `skills install --tool cursor --scope project`. Existing project-scope skills are not modified. Add `--dry-run` to preview without writing.
@@ -150,7 +186,7 @@ npx --yes @artifactshare/cli init --json
150
186
  When an agent receives an Artifact Share URL instead, start with `open`:
151
187
 
152
188
  ```sh
153
- npx --yes @artifactshare/cli open <artifact-id-or-url> --json
189
+ npm exec --yes --package=@artifactshare/cli -- artifactshare open <artifact-id-or-url> --json
154
190
  ```
155
191
 
156
192
  This installs or updates the local skill first, then reads single-file artifacts. Static sites and multi-file artifacts return a `download` next command.
@@ -162,7 +198,7 @@ Comment deletion is permanent. Use `comments delete <target> --thread-id <id> --
162
198
  All commands emit stable JSON when run non-interactively, piped, or with `--json`: success on stdout as `{ "schema_version": 2, "ok": true, "command": ..., "data": ... }`, failures on stderr as `{ "schema_version": 2, "ok": false, "command": ..., "error": ... }` with exit code 1. The `error` object carries a machine-readable `code`, a `hint`, and a structured `recovery` field (for example `{ "kind": "run_command", ... }`), so agents and scripts can branch and recover without parsing prose.
163
199
 
164
200
  ```sh
165
- npx --yes @artifactshare/cli share ./dist --json
201
+ npm exec --yes --package=@artifactshare/cli -- artifactshare share ./dist --json
166
202
  ```
167
203
 
168
204
  Quote paths and free-form text before passing them through a shell. Artifact Share route files and user files can contain `$`, spaces, or glob characters, so prefer single quotes such as `'apps/web/app/routes/a.$id/index.tsx'` and `--body 'Looks good'`.
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,413 @@
1
+ #!/usr/bin/env node
2
+ import { d as previewsDir, p as processAlive, t as CURSOR_ACP_ACK_TIMEOUT_MS } from "./cursor-notification-BBGHJ5v5.js";
3
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ import { spawn } from "node:child_process";
6
+ import { join, resolve } from "node:path";
7
+ import { createHash, randomBytes } from "node:crypto";
8
+ import { createServer } from "node:http";
9
+ import { createInterface } from "node:readline";
10
+ //#region src/preview/cursor-permission.ts
11
+ const MAX_PERMISSION_DISPLAY_LENGTH = 12e3;
12
+ function formatCursorPermissionRequest(toolCall) {
13
+ let serialized;
14
+ try {
15
+ serialized = JSON.stringify(toolCall ?? {}, null, 2);
16
+ } catch {
17
+ serialized = String(toolCall);
18
+ }
19
+ const sanitized = [...serialized].filter((character) => {
20
+ const code = character.charCodeAt(0);
21
+ if (code === 9 || code === 10 || code === 13) return true;
22
+ if (code < 32 || code >= 127 && code <= 159) return false;
23
+ if (code === 1564 || code === 65279) return false;
24
+ if (code >= 8203 && code <= 8207) return false;
25
+ if (code >= 8234 && code <= 8238) return false;
26
+ if (code >= 8288 && code <= 8303) return false;
27
+ return true;
28
+ }).join("");
29
+ if (sanitized.length <= MAX_PERMISSION_DISPLAY_LENGTH) return sanitized;
30
+ return `${sanitized.slice(0, MAX_PERMISSION_DISPLAY_LENGTH)}\n… (truncated)`;
31
+ }
32
+ //#endregion
33
+ //#region src/cursor-acp-entry.ts
34
+ const input = process.argv[2];
35
+ if (!input || input === "--help" || input === "-h") {
36
+ process.stdout.write("Usage: artifactshare-preview-cursor <file> [preview options]\n");
37
+ process.exit(input ? 0 : 1);
38
+ }
39
+ const cwd = process.cwd();
40
+ const stateDir = join(previewsDir(), "cursor-acp");
41
+ const statePath = join(stateDir, `${createHash("sha256").update(cwd).digest("hex")}.json`);
42
+ mkdirSync(stateDir, {
43
+ recursive: true,
44
+ mode: 448
45
+ });
46
+ const lockPath = `${statePath}.lock`;
47
+ function acquireWorkspaceLock() {
48
+ for (let attempt = 0; attempt < 2; attempt++) try {
49
+ const handle = openSync(lockPath, "wx", 384);
50
+ writeSync(handle, String(process.pid));
51
+ closeSync(handle);
52
+ return;
53
+ } catch {
54
+ let owner = 0;
55
+ let initializing = false;
56
+ try {
57
+ owner = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
58
+ if (!Number.isInteger(owner) || owner <= 0) {
59
+ const lock = statSync(lockPath, { throwIfNoEntry: false });
60
+ initializing = lock !== void 0 && Date.now() - lock.mtimeMs < 5e3;
61
+ }
62
+ } catch {
63
+ const lock = statSync(lockPath, { throwIfNoEntry: false });
64
+ initializing = lock !== void 0 && Date.now() - lock.mtimeMs < 5e3;
65
+ }
66
+ if (initializing || Number.isInteger(owner) && owner > 0 && processAlive(owner)) throw new Error("A managed Cursor preview is already running in this workspace.");
67
+ rmSync(lockPath, { force: true });
68
+ }
69
+ throw new Error("Could not acquire the managed Cursor workspace lock.");
70
+ }
71
+ function releaseWorkspaceLock() {
72
+ try {
73
+ if (readFileSync(lockPath, "utf8").trim() === String(process.pid)) rmSync(lockPath, { force: true });
74
+ } catch {}
75
+ }
76
+ acquireWorkspaceLock();
77
+ process.once("exit", releaseWorkspaceLock);
78
+ let prior = {};
79
+ try {
80
+ prior = JSON.parse(readFileSync(statePath, "utf8"));
81
+ } catch {}
82
+ const agent = spawn("agent", ["acp"], {
83
+ cwd,
84
+ env: process.env,
85
+ stdio: [
86
+ "pipe",
87
+ "pipe",
88
+ "inherit"
89
+ ]
90
+ });
91
+ let nextId = 1;
92
+ let busy = false;
93
+ let agentAvailable = true;
94
+ let stopping = false;
95
+ let interrupted = false;
96
+ let fatalAgentFailure = false;
97
+ let bridge;
98
+ let preview;
99
+ let sessionId = "";
100
+ let promptAccepted;
101
+ let cancelActivePermission;
102
+ const pending = /* @__PURE__ */ new Map();
103
+ function failAgent(error) {
104
+ if (!agentAvailable) return;
105
+ agentAvailable = false;
106
+ if (!stopping) fatalAgentFailure = true;
107
+ cancelActivePermission?.();
108
+ promptAccepted?.reject(error);
109
+ promptAccepted = void 0;
110
+ for (const waiter of pending.values()) waiter.reject(error);
111
+ pending.clear();
112
+ bridge?.close();
113
+ if (!stopping && preview?.exitCode === null) preview.kill("SIGTERM");
114
+ }
115
+ agent.once("error", failAgent);
116
+ agent.stdin.on("error", failAgent);
117
+ agent.once("exit", () => {
118
+ setImmediate(() => failAgent(/* @__PURE__ */ new Error("Cursor ACP process exited.")));
119
+ });
120
+ function send(method, params) {
121
+ if (!agentAvailable || !agent.stdin.writable) return Promise.reject(/* @__PURE__ */ new Error("Cursor ACP process is unavailable."));
122
+ const id = nextId++;
123
+ return new Promise((resolveRequest, reject) => {
124
+ pending.set(id, {
125
+ resolve: resolveRequest,
126
+ reject
127
+ });
128
+ agent.stdin.write(`${JSON.stringify({
129
+ jsonrpc: "2.0",
130
+ id,
131
+ method,
132
+ params
133
+ })}\n`, (error) => {
134
+ if (!error) return;
135
+ pending.delete(id);
136
+ reject(error);
137
+ });
138
+ });
139
+ }
140
+ function respond(id, result) {
141
+ if (!agentAvailable || !agent.stdin.writable) return;
142
+ agent.stdin.write(`${JSON.stringify({
143
+ jsonrpc: "2.0",
144
+ id,
145
+ result
146
+ })}\n`);
147
+ }
148
+ function respondError(id, code, message) {
149
+ if (!agentAvailable || !agent.stdin.writable) return;
150
+ agent.stdin.write(`${JSON.stringify({
151
+ jsonrpc: "2.0",
152
+ id,
153
+ error: {
154
+ code,
155
+ message
156
+ }
157
+ })}\n`);
158
+ }
159
+ async function answerPermission(message) {
160
+ const options = Array.isArray(message.params?.options) ? message.params.options : [];
161
+ const allow = options.find((option) => typeof option?.optionId === "string" && (option.kind === "allow_once" || option.optionId === "allow-once"));
162
+ const reject = options.find((option) => typeof option?.optionId === "string" && (option.kind === "reject_once" || option.optionId === "reject-once"));
163
+ let approved = false;
164
+ if (process.stdin.isTTY && allow) {
165
+ const requestDetails = formatCursorPermissionRequest(message.params?.toolCall);
166
+ const terminal = createInterface({
167
+ input: process.stdin,
168
+ output: process.stderr
169
+ });
170
+ approved = await new Promise((resolveAnswer) => {
171
+ let settled = false;
172
+ const finish = (answer) => {
173
+ if (settled) return;
174
+ settled = true;
175
+ cancelActivePermission = void 0;
176
+ terminal.close();
177
+ resolveAnswer(answer);
178
+ };
179
+ cancelActivePermission = () => finish(false);
180
+ terminal.once("SIGINT", () => finish(false));
181
+ terminal.once("close", () => finish(false));
182
+ terminal.question(`\nCursor tool request:\n${requestDetails}\nAllow once? [y/N] `, (answer) => {
183
+ finish(answer.trim().toLowerCase() === "y");
184
+ });
185
+ });
186
+ }
187
+ const selected = approved ? allow : reject;
188
+ respond(message.id, selected ? { outcome: {
189
+ outcome: "selected",
190
+ optionId: selected.optionId
191
+ } } : { outcome: { outcome: "cancelled" } });
192
+ }
193
+ let permissionQueue = Promise.resolve();
194
+ createInterface({ input: agent.stdout }).on("line", (line) => {
195
+ let message;
196
+ try {
197
+ message = JSON.parse(line);
198
+ } catch {
199
+ return;
200
+ }
201
+ if (typeof message.id === "number" && (message.result !== void 0 || message.error !== void 0) && !message.method) {
202
+ const waiter = pending.get(message.id);
203
+ if (!waiter) return;
204
+ pending.delete(message.id);
205
+ if (message.error) waiter.reject(new Error(message.error.message ?? "Cursor ACP request failed."));
206
+ else waiter.resolve(message.result);
207
+ return;
208
+ }
209
+ if (message.method === "session/request_permission" && typeof message.id === "number") permissionQueue = permissionQueue.then(() => answerPermission(message)).catch(() => respond(message.id, { outcome: { outcome: "cancelled" } }));
210
+ else if ((message.method === "cursor/ask_question" || message.method === "cursor/create_plan") && typeof message.id === "number") respond(message.id, { outcome: { outcome: "cancelled" } });
211
+ else if (message.method === "session/update" && promptAccepted && message.params?.sessionId === sessionId && [
212
+ "agent_message_chunk",
213
+ "agent_thought_chunk",
214
+ "tool_call",
215
+ "tool_call_update",
216
+ "plan"
217
+ ].includes(message.params?.update?.sessionUpdate)) {
218
+ promptAccepted?.resolve();
219
+ promptAccepted = void 0;
220
+ } else if (typeof message.id === "number" && message.method) respondError(message.id, -32601, `Unsupported ACP request: ${message.method}`);
221
+ });
222
+ async function initializeSession() {
223
+ await send("initialize", {
224
+ protocolVersion: 1,
225
+ clientCapabilities: {
226
+ fs: {
227
+ readTextFile: false,
228
+ writeTextFile: false
229
+ },
230
+ terminal: false
231
+ },
232
+ clientInfo: {
233
+ name: "artifactshare-preview-cursor",
234
+ version: "1"
235
+ }
236
+ });
237
+ await send("authenticate", { methodId: "cursor_login" });
238
+ if (prior.session_id && prior.cwd === cwd) try {
239
+ await send("session/load", {
240
+ sessionId: prior.session_id,
241
+ cwd,
242
+ mcpServers: []
243
+ });
244
+ return prior.session_id;
245
+ } catch {
246
+ const created = await send("session/new", {
247
+ cwd,
248
+ mcpServers: []
249
+ });
250
+ if (typeof created?.sessionId !== "string") throw new Error("Cursor ACP did not return a session id.");
251
+ return created.sessionId;
252
+ }
253
+ const created = await send("session/new", {
254
+ cwd,
255
+ mcpServers: []
256
+ });
257
+ if (typeof created?.sessionId !== "string") throw new Error("Cursor ACP did not return a session id.");
258
+ return created.sessionId;
259
+ }
260
+ try {
261
+ sessionId = await initializeSession();
262
+ } catch (error) {
263
+ agent.kill();
264
+ throw error;
265
+ }
266
+ const temp = `${statePath}.${process.pid}.tmp`;
267
+ writeFileSync(temp, JSON.stringify({
268
+ schema_version: 1,
269
+ session_id: sessionId,
270
+ cwd
271
+ }, null, 2), { mode: 384 });
272
+ renameSync(temp, statePath);
273
+ const token = randomBytes(32).toString("hex");
274
+ const server = createServer((request, response) => {
275
+ if (request.method !== "POST" || request.url !== "/preview-batch") {
276
+ response.writeHead(404).end();
277
+ return;
278
+ }
279
+ if (request.headers.authorization !== `Bearer ${token}`) {
280
+ response.writeHead(401).end();
281
+ return;
282
+ }
283
+ if (busy) {
284
+ response.writeHead(409).end();
285
+ return;
286
+ }
287
+ busy = true;
288
+ let bodyComplete = false;
289
+ request.once("aborted", () => {
290
+ if (!bodyComplete) busy = false;
291
+ });
292
+ let body = "";
293
+ request.setEncoding("utf8");
294
+ request.on("data", (chunk) => {
295
+ body += chunk;
296
+ if (body.length > 16384) request.destroy();
297
+ });
298
+ request.on("end", async () => {
299
+ bodyComplete = true;
300
+ let event;
301
+ try {
302
+ event = JSON.parse(body);
303
+ } catch {
304
+ busy = false;
305
+ response.writeHead(400).end();
306
+ return;
307
+ }
308
+ if (event?.event !== "preview.batch_ready" || typeof event.preview_session_id !== "string" || typeof event.batch_id !== "string") {
309
+ busy = false;
310
+ response.writeHead(400).end();
311
+ return;
312
+ }
313
+ if (!agentAvailable) {
314
+ busy = false;
315
+ response.writeHead(503).end();
316
+ return;
317
+ }
318
+ const filePath = resolve(cwd, input);
319
+ const text = `Artifact Share preview batch ready for ${JSON.stringify(filePath)}. event=preview.batch_ready preview_session_id=${event.preview_session_id} batch_id=${event.batch_id}. Run: npm exec --yes --package=@artifactshare/cli -- artifactshare preview next --session ${event.preview_session_id} --json. Fetch all comment text only with preview next.`;
320
+ const accepted = new Promise((resolveAccepted, reject) => {
321
+ promptAccepted = {
322
+ resolve: resolveAccepted,
323
+ reject
324
+ };
325
+ });
326
+ const prompt = send("session/prompt", {
327
+ sessionId,
328
+ prompt: [{
329
+ type: "text",
330
+ text
331
+ }]
332
+ });
333
+ const promptTimer = setTimeout(() => {
334
+ failAgent(/* @__PURE__ */ new Error("Cursor ACP preview prompt timed out."));
335
+ agent.kill("SIGTERM");
336
+ }, CURSOR_ACP_ACK_TIMEOUT_MS);
337
+ promptTimer.unref();
338
+ accepted.then(() => clearTimeout(promptTimer), () => clearTimeout(promptTimer));
339
+ prompt.then((result) => {
340
+ if (result?.stopReason === "end_turn") promptAccepted?.resolve();
341
+ else promptAccepted?.reject(/* @__PURE__ */ new Error("Cursor ACP did not complete the preview prompt."));
342
+ }).catch((error) => promptAccepted?.reject(error)).finally(() => {
343
+ busy = false;
344
+ promptAccepted = void 0;
345
+ });
346
+ try {
347
+ await accepted;
348
+ response.writeHead(202).end();
349
+ } catch {
350
+ response.writeHead(agentAvailable ? 502 : 503).end();
351
+ }
352
+ });
353
+ });
354
+ bridge = server;
355
+ await new Promise((resolveListen, reject) => {
356
+ server.once("error", reject);
357
+ server.listen(0, "127.0.0.1", resolveListen);
358
+ });
359
+ const address = server.address();
360
+ if (!address || typeof address === "string") throw new Error("Cursor ACP bridge did not bind.");
361
+ const target = {
362
+ schema_version: 1,
363
+ endpoint: `http://127.0.0.1:${address.port}/preview-batch`,
364
+ token,
365
+ pid: process.pid,
366
+ session_id: sessionId,
367
+ cwd
368
+ };
369
+ preview = spawn(process.execPath, [
370
+ fileURLToPath(new URL("./index.js", import.meta.url)),
371
+ "preview",
372
+ input,
373
+ ...process.argv.slice(3)
374
+ ], {
375
+ cwd,
376
+ env: {
377
+ ...process.env,
378
+ CODEX_THREAD_ID: "",
379
+ CODEX_SESSION_ID: "",
380
+ CLAUDE_CODE_SESSION_ID: "",
381
+ ARTIFACTSHARE_CURSOR_ACP_TARGET: JSON.stringify(target)
382
+ },
383
+ stdio: "inherit"
384
+ });
385
+ process.once("SIGINT", () => {
386
+ stopping = true;
387
+ interrupted = true;
388
+ process.exitCode = 130;
389
+ cancelActivePermission?.();
390
+ setTimeout(() => {
391
+ if (preview?.exitCode === null) preview.kill("SIGTERM");
392
+ if (agent.exitCode === null) agent.kill("SIGTERM");
393
+ }, 2e3).unref();
394
+ });
395
+ process.once("SIGTERM", () => {
396
+ stopping = true;
397
+ cancelActivePermission?.();
398
+ preview?.kill("SIGTERM");
399
+ agent.kill("SIGTERM");
400
+ });
401
+ const previewExit = await new Promise((resolveExit) => preview.once("exit", (code, signal) => resolveExit({
402
+ code,
403
+ signal
404
+ })));
405
+ if (previewExit.signal === "SIGINT") interrupted = true;
406
+ stopping = true;
407
+ server.close();
408
+ agent.stdin.end();
409
+ agent.kill();
410
+ releaseWorkspaceLock();
411
+ process.exitCode = interrupted ? 130 : fatalAgentFailure ? 1 : previewExit.code ?? 1;
412
+ //#endregion
413
+ export {};