@gheima/cli 0.6.0 → 0.8.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,34 @@
1
1
  # @gheima/cli
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c2a2f09: `gheima agents` prints a short section for a repository's `AGENTS.md` that tells coding agents how the project deploys on Gheima: the linked service, the deploy and logs commands, and the exit codes. `--write` adds it to the file between markers, so running it again replaces it instead of adding a copy.
8
+
9
+ ### Patch Changes
10
+
11
+ - 83540e6: `streamLogs` now reconnects when the server ends a live tail. The API closes every tail after 30 minutes. A runtime tail resumes from the millisecond after the last line it yielded, the same step the live poll already uses. Lines are not repeated, and lines written while it reconnects are not lost. The iterator now ends only when you abort it or when a reconnect is refused (for example, a revoked key), and in that case it throws. `gheima logs -f` keeps tailing past 30 minutes.
12
+ - Updated dependencies [c4af7ee]
13
+ - Updated dependencies [83540e6]
14
+ - @gheima/contracts@0.2.1
15
+ - @gheima/sdk@0.5.0
16
+
17
+ ## 0.7.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 9067536: **`gheima run <service> -- <cmd>`** runs a one-off command (a migration, a seed) in a fresh container from the service's live image and environment, waits for it, prints its log and exits with the command's own exit code, or **9** when the run ended without one (refused, timed out). `--timeout <seconds>` (default 300, at most 3600) bounds the command; `--no-wait` only queues it. Under `--json`, stdout is one document holding the run and its log.
22
+
23
+ ### Patch Changes
24
+
25
+ - d011c04: **Breaking (types only):** response types now say what the API actually sends. `ServiceSummary.url` and `.branch`, and `Service.projectId`, `.subdomain` and `.repoBranch` are `string | null` (a service need not sit in a project, and has no URL until it is routed). `Service` no longer declares `branch`, which the single-service response never carried — use `repoBranch`. `QueueSummary.keyPrefix` is `string | null`, and `ActivityEvent` is read from the API contract: `metadata` is `unknown` (narrow it before use) and `actorName` is added. Code that compiled against 0.3.0 may need a null check; nothing changes at runtime.
26
+
27
+ `gheima open --live` now says the service has no live URL yet instead of trying to open `null`.
28
+
29
+ - Updated dependencies [d011c04]
30
+ - @gheima/sdk@0.4.0
31
+
3
32
  ## 0.6.0
4
33
 
5
34
  ### Minor Changes
package/README.md CHANGED
@@ -9,7 +9,15 @@ gheima login
9
9
  gheima services
