@outerlayer/cli 0.9.0 → 0.10.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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @outerlayer/cli
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 60067bc: `outerlayer work pr` and `outerlayer work open-pr` now declare a pull request onto the work item named by `OUTERLAYER_WORK`, and refuse when the session is not on that item. The message names both item numbers and `--session-id`. A successful declaration prints the item's number and title. `outerlayer work pr <n> --withdraw --item <number>` removes a wrong declaration.
8
+
3
9
  ## 0.9.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -74,8 +74,10 @@ content:
74
74
  hook spawns `outerlayer work link-session` when you launch a session with
75
75
  `OUTERLAYER_WORK`, naming the item and the session id — the item itself
76
76
  must already exist, created ahead of time with `outerlayer work build --local`.
77
- `outerlayer work pr` sends the session id and the pull request number and
78
- repository — never the session's own content. `outerlayer work open-pr`
77
+ `outerlayer work pr` sends the session id, the `OUTERLAYER_WORK` item
78
+ number and the pull request number and repository — never the session's
79
+ own content. With `--withdraw` it sends a DELETE naming the item, the
80
+ repository and the pull request number. `outerlayer work open-pr`
79
81
  sends the pull request's title and the text of the body file you name. In a
80
82
  host build, which holds an item key, it goes to the gateway, which opens or
81
83
  edits the pull request as the factory's GitHub App on the branch the claim
@@ -375,7 +377,7 @@ before it gives up.
375
377
  | `outerlayer work remove --issue <n>\|--pr <n> --reason <text> [--repo]` | Withdraws the caller's own addition, recording the reason. Never deletes anything; the item leaves the Work page only once no live addition remains on it. Removing again is a no-op that still succeeds. |
376
378
  | `outerlayer work status --issue <n>\|--pr <n> [--repo]` | Shows one item's stage, section, gate ledger, linked pull requests and sessions, and its additions. |
377
379
  | `outerlayer work list [--stage] [--section] [--repo] [--claimed] [--unclaimed] [--startable] [--needs amend]` | Lists live work items for the current factory, filterable by stage, section, claim state, startability and whether a comment thread is waiting on an agent. |
378
- | `outerlayer work pr <n> [--repo] [--session-id]` | Run inside a session on a work item: declares that pull request `<n>` in the checkout's repository belongs to that item. Idempotent — declaring the same pull request twice is a no-op. Refuses when the session is on no item, or the repository is not connected. |
380
+ | `outerlayer work pr <n> [--repo] [--session-id] [--withdraw --item <number>]` | Run inside a session on a work item: declares that pull request `<n>` in the checkout's repository belongs to the `OUTERLAYER_WORK` item. Idempotent — declaring the same pull request twice is a no-op. Refuses when the session is not on that item, or the repository is not connected. `--withdraw --item <number>` removes that item's declaration; it needs your own login. |
379
381
  | `outerlayer work open-pr --title <text> --body-file <path> [--repo] [--session-id] [--json]` | Opens the pull request for the work item this session is on, or edits the one already open on its branch. A host build, which holds an item key, sends it to the gateway, which opens it as the factory's GitHub App from the branch the claim named; no `gh` command runs. Your own session runs `gh pr create` or `gh pr edit` under your login and then declares the pull request on the item. Run it again after changing the title or description. |
380
382
  | `outerlayer work claim --item <n>\|--issue <n> --kind implement\|amend [--repo] [--host] [--seconds]` | Records a lease for this host (default: its own hostname), so two hosts never build the same item at once. The lease belongs to the runner key that claimed it: a live lease held by a different key is refused, even under the same host name, and claiming again with the same key extends it. The first claim creates the host key (`host-key.pem` beside the config file) and binds the runner key to it; from then on every request made with that key is signed. Lease length defaults to 900 seconds, the server's own cap. |
381
383
  | `outerlayer work renew --item <n>\|--issue <n> [--repo] [--host] [--seconds]` | Extends this host's own live lease. Refused if the lease has expired, or if a different runner key holds it (403 `claim_not_held`). |