10
10
  ```
11
11
 
12
- Requires Node.js 20.18.1 or newer.
12
+ Requires Node.js 20.18.1 or newer, unless you use the standalone binary, which needs nothing:
13
+
14
+ ```bash
15
+ curl -fsSL https://gheima.ma/install.sh | sh # macOS / Linux, checksum-verified, to ~/.local/bin
16
+ brew install gheima/tap/gheima # or Homebrew
17
+ ```
18
+
19
+ Windows: download `gheima-windows-x64.exe` from the
20
+ [latest release](https://github.com/gheima/cli/releases/latest).
13
21
 
14
22
  ## Authentication
15
23
 
@@ -67,17 +75,18 @@ This bites anyone who set a custom npm prefix to avoid `sudo` without also exten
67
75
 
68
76
  ### Services
69
77
 
70
- | Command | Description |
71
- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
72
- | `gheima services [list]` | List services |
73
- | `gheima services get <service>` | Show service detail |
74
- | `gheima services create --name <name> [--type WEB\|WORKER\|STATIC] [--repo <url>] [--project <id>]` | Create a service. Names are unique per **account**; omitting `--project` leaves the service ungrouped |
75
- | `gheima services delete <service> [-y]` | Delete a service |
76
- | `gheima link <service>` | Link the current directory to a service: commands run anywhere inside it then default to that service. Writes `.gheima/project.json` and adds `.gheima/` to `.gitignore` |
77
- | `gheima deploy [service] [--no-wait] [--timeout <min>]` | Deploy, stream the build, and exit 0 once it is live, or 8 if it fails. `--no-wait` only queues it |
78
- | `gheima logs [service] [-f] [-b] [-s <text>]` | Show or tail runtime (`-b` → build) logs |
79
- | `gheima templates [list]` | List marketplace templates |
80
- | `gheima templates deploy <templateId> <name> [--project <id>]` | Deploy a one-click template |
78
+ | Command | Description |
79
+ | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
80
+ | `gheima services [list]` | List services |
81
+ | `gheima services get <service>` | Show service detail |
82
+ | `gheima services create --name <name> [--type WEB\|WORKER\|STATIC] [--repo <url>] [--project <id>]` | Create a service. Names are unique per **account**; omitting `--project` leaves the service ungrouped |
83
+ | `gheima services delete <service> [-y]` | Delete a service |
84
+ | `gheima link <service>` | Link the current directory to a service: commands run anywhere inside it then default to that service. Writes `.gheima/project.json` and adds `.gheima/` to `.gitignore` |
85
+ | `gheima deploy [service] [--no-wait] [--timeout <min>]` | Deploy, stream the build, and exit 0 once it is live, or 8 if it fails. `--no-wait` only queues it |
86
+ | `gheima logs [service] [-f] [-b] [-s <text>]` | Show or tail runtime (`-b` → build) logs |
87
+ | `gheima run <service> [--timeout <s>] [--no-wait] -- <cmd>` | Run a one-off command (a migration, a seed) in a fresh container from the service's live image and environment, print its log, and exit with its exit code. The words after `--` are joined and run by the remote `/bin/sh -c`, so quote the whole command when an argument holds spaces: `gheima run web -- 'psql -c "select 1"'`. Admins only; 10 runs an hour per service |
88
+ | `gheima templates [list]` | List marketplace templates |
89
+ | `gheima templates deploy <templateId> <name> [--project <id>]` | Deploy a one-click template |
81
90
 
82
91
  ### Configuration
83
92
 
@@ -182,17 +191,18 @@ current one). The URL follows the same order: `--url` → `GHEIMA_URL` → profi
182
191
 
183
192
  Stable: a code never changes meaning.
184
193
 
185
- | Code | Meaning |
186
- | ---- | -------------------------------------------------------------------------------------------- |
187
- | 0 | Success |
188
- | 1 | Any other error (including a 5xx from the API) |
189
- | 2 | Usage: unknown flag, missing argument, or a prompt with no terminal (pass the flag it names) |
190
- | 3 | Not authenticated, or not allowed (401 / 403) |
191
- | 4 | Not found (404) |
192
- | 5 | Conflict or validation (400 / 409 / 412 / 422 / 428) |
193
- | 6 | Rate limited (429) |
194
- | 7 | Network failure or timeout (no response, 408, 504; also `deploy --timeout`) |
195
- | 8 | `gheima deploy` waited and the deployment did not go live (failed, cancelled, skipped) |
194
+ | Code | Meaning |
195
+ | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
196
+ | 0 | Success |
197
+ | 1 | Any other error (including a 5xx from the API) |
198
+ | 2 | Usage: unknown flag, missing argument, or a prompt with no terminal (pass the flag it names) |
199
+ | 3 | Not authenticated, or not allowed (401 / 403) |
200
+ | 4 | Not found (404) |
201
+ | 5 | Conflict or validation (400 / 409 / 412 / 422 / 428) |
202
+ | 6 | Rate limited (429) |
203
+ | 7 | Network failure or timeout (no response, 408, 504; also `deploy --timeout`) |
204
+ | 8 | `gheima deploy` waited and the deployment did not go live (failed, cancelled, skipped) |
205
+ | 9 | `gheima run` ended without the command reporting an exit code (refused, timed out). Otherwise `run` exits with the command's own code, which can be any of these numbers: a command that exits 6 is not a rate limit, so after `run` branch on the command's codes, not this table |
196
206
 
197
207
  ## Examples
198
208
 
@@ -201,6 +211,8 @@ gheima services --json | jq '.[].url'
201
211
  gheima api services.delete '{"id":"svc_123"}' --yes # no terminal: destructive needs --yes
202
212
  gheima logs my-app -f --json | jq -r .line # NDJSON, one entry per line
203
213
  gheima link my-app && gheima deploy # later, just: gheima deploy
214
+ gheima run my-app -- npx prisma migrate deploy # exits with the migration's own code
215
+ gheima run my-app -- 'psql -c "select count(*) from users"' # quote it whole: the remote shell splits it
204
216
  gheima logs my-app -f
205
217
  gheima env set my-app DATABASE_URL=postgres://…
206
218
  gheima env set my-app STRIPE_SECRET --stdin < secret.txt # keeps the value out of shell history
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * `gheima agents`: the section of AGENTS.md that tells a coding agent how this project ships on
5
+ * Gheima. Agents read AGENTS.md at the repository root before they act, so a few lines there
6
+ * save each one rediscovering the CLI, its exit codes and where the docs are.
7
+ *
8
+ * The section sits between markers, so writing it again replaces it rather than stacking
9
+ * copies, and everything outside the markers is the repository's own and left untouched.
10
+ */
11
+ export const AGENTS_FILE = 'AGENTS.md';
12
+ const START = '<!-- gheima:start -->';
13
+ const END = '<!-- gheima:end -->';
14
+ export function agentsSection(serviceName) {
15
+ const svc = serviceName ?? '<service>';
16
+ return [
17
+ START,
18
+ '## Deploying (Gheima)',
19
+ '',
20
+ `This project deploys to the Gheima service \`${svc}\`. Gheima builds it from the pushed`,
21
+ 'branch of this repository; uncommitted or unpushed changes are not deployed.',
22
+ '',
23
+ '- Deploy and wait for the outcome: `npx @gheima/cli deploy --json` (exit 0 = live, 8 = the',
24
+ ' deployment did not go live).',
25
+ '- Read logs: `npx @gheima/cli logs --json`. Status: `npx @gheima/cli services get ' +
26
+ `${svc} --json\`.`,
27
+ '- Auth comes from `gheima login` or `GHEIMA_API_KEY`. Never print or commit the key.',
28
+ '- Configuration is environment variables on the service, never committed `.env` files.',
29
+ '- Exit codes: 2 usage, 3 auth, 4 not found, 5 conflict or validation, 6 rate limited,',
30
+ ' 7 network. Destructive commands need `--yes`: ask before passing it.',
31
+ '- Docs for agents: https://gheima.ma/llms.txt (append `.md` to any docs URL). MCP server:',
32
+ ' https://gheima.ma/mcp.',
33
+ END,
34
+ ].join('\n');
35
+ }
36
+ /**
37
+ * Put the section into `dir/AGENTS.md`: replace an existing one in place, or append it.
38
+ * Returns what happened, for the command to report.
39
+ */
40
+ export function upsertAgentsMd(dir, section) {
41
+ const path = join(dir, AGENTS_FILE);
42
+ if (!existsSync(path)) {
43
+ writeFileSync(path, `# AGENTS.md\n\n${section}\n`);
44
+ return 'created';
45
+ }
46
+ const current = readFileSync(path, 'utf8');
47
+ const start = current.indexOf(START);
48
+ const end = current.indexOf(END, start);
49
+ if (start !== -1 && end !== -1) {
50
+ writeFileSync(path, current.slice(0, start) + section + current.slice(end + END.length));
51
+ return 'updated';
52
+ }
53
+ const sep = current.endsWith('\n\n') ? '' : current.endsWith('\n') ? '\n' : '\n\n';
54
+ writeFileSync(path, `${current}${sep}${section}\n`);
55
+ return 'appended';
56
+ }
package/dist/cli.js CHANGED
@@ -16,6 +16,7 @@ import { table, printJson, printJsonLine, spinner, success, info, color, isInter
16
16
  import { completionScript } from './completion.js';
17
17
  import { callOp, registerGenerated } from './generated.js';
18
18
  import { findLink, toDotenv, writeLink } from './link.js';
19
+ import { AGENTS_FILE, agentsSection, upsertAgentsMd } from './agents-md.js';
19
20
  import { defaultClientName, openBrowser, pollForApproval, startDeviceLogin, } from './device-login.js';
20
21
  const program = new Command();
21
22
  program
@@ -972,6 +973,34 @@ program
972
973
  fail(err);
973
974
  }
974
975
  });
976
+ program
977
+ .command('agents')
978
+ .description(`Print the Gheima section for ${AGENTS_FILE}, so coding agents know how this project deploys`)
979
+ .option('--write', `add it to ${AGENTS_FILE} (replacing an earlier copy) instead of printing it`)
980
+ .action((opts, cmd) => {
981
+ const g = globals(cmd);
982
+ try {
983
+ // Offline on purpose: the link already names the service, and no key is needed to write
984
+ // a file. Unlinked, the section carries a placeholder to fill in.
985
+ const found = findLink();
986
+ const section = agentsSection(found?.link.serviceName);
987
+ if (!opts.write) {
988
+ if (g.json)
989
+ return printJson({ section });
990
+ return void process.stdout.write(section + '\n');
991
+ }
992
+ const dir = found?.dir ?? process.cwd();
993
+ const outcome = upsertAgentsMd(dir, section);
994
+ if (g.json)
995
+ return printJson({ file: `${dir}/${AGENTS_FILE}`, outcome });
996
+ success(`${outcome[0].toUpperCase()}${outcome.slice(1)} the Gheima section in ${dir}/${AGENTS_FILE}`);
997
+ if (!found)
998
+ info('No linked service here: run `gheima link <service>`, then run this again.');
999
+ }
1000
+ catch (err) {
1001
+ fail(err);
1002
+ }
1003
+ });
975
1004
  program