@@ -1 +1 @@
1
- {"id":"2026-10-07T00:34:36.863Z+f427d9c","root":"/home/runner/_work/outerlayer/outerlayer","pkg":"outerlayer"}
1
+ {"id":"2026-10-07T12:35:00.915Z+be9473d","root":"/home/runner/_work/outerlayer/outerlayer","pkg":"outerlayer"}
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { autoConnect } from './chunk-KPUJGBA4.js';
4
+ import { detectActiveSession } from './chunk-BFESLKPP.js';
5
+ import { resolveRepoIdentity } from './chunk-LTJPX7TX.js';
6
+ import { parseWorkItemEnv } from './chunk-GQD22KKN.js';
7
+ import { parseTrackerNumber, trackerNumberError } from './chunk-WZBHBH3J.js';
8
+ import { defaultFetch } from './chunk-YO4PSLVB.js';
9
+ import { unauthorizedMessage, resolveGatewayCredentials } from './chunk-PLMTLGYH.js';
10
+ import { homeFromEnv } from './chunk-VNVZDWO3.js';
11
+
12
+ createRequire(import.meta.url);
13
+
14
+ // src/work-pr-cmd.ts
15
+ var GREEN = "\x1B[32m";
16
+ var DIM = "\x1B[2m";
17
+ var RESET = "\x1B[0m";
18
+ var WorkPrCommandError = class extends Error {
19
+ };
20
+ function resolveCredentials(opts) {
21
+ const resolved = resolveGatewayCredentials(opts);
22
+ if (!resolved.ok) throw new WorkPrCommandError(resolved.message);
23
+ return { url: resolved.url, apiKey: resolved.credential, appId: resolved.appId };
24
+ }
25
+ function resolveRepository(repoFlag, cwd) {
26
+ if (repoFlag) return repoFlag;
27
+ const identity = resolveRepoIdentity(cwd);
28
+ if (identity.gitRepo) return identity.gitRepo;
29
+ throw new WorkPrCommandError(
30
+ "no repository. Pass --repo <owner/name>, or run from a git checkout with a remote."
31
+ );
32
+ }
33
+ function resolvePrNumber(raw) {
34
+ const n = parseTrackerNumber(raw);
35
+ if (n === void 0) throw new WorkPrCommandError(trackerNumberError("<n>", raw ?? ""));
36
+ return n;
37
+ }
38
+ var SESSION_ID_HINT = "pass --session-id <id> to name the session that was launched on the item";
39
+ function sessionNotOnItemMessage(error, sessionId) {
40
+ const on = error.sessionItems;
41
+ const onText = on === void 0 ? "" : `; it is on ${on.length === 0 ? "no work item" : on.map((n) => `item ${n}`).join(", ")}`;
42
+ return `session ${sessionId} is not on item ${error.workItem ?? "?"} (OUTERLAYER_WORK)${onText}. Nothing was declared. If another session was launched for item ${error.workItem ?? "?"}, ${SESSION_ID_HINT}.`;
43
+ }
44
+ function itemLabel(data) {
45
+ if (data.workItemNumber == null) return data.workItemId;
46
+ return data.workItemTitle ? `item ${data.workItemNumber} ${DIM}\xB7${RESET} ${data.workItemTitle}` : `item ${data.workItemNumber}`;
47
+ }
48
+ async function runWorkPrWithdraw(opts, ctx) {
49
+ const itemNumber = parseTrackerNumber(opts.item);
50
+ if (itemNumber === void 0) {
51
+ throw new WorkPrCommandError("--withdraw needs --item <number>, the item to remove the declaration from.");
52
+ }
53
+ const { creds, prNumber, repository, sessionId } = ctx;
54
+ const fetchImpl = opts.fetchImpl ?? defaultFetch;
55
+ const query = sessionId === void 0 ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
56
+ const endpoint = new URL(
57
+ `/v1/work-items/${itemNumber}/pull-requests/${encodeURIComponent(repository)}/${prNumber}${query}`,
58
+ creds.url
59
+ ).toString();
60
+ let response;
61
+ try {
62
+ response = await fetchImpl(endpoint, {
63
+ method: "DELETE",
64
+ headers: { authorization: `Bearer ${creds.apiKey}`, "x-outerlayer-app-id": creds.appId }
65
+ });
66
+ } catch (err) {
67
+ throw new WorkPrCommandError(`network error reaching ${endpoint}: ${String(err)}`);
68
+ }
69
+ if (response.status === 401) throw new WorkPrCommandError(unauthorizedMessage(creds.apiKey));
70
+ let json;
71
+ try {
72
+ json = await response.json();
73
+ } catch {
74
+ throw new WorkPrCommandError(
75
+ `${endpoint} answered ${response.status} with a body that is not JSON \u2014 the request may not have reached the gateway`
76
+ );
77
+ }
78
+ if (!response.ok || !json.data) {
79
+ if (json.error?.code === "withdraw_needs_person") {
80
+ throw new WorkPrCommandError("only a person can withdraw a declaration; run this from your own login, not an agent session or a factory key.");
81
+ }
82
+ if (json.error?.code === "declaration_not_found") {
83
+ throw new WorkPrCommandError(`item ${itemNumber} has no declaration of ${repository}#${prNumber}.`);
84
+ }
85
+ if (json.error?.code === "work_item_not_found") {
86
+ throw new WorkPrCommandError(`item ${itemNumber} does not exist in this factory.`);
87
+ }
88
+ throw new WorkPrCommandError(json.error?.message ?? `request failed (${response.status})`);
89
+ }
90
+ const data = json.data;
91
+ const output = opts.json ? JSON.stringify(data) : `${GREEN}\u2713${RESET} withdrawn ${DIM}\xB7${RESET} ${data.repository}#${data.prNumber} ${DIM}from${RESET} item ${itemNumber}`;
92
+ if (!opts.quiet) process.stdout.write(output + "\n");
93
+ return { data, output };
94
+ }
95
+ async function runWorkPr(opts) {
96
+ const cwd = opts.cwd ?? process.cwd();
97
+ const env = opts.env ?? process.env;
98
+ const home = opts.home ?? homeFromEnv(env);
99
+ const refusal = await autoConnect({ ...opts, repository: opts.repo });
100
+ if (refusal !== void 0) throw new WorkPrCommandError(refusal);
101
+ const creds = resolveCredentials(opts);
102
+ const prNumber = resolvePrNumber(opts.number);
103
+ const repository = resolveRepository(opts.repo, cwd);
104
+ const identity = resolveRepoIdentity(cwd);
105
+ const sessionId = opts.sessionId ?? detectActiveSession({
106
+ env,
107
+ home,
108
+ cwds: identity.repoRoot !== void 0 ? [identity.repoRoot, cwd] : [cwd],
109
+ nowMs: Date.now()
110
+ });
111
+ if (opts.withdraw) return runWorkPrWithdraw(opts, { creds, prNumber, repository, sessionId });
112
+ let workItem;
113
+ if (env.OUTERLAYER_WORK !== void 0) {
114
+ const parsed = parseWorkItemEnv(env.OUTERLAYER_WORK);
115
+ if (!("number" in parsed)) throw new WorkPrCommandError(parsed.reason);
116
+ workItem = parsed.number;
117
+ }
118
+ if (sessionId === void 0) {
119
+ throw new WorkPrCommandError(
120
+ `no active session detected. \`work pr\` declares a pull request from inside the session that opened it, or ${SESSION_ID_HINT}.`
121
+ );
122
+ }
123
+ const fetchImpl = opts.fetchImpl ?? defaultFetch;
124
+ const headers = {
125
+ "content-type": "application/json",
126
+ authorization: `Bearer ${creds.apiKey}`,
127
+ "x-outerlayer-app-id": creds.appId
128
+ };
129
+ const endpoint = new URL("/v1/work-items/pull-requests", creds.url).toString();
130
+ let response;
131
+ try {
132
+ response = await fetchImpl(endpoint, {
133
+ method: "POST",
134
+ headers,
135
+ body: JSON.stringify({
136
+ sessionId,
137
+ workItem,
138
+ // JSON.stringify omits it when undefined
139
+ pullRequest: { repository, number: prNumber }
140
+ })
141
+ });
142
+ } catch (err) {
143
+ throw new WorkPrCommandError(`network error reaching ${endpoint}: ${String(err)}`);
144
+ }
145
+ if (response.status === 401) {
146
+ throw new WorkPrCommandError(
147
+ unauthorizedMessage(creds.apiKey)
148
+ );
149
+ }
150
+ let json;
151
+ try {
152
+ json = await response.json();
153
+ } catch {
154
+ throw new WorkPrCommandError(
155
+ `${endpoint} answered ${response.status} with a body that is not JSON \u2014 the request may not have reached the gateway`
156
+ );
157
+ }
158
+ if (!response.ok || !json.data) {
159
+ if (json.error?.code === "session_not_on_item") {
160
+ if (response.status === 409) throw new WorkPrCommandError(sessionNotOnItemMessage(json.error, sessionId));
161
+ throw new WorkPrCommandError("this session is not launched on a work item.");
162
+ }
163
+ if (json.error?.code === "work_item_not_found" && workItem !== void 0) {
164
+ throw new WorkPrCommandError(`OUTERLAYER_WORK names item ${workItem}, which does not exist in this factory.`);
165
+ }
166
+ if (json.error?.code === "repository_not_connected") {
167
+ throw new WorkPrCommandError(`${repository} is not a workpiece of this factory.`);
168
+ }
169
+ throw new WorkPrCommandError(json.error?.message ?? `request failed (${response.status})`);
170
+ }
171
+ const data = json.data;
172
+ const verb = data.created ? "declared" : "already declared";
173
+ const output = opts.json ? JSON.stringify(data) : `${GREEN}\u2713${RESET} ${verb} ${DIM}\xB7${RESET} ${data.repository}#${data.prNumber} ${DIM}\u2192${RESET} ${itemLabel(data)}`;
174
+ if (!opts.quiet) process.stdout.write(output + "\n");
175
+ return { data, output };
176
+ }
177
+
178
+ export { WorkPrCommandError, itemLabel, runWorkPr };
@@ -4413,12 +4413,12 @@ live addition remains on it.
4413
4413
  throw err;
4414
4414
  }
4415
4415
  });
4416
- workCmd.command("pr <number>").description("Declare that a pull request belongs to the work item this session is on").option("--repo <owner/name>", "repository (default: the current checkout's remote)").option("--session-id <id>", "session id to record as-is, skipping detection").option("--json", "machine-readable JSON output").option("--url <url>", "cloud base URL (or OUTERLAYER_URL / config)").addOption(apiKeyOption()).option("--app-id <id>", "factory id the key is bound to (or OUTERLAYER_APP_ID / config)").addHelpText(
4416
+ workCmd.command("pr <number>").description("Declare a pull request onto the launched work item, or withdraw it").option("--repo <owner/name>", "repository (default: the current checkout's remote)").option("--session-id <id>", "session id to record as-is, skipping detection").option("--withdraw", "remove the declaration instead of making one (needs --item)").option("--item <number>", "with --withdraw, the item to remove the declaration from").option("--json", "machine-readable JSON output").option("--url <url>", "cloud base URL (or OUTERLAYER_URL / config)").addOption(apiKeyOption()).option("--app-id <id>", "factory id the key is bound to (or OUTERLAYER_APP_ID / config)").addHelpText(
4417
4417
  "after",
4418
- "\n outerlayer work pr 481\n\nRun inside a session already on a work item. Records that pull\nrequest 481 in the checkout's repository belongs to that item \u2014 the\nsame fact a `pr-link` in the session's own transcript records on\nsync. Idempotent: declaring the same pull request twice is a no-op.\n"
4418
+ "\n outerlayer work pr 481\n outerlayer work pr 481 --withdraw --item 250\n\nRun inside a session already on a work item. Records that pull\nrequest 481 in the checkout's repository belongs to the item named by\nOUTERLAYER_WORK, or refuses when the session is not on it. The same\nfact a `pr-link` in the session's own transcript records on sync.\nIdempotent: declaring the same pull request twice is a no-op.\n\n--withdraw removes one item's declaration of the pull request. It\nneeds your own login; an agent session or a factory key is refused.\n"
4419
4419
  ).action(async (number, opts) => {
4420
4420
  warnIfApiKeyFlag(opts);
4421
- const { runWorkPr, WorkPrCommandError } = await import('./work-pr-cmd-MX6UO5GO.js');
4421
+ const { runWorkPr, WorkPrCommandError } = await import('./work-pr-cmd-6TMSCO3Q.js');
4422
4422
  try {
4423
4423
  await runWorkPr({ ...opts, number });
4424
4424
  } catch (err) {
@@ -4434,7 +4434,7 @@ live addition remains on it.
4434
4434
  '\n outerlayer work open-pr --title "Add the thing" --body-file pr.md\n\nIn a host build, which holds an item key, the gateway opens the pull\nrequest as the factory\'s GitHub App, from the branch the claim named,\nor edits the one already open on that branch. No gh command runs.\nIn your own session it runs `gh pr create` (or `gh pr edit`) under your\nlogin, then declares the pull request on the item, as `work pr` does.\nRun it again after a change to the title or description.\n'
4435
4435
  ).action(async (opts) => {
4436
4436
  warnIfApiKeyFlag(opts);
4437
- const { runWorkOpenPr, WorkOpenPrCommandError } = await import('./work-open-pr-cmd-ZYOC5SPB.js');
4437
+ const { runWorkOpenPr, WorkOpenPrCommandError } = await import('./work-open-pr-cmd-YESMWATB.js');
4438
4438
  const { WorkCommandError } = await import('./work-cmd-TK4VOOHL.js');
4439
4439
  try {
4440
4440
  await runWorkOpenPr(opts);
package/dist/index.js CHANGED
@@ -22,5 +22,5 @@ if (argv[0] === "statusline") {
22
22
  process.exit(0);
23
23
  }
24
24
  (await import('./hook-fast-AQCAQIA6.js')).recordLinkExitFailure(argv);
25
- var { runCli } = await import('./cli-7RQYILJT.js');
25
+ var { runCli } = await import('./cli-77URFYI7.js');
26
26
  await runCli(process.argv);
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module';
3
- import { runWorkPr, WorkPrCommandError } from './chunk-5MF73XCV.js';
3
+ import { itemLabel, runWorkPr, WorkPrCommandError } from './chunk-5K3IUOPJ.js';
4
4
  import { resolveCredentials } from './chunk-KWCJLAHQ.js';
5
5
  import './chunk-KPUJGBA4.js';
6
6
  import './chunk-BFESLKPP.js';
@@ -10,6 +10,7 @@ import './chunk-LTJPX7TX.js';
10
10
  import './chunk-USO2DKBD.js';
11
11
  import './chunk-N6LURUEF.js';
12
12
  import './chunk-YRYMNBGQ.js';
13
+ import { parseWorkItemEnv } from './chunk-GQD22KKN.js';
13
14
  import './chunk-WZBHBH3J.js';
14
15
  import { defaultFetch } from './chunk-YO4PSLVB.js';
15
16
  import './chunk-PLMTLGYH.js';
@@ -82,6 +83,11 @@ async function openThroughGateway(creds, workItem, title, body, fetchImpl) {
82
83
  return json.data;
83
84
  }
84
85
  async function openWithGh(opts, title, bodyFile, cwd) {
86
+ const launched = opts.env.OUTERLAYER_WORK;
87
+ if (launched !== void 0) {
88
+ const parsed = parseWorkItemEnv(launched);
89
+ if (!("number" in parsed)) throw new WorkOpenPrCommandError(parsed.reason);
90
+ }
85
91
  const runGh = opts.runGh ?? spawnGh;
86
92
  const viewed = runGh(["pr", "view", "--json", "number"], cwd);
87
93
  let existing;
@@ -130,7 +136,9 @@ async function openWithGh(opts, title, bodyFile, cwd) {
130
136
  repository,
131
137
  number,
132
138
  url: urlMatch ? urlMatch[0] : `https://${repository.startsWith("github.com/") ? repository : `github.com/${repository}`}/pull/${number}`,
133
- created: existing === void 0
139
+ created: existing === void 0,
140
+ workItemNumber: declared.data.workItemNumber,
141
+ workItemTitle: declared.data.workItemTitle
134
142
  };
135
143
  }
136
144
  async function runWorkOpenPr(opts) {
@@ -154,7 +162,7 @@ async function runWorkOpenPr(opts) {
154
162
  } else {
155
163
  data = await openWithGh({ ...opts, env }, opts.title, opts.bodyFile, cwd);
156
164
  }
157
- const output = opts.json ? JSON.stringify(data) : `${GREEN}\u2713${RESET} ${data.created ? "opened" : "edited"} ${DIM}\xB7${RESET} ${data.repository}#${data.number} ${DIM}\xB7${RESET} ${data.url}`;
165
+ const output = opts.json ? JSON.stringify(data) : `${GREEN}\u2713${RESET} ${data.created ? "opened" : "edited"} ${DIM}\xB7${RESET} ${data.repository}#${data.number} ${DIM}\xB7${RESET} ${data.url}${data.workItemNumber == null ? "" : ` ${DIM}\u2192${RESET} ${itemLabel({ workItemId: "", ...data })}`}`;
158
166
  if (!opts.quiet) process.stdout.write(output + "\n");
159
167
  return { data, output };
160
168
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module';
3
- export { WorkPrCommandError, runWorkPr } from './chunk-5MF73XCV.js';
3
+ export { WorkPrCommandError, itemLabel, runWorkPr } from './chunk-5K3IUOPJ.js';
4
4
  import './chunk-KPUJGBA4.js';
5
5
  import './chunk-BFESLKPP.js';
6
6
  import './chunk-LYESSQUA.js';
@@ -9,6 +9,7 @@ import './chunk-LTJPX7TX.js';
9
9
  import './chunk-USO2DKBD.js';
10
10
  import './chunk-N6LURUEF.js';
11
11
  import './chunk-YRYMNBGQ.js';
12
+ import './chunk-GQD22KKN.js';
12
13
  import './chunk-WZBHBH3J.js';
13
14
  import './chunk-YO4PSLVB.js';
14
15
  import './chunk-PLMTLGYH.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outerlayer/cli",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "OuterLayer CLI — commands: init, connect, doctor, login, logout, sync, daemon (alias: watch), emit, work, runner, hooks, mcp, import, context. Capture and sync coding-agent sessions, and record proof of factory work.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Magu Studios, Inc.",
@@ -1,103 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- import { autoConnect } from './chunk-KPUJGBA4.js';
4
- import { detectActiveSession } from './chunk-BFESLKPP.js';
5
- import { resolveRepoIdentity } from './chunk-LTJPX7TX.js';
6
- import { parseTrackerNumber, trackerNumberError } from './chunk-WZBHBH3J.js';
7
- import { defaultFetch } from './chunk-YO4PSLVB.js';
8
- import { unauthorizedMessage, resolveGatewayCredentials } from './chunk-PLMTLGYH.js';
9
- import { homeFromEnv } from './chunk-VNVZDWO3.js';
10
-
11
- createRequire(import.meta.url);
12
-
13
- // src/work-pr-cmd.ts
14
- var GREEN = "\x1B[32m";
15
- var DIM = "\x1B[2m";
16
- var RESET = "\x1B[0m";
17
- var WorkPrCommandError = class extends Error {
18
- };
19
- function resolveCredentials(opts) {
20
- const resolved = resolveGatewayCredentials(opts);
21
- if (!resolved.ok) throw new WorkPrCommandError(resolved.message);
22
- return { url: resolved.url, apiKey: resolved.credential, appId: resolved.appId };
23
- }
24
- function resolveRepository(repoFlag, cwd) {
25
- if (repoFlag) return repoFlag;
26
- const identity = resolveRepoIdentity(cwd);
27
- if (identity.gitRepo) return identity.gitRepo;
28
- throw new WorkPrCommandError(
29
- "no repository. Pass --repo <owner/name>, or run from a git checkout with a remote."
30
- );
31
- }
32
- function resolvePrNumber(raw) {
33
- const n = parseTrackerNumber(raw);
34
- if (n === void 0) throw new WorkPrCommandError(trackerNumberError("<n>", raw ?? ""));
35
- return n;
36
- }
37
- async function runWorkPr(opts) {
38
- const cwd = opts.cwd ?? process.cwd();
39
- const env = opts.env ?? process.env;
40
- const home = opts.home ?? homeFromEnv(env);
41
- const refusal = await autoConnect({ ...opts, repository: opts.repo });
42
- if (refusal !== void 0) throw new WorkPrCommandError(refusal);
43
- const creds = resolveCredentials(opts);
44
- const prNumber = resolvePrNumber(opts.number);
45
- const repository = resolveRepository(opts.repo, cwd);
46
- const identity = resolveRepoIdentity(cwd);
47
- const sessionId = opts.sessionId ?? detectActiveSession({
48
- env,
49
- home,
50
- cwds: identity.repoRoot !== void 0 ? [identity.repoRoot, cwd] : [cwd],
51
- nowMs: Date.now()
52
- });
53
- if (sessionId === void 0) {
54
- throw new WorkPrCommandError(
55
- "no active session detected. `work pr` declares a pull request from inside the session that opened it."
56
- );
57
- }
58
- const fetchImpl = opts.fetchImpl ?? defaultFetch;
59
- const endpoint = new URL("/v1/work-items/pull-requests", creds.url).toString();
60
- let response;
61
- try {
62
- response = await fetchImpl(endpoint, {
63
- method: "POST",
64
- headers: {
65
- "content-type": "application/json",
66
- authorization: `Bearer ${creds.apiKey}`,
67
- "x-outerlayer-app-id": creds.appId
68
- },
69
- body: JSON.stringify({ sessionId, pullRequest: { repository, number: prNumber } })
70
- });
71
- } catch (err) {
72
- throw new WorkPrCommandError(`network error reaching ${endpoint}: ${String(err)}`);
73
- }
74
- if (response.status === 401) {
75
- throw new WorkPrCommandError(
76
- unauthorizedMessage(creds.apiKey)
77
- );
78
- }
79
- let json;
80
- try {
81
- json = await response.json();
82
- } catch {
83
- throw new WorkPrCommandError(
84
- `${endpoint} answered ${response.status} with a body that is not JSON \u2014 the request may not have reached the gateway`
85
- );
86
- }
87
- if (!response.ok || !json.data) {
88
- if (json.error?.code === "session_not_on_item") {
89
- throw new WorkPrCommandError("this session is not launched on a work item.");
90
- }
91
- if (json.error?.code === "repository_not_connected") {
92
- throw new WorkPrCommandError(`${repository} is not a workpiece of this factory.`);
93
- }
94
- throw new WorkPrCommandError(json.error?.message ?? `request failed (${response.status})`);
95
- }
96
- const data = json.data;
97
- const verb = data.created ? "declared" : "already declared";
98
- const output = opts.json ? JSON.stringify(data) : `${GREEN}\u2713${RESET} ${verb} ${DIM}\xB7${RESET} ${data.repository}#${data.prNumber} ${DIM}\u2192${RESET} ${data.workItemId}`;
99
- if (!opts.quiet) process.stdout.write(output + "\n");
100
- return { data, output };
101
- }
102
-
103
- export { WorkPrCommandError, runWorkPr };