976
1005
  .command('deploy [service]')
977
1006
  .description('Deploy, stream the build, and exit with the outcome (the linked service by default)')
@@ -1054,8 +1083,82 @@ async function waitForDeployment(client, serviceId, deploymentId, timeoutMs) {
1054
1083
  stop.abort();
1055
1084
  }
1056
1085
  }
1057
- /** How often `deploy` asks for the outcome. Tests shorten it. */
1086
+ /** How often `deploy` and `run` ask for the outcome. Tests shorten it. */
1058
1087
  const POLL_MS = Number(process.env.GHEIMA_DEPLOY_POLL_MS) || 3000;
1088
+ /** Statuses a one-off run never leaves (the `CronStatus` values its row reuses). */
1089
+ const RUN_FINISHED = new Set(['SUCCESS', 'FAILED', 'SKIPPED']);
1090
+ /** How long `run` waits beyond the command's own timeout, for the run to leave the queue. */
1091
+ const RUN_QUEUE_SLACK_MS = 10 * 60_000;
1092
+ program
1093
+ .command('run <service> <command...>')
1094
+ .description("Run a one-off command against the service's live image and environment, print its log, " +
1095
+ 'and exit with its exit code. Put the command after `--`. The words are joined and run by the ' +
1096
+ 'remote /bin/sh -c, so quote the whole command when an argument holds spaces')
1097
+ .option('--timeout <seconds>', 'stop the command after this long (1-3600)', '300')
1098
+ .option('--no-wait', 'queue the run and exit without waiting for it')
1099
+ .action(async (ref, words, opts, cmd) => {
1100
+ const g = globals(cmd);
1101
+ try {
1102
+ const timeout = Number(opts.timeout);
1103
+ // Checked before anything is queued: the API would refuse it, but only after a lookup.
1104
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 3600) {
1105
+ throw new UsageError(`--timeout must be a whole number of seconds from 1 to 3600, not ${opts.timeout}.`);
1106
+ }
1107
+ const client = makeClient(g);
1108
+ const id = await resolveServiceId(client, ref);
1109
+ // Joined as typed, like `heroku run`: the remote shell does the word splitting, so
1110
+ // `gheima run web -- 'npm run migrate && npm run seed'` means what it says.
1111
+ const { run } = (await callOp('services.createRun', { id, command: words.join(' '), timeoutSeconds: timeout }, g));
1112
+ if (!opts.wait) {
1113
+ if (g.json)
1114
+ return printJson(run);
1115
+ return success(`Run queued: ${color.bold(run.id)}`);
1116
+ }
1117
+ info(`Run ${run.id} queued. Waiting for it to finish…`);
1118
+ const final = await waitForRun(id, run.id, timeout * 1000 + RUN_QUEUE_SLACK_MS, g);
1119
+ // Written only once the run has finished, so the log comes in one piece at the end.
1120
+ const { logs } = (await callOp('services.runLogs', { id, runId: run.id }, g));
1121
+ if (g.json)
1122
+ printJson({ run: final, logs });
1123
+ else if (logs)
1124
+ writeRaw(logs.endsWith('\n') ? logs : `${logs}\n`);
1125
+ // exitCode, not exit(): a long log on a pipe must drain before the process ends.
1126
+ if (final.exitCode !== null) {
1127
+ if (!g.json && final.exitCode !== 0) {
1128
+ process.stderr.write(`${color.red('Run')} ${run.id} exited ${final.exitCode}\n`);
1129
+ }
1130
+ process.exitCode = final.exitCode;
1131
+ return;
1132
+ }
1133
+ process.stderr.write(`${color.red('Run')} ${run.id} ended ${final.status}` +
1134
+ `${final.error ? `: ${final.error}` : ''}\n`);
1135
+ process.exitCode = EXIT.runFailed;
1136
+ }
1137
+ catch (err) {
1138
+ fail(err);
1139
+ }
1140
+ });
1141
+ /** Poll a one-off run until it finishes, saying so on stderr when it starts. */
1142
+ async function waitForRun(serviceId, runId, timeoutMs, g) {
1143
+ const deadline = Date.now() + timeoutMs;
1144
+ let started = false;
1145
+ while (Date.now() < deadline) {
1146
+ const { run } = (await callOp('services.getRun', { id: serviceId, runId }, g));
1147
+ if (RUN_FINISHED.has(run.status))
1148
+ return run;
1149
+ if (!started && run.status === 'RUNNING') {
1150
+ started = true;
1151
+ info('Running…');
1152
+ }
1153
+ await new Promise((r) => setTimeout(r, POLL_MS));
1154
+ }
1155
+ throw new GheimaError({
1156
+ status: 0,
1157
+ code: 'timeout',
1158
+ message: `Run ${runId} had not finished after ${Math.round(timeoutMs / 60_000)} minutes. ` +
1159
+ `Read it later with \`gheima services get-run ${serviceId} ${runId}\`.`,
1160
+ });
1161
+ }
1059
1162
  program
1060
1163
  .command('logs [service]')
1061
1164
  .description('Show or tail service logs (the linked service by default)')
@@ -1552,14 +1655,19 @@ program
1552
1655
  ? `${base}/services/${linked.link.serviceId}`
1553
1656
  : base;
1554
1657
  if (opts.live) {
1658
+ let live = null;
1555
1659
  try {
1556
1660
  const client = makeClient(g);
1557
1661
  const service = await client.services.get(await resolveServiceId(client, resource));
1558
- url = service.url;
1662
+ live = service.url;
1559
1663
  }
1560
1664
  catch (err) {
1561
1665
  fail(err);
1562
1666
  }
1667
+ // A service with no route yet (never deployed, or a worker) has no live URL.
1668
+ if (!live)
1669
+ fail(new Error('This service has no live URL yet'));
1670
+ url = live;
1563
1671
  }
1564
1672
  if (g.json)
1565
1673
  return printJson({ url });
package/dist/exit.js CHANGED
@@ -14,6 +14,8 @@ export const EXIT = {
14
14
  network: 7,
15
15
  /** `gheima deploy` waited, and the deployment did not go live. */
16
16
  deployFailed: 8,
17
+ /** `gheima run` ended without the command reporting an exit code (refused, timed out). */
18
+ runFailed: 9,
17
19
  };
18
20
  /** The command was invoked wrongly: a missing flag, or a prompt with nobody to answer it. */
19
21
  export class UsageError extends Error {
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // GENERATED by scripts/write-version.mjs from package.json. Do not edit.
2
- export const VERSION = '0.6.0';
2
+ export const VERSION = '0.8.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gheima/cli",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Command-line interface for the Gheima platform.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -35,8 +35,8 @@
35
35
  "commander": "^12.1.0",
36
36
  "undici": "^7.29.0",
37
37
  "zod": "^4.4.3",
38
- "@gheima/contracts": "0.2.0",
39
- "@gheima/sdk": "0.3.0"
38
+ "@gheima/contracts": "0.2.1",
39
+ "@gheima/sdk": "0.5.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@arethetypeswrong/cli": "^0.18.5",