anhedral 0.22.0 → 0.23.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.
Files changed (92) hide show
  1. package/README.md +37 -51
  2. package/assets/contracts/deployment-provenance.json +4 -4
  3. package/assets/contracts/environment-provenance.json +2 -2
  4. package/dist/cli-commands.js +5 -17
  5. package/dist/cli-errors.js +1 -1
  6. package/dist/cli-output.js +1 -1
  7. package/dist/command-schema.d.ts +1 -0
  8. package/dist/command-schema.js +19 -1
  9. package/dist/completion.js +1 -1
  10. package/dist/{capability-catalog.d.ts → composition/catalog.d.ts} +2 -2
  11. package/dist/{capability-catalog.js → composition/catalog.js} +2 -2
  12. package/dist/{capability-command.d.ts → composition/command.d.ts} +3 -3
  13. package/dist/{capability-command.js → composition/command.js} +29 -22
  14. package/dist/{composition.d.ts → composition/composition.d.ts} +1 -1
  15. package/dist/{composition.js → composition/composition.js} +2 -2
  16. package/dist/{capability-editor.js → composition/editor.js} +1 -1
  17. package/dist/{capability-recipes.d.ts → composition/recipes.d.ts} +2 -2
  18. package/dist/{capability-recipes.js → composition/recipes.js} +7 -7
  19. package/dist/{capability-references.js → composition/references.js} +2 -2
  20. package/dist/{stack-update.d.ts → composition/update.d.ts} +3 -3
  21. package/dist/{stack-update.js → composition/update.js} +11 -11
  22. package/dist/contracts/cli-transport.d.ts +1 -1
  23. package/dist/contracts/deployment.d.ts +4 -65
  24. package/dist/contracts/deployment.js +0 -29
  25. package/dist/contracts/environment-file.d.ts +3 -0
  26. package/dist/contracts/environment-file.js +8 -5
  27. package/dist/contracts/production-transport.d.ts +2 -2
  28. package/dist/contracts/staging-transport.d.ts +2 -2
  29. package/dist/dependencies.d.ts +1 -1
  30. package/dist/dependencies.js +1 -1
  31. package/dist/launch.js +8 -8
  32. package/dist/platform/auth.d.ts +14 -0
  33. package/dist/platform/auth.js +62 -0
  34. package/dist/{platform-command.d.ts → platform/command.d.ts} +2 -2
  35. package/dist/platform/command.js +279 -0
  36. package/dist/{credential-helper.js → platform/credential-helper.js} +1 -1
  37. package/dist/platform/deploy.d.ts +2 -0
  38. package/dist/platform/deploy.js +158 -0
  39. package/dist/{platform-environment.d.ts → platform/environment.d.ts} +1 -1
  40. package/dist/{platform-environment.js → platform/environment.js} +12 -12
  41. package/dist/platform/http.d.ts +7 -0
  42. package/dist/platform/http.js +105 -0
  43. package/dist/{platform-operations.d.ts → platform/operations.d.ts} +1 -1
  44. package/dist/{platform-operations.js → platform/operations.js} +5 -5
  45. package/dist/platform/output.d.ts +2 -0
  46. package/dist/platform/output.js +79 -0
  47. package/dist/{platform-production.d.ts → platform/production.d.ts} +1 -1
  48. package/dist/{platform-production.js → platform/production.js} +4 -4
  49. package/dist/platform/projects.d.ts +12 -0
  50. package/dist/platform/projects.js +125 -0
  51. package/dist/{platform-source.js → platform/source.js} +7 -7
  52. package/dist/platform/state-schema.d.ts +25 -0
  53. package/dist/platform/state-schema.js +11 -0
  54. package/dist/{platform-state.d.ts → platform/state.d.ts} +1 -1
  55. package/dist/{platform-state.js → platform/state.js} +3 -4
  56. package/dist/platform/types.d.ts +26 -0
  57. package/dist/platform/upload.d.ts +2 -0
  58. package/dist/platform/upload.js +60 -0
  59. package/dist/process/runner.d.ts +1 -0
  60. package/dist/{command-runner.js → process/runner.js} +1 -1
  61. package/dist/registry/usage.d.ts +1 -0
  62. package/dist/{platforms → scaffold}/tanstack.d.ts +2 -2
  63. package/dist/{platforms → scaffold}/tanstack.js +2 -2
  64. package/dist/transactions/durable-files.d.ts +8 -0
  65. package/dist/transactions/durable-files.js +132 -0
  66. package/dist/transactions/journal.d.ts +4 -0
  67. package/dist/transactions/journal.js +141 -0
  68. package/dist/{transaction-lock.js → transactions/lock.js} +2 -2
  69. package/dist/transactions/model.d.ts +18 -0
  70. package/dist/transactions/model.js +4 -0
  71. package/dist/transactions/paths.d.ts +12 -0
  72. package/dist/transactions/paths.js +155 -0
  73. package/dist/transactions/recovery.d.ts +7 -0
  74. package/dist/transactions/recovery.js +132 -0
  75. package/dist/{transaction.d.ts → transactions/transaction.d.ts} +1 -2
  76. package/dist/transactions/transaction.js +179 -0
  77. package/dist/util.js +2 -2
  78. package/dist/version.d.ts +1 -1
  79. package/dist/version.js +1 -1
  80. package/docs/capabilities.md +8 -6
  81. package/docs/software-factory.md +36 -6
  82. package/package.json +22 -22
  83. package/dist/platform-command.js +0 -787
  84. package/dist/transaction.js +0 -716
  85. /package/dist/{capability-editor.d.ts → composition/editor.d.ts} +0 -0
  86. /package/dist/{capability-references.d.ts → composition/references.d.ts} +0 -0
  87. /package/dist/{credential-helper.d.ts → platform/credential-helper.d.ts} +0 -0
  88. /package/dist/{platform-source.d.ts → platform/source.d.ts} +0 -0
  89. /package/dist/{command-runner.d.ts → platform/types.js} +0 -0
  90. /package/dist/{command.d.ts → process/resolve-command.d.ts} +0 -0
  91. /package/dist/{command.js → process/resolve-command.js} +0 -0
  92. /package/dist/{transaction-lock.d.ts → transactions/lock.d.ts} +0 -0
@@ -1,787 +0,0 @@
1
- import { runProductionCommand, validateProductionArguments } from './platform-production.js';
2
- import { runEnvironmentCommand, validateEnvironmentArguments } from './platform-environment.js';
3
- import { runStagingCommand, runLogsCommand, validateStagingArguments, validateLogsArguments, } from './platform-operations.js';
4
- import { constants } from 'node:fs';
5
- import { createHash, randomUUID } from 'node:crypto';
6
- import { join, resolve } from 'node:path';
7
- import { unlink } from 'node:fs/promises';
8
- import { z } from 'zod';
9
- import { CliArgumentError, commandArguments, commandArgumentError } from './cli-arguments.js';
10
- import { CliFailure } from './cli-errors.js';
11
- import { stripVTControlCharacters } from 'node:util';
12
- import { createReporter } from './cli-output.js';
13
- import { canonicalCliJson, cliProjectListQuerySchema, cliProjectCreateInputSchema, cliProjectListSchema, cliProjectCreateReceiptSchema, cliPlanInputSchema, cliPlanSchema, cliPreparationSchema, cliDeviceSchema, cliLinkSchema, cliLoginSchema, SOURCE_LIMITS, sourceUploadInputSchema, sourceUploadReceiptSchema, } from './contracts/cli-transport.js';
14
- import { readSourceBounded } from './contracts/source-bundle.js';
15
- import { deploymentManifestSchema } from './contracts/deployment.js';
16
- import { packageSource } from './platform-source.js';
17
- import { platformFailure as createPlatformFailure, platformOrigin, readPrivate, secretStore, writePrivate, withProjectLock, } from './platform-state.js';
18
- const credential = cliLoginSchema.extend({ origin: z.string() });
19
- const pending = z
20
- .object({ origin: z.string(), device: cliDeviceSchema, expiresAt: z.number() })
21
- .strict();
22
- const linkSchema = cliLinkSchema.extend({ origin: z.string() }).strict();
23
- const projectCreateState = z
24
- .object({
25
- origin: z.string(),
26
- principalId: z.uuid(),
27
- teamId: z.uuid(),
28
- input: cliProjectCreateInputSchema,
29
- receipt: cliProjectCreateReceiptSchema.optional(),
30
- })
31
- .strict();
32
- const uploadState = z
33
- .object({
34
- origin: z.string(),
35
- principalId: z.uuid(),
36
- input: sourceUploadInputSchema,
37
- uploadId: z.uuid().optional(),
38
- })
39
- .strict();
40
- const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
41
- function visible(value) {
42
- return stripVTControlCharacters(String(value ?? '')).replace(/[\x00-\x1f\x7f]/g, ' ');
43
- }
44
- function formatPlatformResult(command, result) {
45
- const data = result;
46
- if (data.status === 'authorization_required')
47
- return `Approve CLI access at ${visible(data.verificationUrl)}\nConfirm code ${visible(data.userCode)}.\nNext: ${visible(data.nextAction)}`;
48
- if (data.status === 'authenticated')
49
- return `Signed in to ${visible(data.origin)}.\nExpires: ${visible(data.expiresAt)}.`;
50
- if (data.status === 'logged_out')
51
- return `Logged out of ${visible(data.origin)}.`;
52
- if (data.status === 'unlinked')
53
- return 'Removed the local project link.';
54
- if (command === 'whoami') {
55
- const context = data.context;
56
- return [
57
- `Signed in as ${visible(data.name)} (${visible(data.principalId)}).`,
58
- `API origin: ${visible(data.origin)}.`,
59
- `Expires: ${visible(data.expiresAt)}.`,
60
- ...(context
61
- ? [
62
- `Credential store: ${visible(context.credential?.kind)}.`,
63
- context.project
64
- ? `Saved local project: ${visible(context.project.name)} (${visible(context.project.projectId)}), team ${visible(context.project.teamId)}. Project access has not been verified.`
65
- : 'No local project link is saved.',
66
- ]
67
- : []),
68
- ].join('\n');
69
- }
70
- if (command === 'projects') {
71
- if (data.status === 'dry_run')
72
- return `Project creation preview: ${visible(data.name)}.\nNo project, source or deployment was created.`;
73
- if (Array.isArray(data.projects)) {
74
- const projects = data.projects;
75
- const teams = data.availableTeams;
76
- return [
77
- data.team
78
- ? `Team: ${visible(data.team.name)} (${visible(data.team.id)}).`
79
- : 'No team is selected.',
80
- ...projects.map((project) => `${visible(project.name)} (${visible(project.projectId)})${project.canLink ? '' : ' [cannot link]'}`),
81
- ...(projects.length ? [] : ['No projects found.']),
82
- 'Available teams:',
83
- ...teams.map((team) => `${visible(team.name)} (${visible(team.id)})`),
84
- ...(data.teamsTruncated
85
- ? ['Team list is truncated. Use a known team ID with --team.']
86
- : []),
87
- ...(data.nextCursor
88
- ? [
89
- `Next: anhedral projects list --cursor ${visible(data.nextCursor)}${data.team ? ` --team ${visible(data.team.id)}` : ''} (with the same API origin and credential store).`,
90
- ]
91
- : []),
92
- ].join('\n');
93
- }
94
- return `Created project ${visible(data.name)} (${visible(data.projectId)}).\nTeam: ${visible(data.teamId)}.${data.linked ? '\nSaved verified local project link.' : ''}\n${data.linked ? 'Next: anhedral source upload --dry-run' : `Next: anhedral link --project ${visible(data.projectId)} --team ${visible(data.teamId)}`} (with the same API origin and credential store).\nNo source was generated or deployment started.`;
95
- }
96
- if (command === 'link')
97
- return `Linked to ${visible(data.name)} (${visible(data.projectId)}).\nTeam: ${visible(data.teamId)}.`;
98
- if (data.status === 'dry_run')
99
- return `Source archive preview: ${visible(data.files)} files, ${visible(data.bytes)} source bytes, ${visible(data.archiveBytes)} archive bytes.\nNo source was uploaded. Review the included paths with --json.`;
100
- if (command === 'source')
101
- return `Source ${visible(data.state)} (${visible(data.id)}).\nSource revision: ${visible(data.sourceRevision ?? 'not sealed')}.\nUpload does not activate a runtime or deployment.`;
102
- if (command === 'deploy')
103
- return [
104
- data.state
105
- ? `Candidate ${visible(data.state)} (${visible(data.candidateId)}).`
106
- : `Deployment plan prepared (${visible(data.id)}).`,
107
- `Source revision: ${visible(data.sourceRevision)}.`,
108
- ...(data.admission?.diagnostics ?? []).flatMap((item) => [
109
- `[${visible(item.code)}] ${visible(item.message)}`,
110
- `Next: ${visible(item.action)}`,
111
- ]),
112
- ...(data.admission && data.blockers?.length === 0
113
- ? ['Source is eligible for candidate preparation. Run anhedral deploy prepare.']
114
- : []),
115
- 'No preview or deployment was activated.',
116
- ].join('\n');
117
- return 'Platform command completed.';
118
- }
119
- export async function runPlatformCommand(command, args, output, dependencies = {}) {
120
- try {
121
- await runPlatformOperation(command, args, output, dependencies);
122
- }
123
- catch (error) {
124
- if (error instanceof CliArgumentError || error instanceof CliFailure)
125
- throw error;
126
- if (error instanceof z.ZodError)
127
- throw createPlatformFailure('Platform data or saved context does not match the supported protocol. Preserve saved state and verify the selected context before retrying.', `Run anhedral ${command} --help.`, 'context');
128
- if (error instanceof SyntaxError)
129
- throw createPlatformFailure('Selected local Platform input is not valid JSON. Preserve saved state and review the selected input before retrying.', `Run anhedral ${command} --help.`, 'context');
130
- if (['ENOENT', 'ENOTDIR', 'EISDIR', 'EACCES', 'EPERM'].includes(error?.code ?? ''))
131
- throw createPlatformFailure('A required local Platform file is missing or inaccessible. Review the selected working directory, manifest and credential store.', `Run anhedral ${command} --help.`, 'context');
132
- throw error;
133
- }
134
- }
135
- async function runPlatformOperation(command, args, output, dependencies) {
136
- const reporter = createReporter(output, (result) => formatPlatformResult(command, result), true);
137
- const platformFailure = (message, category = 'context', retryable = false, nextAction = `Run anhedral ${command} --help.`) => createPlatformFailure(message, nextAction, category, retryable);
138
- const options = commandArguments(command, args), origin = platformOrigin(options.value('--api-url'));
139
- if (command === 'env')
140
- validateEnvironmentArguments(args);
141
- if (command === 'staging')
142
- validateStagingArguments(args);
143
- if (command === 'production')
144
- validateProductionArguments(args);
145
- if (command === 'logs')
146
- validateLogsArguments(args);
147
- const emit = (result) => reporter.result(result);
148
- if (['login', 'logout', 'whoami', 'link', 'unlink'].includes(command) &&
149
- options.positional.length)
150
- throw commandArgumentError(command, 'Unexpected positional arguments.');
151
- if (command === 'login' && options.has('--start') && options.has('--resume'))
152
- throw commandArgumentError(command, 'Choose --start or --resume.');
153
- if (command === 'source' &&
154
- (options.positional.length !== 1 || !['upload', 'status'].includes(options.positional[0])))
155
- throw commandArgumentError(command, 'Use source upload or source status.');
156
- if (command === 'deploy' &&
157
- (options.positional.length !== 1 ||
158
- !['plan', 'prepare', 'status'].includes(options.positional[0])))
159
- throw commandArgumentError(command, 'Use deploy plan, deploy prepare or deploy status.');
160
- if (command === 'deploy' &&
161
- options.positional[0] !== 'plan' &&
162
- (options.has('--manifest') || options.has('--new')))
163
- throw commandArgumentError(command, 'Manifest and --new options apply to deploy plan only.');
164
- if (command === 'link' &&
165
- (!z.uuid().safeParse(options.value('--project')).success ||
166
- !z.uuid().safeParse(options.value('--team')).success))
167
- throw commandArgumentError(command, 'Supply existing project and team UUIDs with --project and --team.');
168
- let projectInput;
169
- if (command === 'projects') {
170
- const operation = options.positional[0];
171
- if (options.has('--team') && !z.uuid().safeParse(options.value('--team')).success)
172
- throw commandArgumentError(command, 'Supply a team UUID with --team.');
173
- if (operation === 'list') {
174
- if (['--name', '--summary', '--link', '--dry-run', '--new'].some((flag) => options.has(flag)))
175
- throw commandArgumentError(command, 'Creation options apply to projects create only.');
176
- const query = cliProjectListQuerySchema.safeParse({
177
- ...(options.has('--limit') ? { limit: options.value('--limit') } : {}),
178
- ...(options.has('--cursor') ? { cursor: options.value('--cursor') } : {}),
179
- });
180
- if (!query.success || (options.has('--limit') && !/^[0-9]+$/.test(options.value('--limit'))))
181
- throw commandArgumentError(command, 'Use --limit 1–100 and an optional cursor UUID.');
182
- }
183
- else {
184
- if (options.has('--limit') || options.has('--cursor'))
185
- throw commandArgumentError(command, 'Pagination options apply to projects list only.');
186
- const parsed = cliProjectCreateInputSchema.safeParse({
187
- protocol: 1,
188
- requestId: randomUUID(),
189
- name: options.value('--name'),
190
- summary: options.value('--summary') ?? '',
191
- });
192
- if (!parsed.success)
193
- throw commandArgumentError(command, 'Supply --name with 1–160 characters and an optional summary up to 2000 characters.');
194
- projectInput = { name: parsed.data.name, summary: parsed.data.summary };
195
- if (options.has('--dry-run')) {
196
- emit({
197
- status: 'dry_run',
198
- ...projectInput,
199
- teamId: options.value('--team') ?? null,
200
- link: options.has('--link'),
201
- initialization: 'source-upload',
202
- });
203
- return;
204
- }
205
- }
206
- }
207
- const root = process.cwd(), stateDir = join(root, '.anhedral', 'platform'), linkPath = join(stateDir, 'project.json'), uploadPath = join(stateDir, 'upload.json');
208
- if (command === 'unlink') {
209
- if ((await readPrivate(linkPath)) === null) {
210
- emit({ status: 'unlinked' });
211
- return;
212
- }
213
- await withProjectLock(stateDir, async () => {
214
- await readPrivate(linkPath);
215
- await unlink(linkPath).catch((e) => {
216
- if (e.code !== 'ENOENT')
217
- throw e;
218
- });
219
- });
220
- emit({ status: 'unlinked' });
221
- return;
222
- }
223
- if (command === 'env' && options.has('--dry-run'))
224
- return runEnvironmentCommand(args, output);
225
- if (command === 'source' && options.has('--dry-run')) {
226
- if (options.positional[0] !== 'upload')
227
- throw commandArgumentError(command, 'Use source upload --dry-run.');
228
- const source = await packageSource(root), archiveDigest = hash(source.archive);
229
- emit({
230
- status: 'dry_run',
231
- archiveDigest,
232
- inventoryDigest: source.inventoryDigest,
233
- files: source.files,
234
- includedPaths: source.paths,
235
- bytes: source.bytes,
236
- archiveBytes: source.archive.length,
237
- });
238
- return;
239
- }
240
- const store = dependencies.store ??
241
- secretStore(origin, options.value('--credential-file') ? resolve(options.value('--credential-file')) : undefined);
242
- const readCredential = async () => {
243
- try {
244
- return await store.read();
245
- }
246
- catch (error) {
247
- if (error instanceof SyntaxError)
248
- throw platformFailure('Saved credential data is not valid JSON. Preserve it and reconcile the selected credential store.', 'auth', false, 'Run anhedral login --help.');
249
- throw error;
250
- }
251
- };
252
- const request = async (path, method, body, token, team) => {
253
- let response;
254
- try {
255
- response = await (dependencies.fetch ?? fetch)(`${origin}/api/cli/v1${path}`, {
256
- method,
257
- redirect: 'error',
258
- signal: AbortSignal.timeout(30000),
259
- headers: {
260
- 'x-anhedral-cli-protocol': '1',
261
- ...(body instanceof Uint8Array
262
- ? { 'content-type': 'application/octet-stream' }
263
- : { 'content-type': 'application/json' }),
264
- ...(token ? { authorization: `Bearer ${token}` } : {}),
265
- ...(team ? { 'x-anhedral-team': team } : {}),
266
- },
267
- body: body === undefined
268
- ? undefined
269
- : body instanceof Uint8Array
270
- ? Uint8Array.from(body)
271
- : JSON.stringify(body),
272
- });
273
- }
274
- catch {
275
- throw platformFailure(command === 'projects' && options.positional[0] === 'create'
276
- ? 'Platform request was interrupted. Retry the saved project request without --new to resume.'
277
- : 'Platform request was interrupted. Retry the same command to resume.', 'network', true, command === 'projects' && options.positional[0] === 'create'
278
- ? 'Retry anhedral projects create with the same name, summary, team, API origin, credential store and working directory, omitting --new to reuse the saved request.'
279
- : `Retry anhedral ${command} with the same API origin, working directory and options to resume.`);
280
- }
281
- const data = await readSourceBounded(response.body, /\/projects\/[^/]+\/(environment|staging|production|runtime-logs)(\?|$)/.test(path)
282
- ? 1024 * 1024
283
- : command === 'projects'
284
- ? 1024 * 1024
285
- : 65536)
286
- .then((b) => JSON.parse(new TextDecoder().decode(b)))
287
- .catch(() => {
288
- throw platformFailure('Platform returned an invalid response.', 'network');
289
- });
290
- if (!response.ok) {
291
- if (path === '/auth/token') {
292
- const error = z
293
- .object({
294
- error: z.enum([
295
- 'authorization_pending',
296
- 'slow_down',
297
- 'access_denied',
298
- 'expired_token',
299
- 'invalid_grant',
300
- ]),
301
- })
302
- .safeParse(data);
303
- if (error.success)
304
- return error.data;
305
- }
306
- const serverMessage = z.object({ error: z.string().max(2000) }).safeParse(data);
307
- const admissionProblem = serverMessage.success &&
308
- /^\[(?:RUNTIME_UNAVAILABLE|ARTIFACT_MISMATCH|SOURCE_VERSION_MISMATCH|DEPENDENCY_LOCK_MISMATCH|INDEPENDENT_APPROVAL_REQUIRED|PRODUCTION_PERMISSION_REQUIRED)\] [^\r\n]{1,1500}$/.test(serverMessage.data.error)
309
- ? visible(serverMessage.data.error)
310
- : null;
311
- throw platformFailure(admissionProblem ??
312
- (response.status === 401
313
- ? 'CLI login expired or was revoked. Run anhedral login.'
314
- : response.status === 409
315
- ? command === 'deploy'
316
- ? 'Deployment plan is stale or inputs conflict. Review deploy plan --new.'
317
- : command === 'projects'
318
- ? 'Project creation conflicts with the saved request. Preserve retry state; use projects create --new only to create another project.'
319
- : command === 'staging'
320
- ? 'Candidate, configuration or staging generation changed. Review staging status before starting a new deployment.'
321
- : command === 'production'
322
- ? 'Candidate, production configuration, permissions or generation changed. Review production status before retrying.'
323
- : command === 'env'
324
- ? 'Environment versions or import contents conflict. Review env list and preserve saved retry state before starting a new import.'
325
- : 'Upload conflicts with saved source. Restore the original files or use source upload --new.'
326
- : response.status === 403
327
- ? command === 'projects'
328
- ? 'Current team project access or project creation permission is unavailable.'
329
- : command === 'env'
330
- ? 'Current project environment access or administrator permission is unavailable.'
331
- : command === 'logs'
332
- ? 'Current project log access is unavailable.'
333
- : command === 'production'
334
- ? 'Current production permission or team approval policy does not allow this deployment. Review production status and the team policy.'
335
- : 'Current project build access is unavailable.'
336
- : `Platform request failed (${response.status}).`), response.status === 401
337
- ? 'auth'
338
- : response.status === 403
339
- ? 'permission'
340
- : response.status === 409
341
- ? 'conflict'
342
- : 'network', response.status === 429 || response.status >= 500, response.status === 401
343
- ? 'Run anhedral login with the same API origin and credential store.'
344
- : response.status === 403 && command === 'production'
345
- ? 'Run anhedral production status and review current production permissions and the team approval policy in Platform.'
346
- : `Run anhedral ${command} --help.`);
347
- }
348
- return data;
349
- };
350
- if (command === 'login') {
351
- if (options.positional.length)
352
- throw commandArgumentError(command, 'Login does not accept positional arguments.');
353
- let state = pending.safeParse(await readCredential());
354
- if (!options.has('--resume') ||
355
- !state.success ||
356
- state.data.origin !== origin ||
357
- state.data.expiresAt <= Date.now()) {
358
- const device = cliDeviceSchema.parse(await request('/auth/code', 'POST', {}));
359
- if (new URL(device.verification_uri_complete).origin !== origin ||
360
- new URL(device.verification_uri_complete).protocol !== new URL(origin).protocol)
361
- throw platformFailure('Platform returned an unexpected verification origin.');
362
- const saved = { origin, device, expiresAt: Date.now() + device.expires_in * 1000 };
363
- await store.write(saved);
364
- state = pending.safeParse(saved);
365
- }
366
- if (!state.success)
367
- throw platformFailure('Login state is unavailable. Start login again.');
368
- const saved = state.data;
369
- if (options.has('--start') || (!reporter.canPrompt && !options.has('--resume'))) {
370
- emit({
371
- status: 'authorization_required',
372
- verificationUrl: saved.device.verification_uri_complete,
373
- userCode: saved.device.user_code,
374
- expiresAt: new Date(saved.expiresAt).toISOString(),
375
- nextAction: 'Approve in your browser, then run anhedral login --resume with the same API origin and credential store.',
376
- });
377
- return;
378
- }
379
- reporter.diagnostic(`Approve CLI access at ${saved.device.verification_uri_complete}\nConfirm code ${saved.device.user_code}.`);
380
- let interval = saved.device.interval * 1000;
381
- while (Date.now() < saved.expiresAt) {
382
- await (dependencies.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(interval);
383
- const result = await request('/auth/token', 'POST', {
384
- device_code: saved.device.device_code,
385
- });
386
- const grant = cliLoginSchema.safeParse(result);
387
- if (grant.success) {
388
- await store.write({ ...grant.data, origin });
389
- emit({ status: 'authenticated', origin, expiresAt: grant.data.expiresAt });
390
- return;
391
- }
392
- const error = result.error;
393
- if (error === 'slow_down')
394
- interval += 5000;
395
- else if (error !== 'authorization_pending') {
396
- await store.clear();
397
- throw platformFailure('Device approval was denied or expired. Start login again.');
398
- }
399
- }
400
- await store.clear();
401
- throw platformFailure('Device approval expired. Start login again.');
402
- }
403
- const saved = credential.safeParse(await readCredential());
404
- if (!saved.success || saved.data.origin !== origin)
405
- throw platformFailure('Log in to the selected API origin first.', 'auth', false, 'Run anhedral login with the same API origin and credential store.');
406
- const token = saved.data.token;
407
- if (command === 'logout') {
408
- await request('/auth/logout', 'POST', {}, token);
409
- try {
410
- await store.clear();
411
- }
412
- catch {
413
- throw platformFailure('Platform access was revoked, but the saved local credential could not be removed.', 'context', false, 'Remove the saved credential from the selected credential store before signing in again.');
414
- }
415
- emit({ status: 'logged_out', origin });
416
- return;
417
- }
418
- const actor = z
419
- .object({
420
- protocol: z.literal(1),
421
- principalId: z.uuid(),
422
- name: z.string(),
423
- teamId: z.uuid().nullable(),
424
- })
425
- .parse(await request('/actor', 'GET', undefined, token));
426
- if (command === 'whoami') {
427
- const identity = { ...actor, origin, expiresAt: saved.data.expiresAt };
428
- if (!options.has('--context')) {
429
- emit(identity);
430
- return;
431
- }
432
- const savedLink = await readPrivate(linkPath);
433
- const localLink = savedLink === null ? null : linkSchema.safeParse(savedLink);
434
- if (localLink &&
435
- (!localLink.success ||
436
- localLink.data.origin !== origin ||
437
- localLink.data.principalId !== actor.principalId))
438
- throw platformFailure('The saved project link does not match the selected API origin and signed-in identity. Preserve it and explicitly link the intended project.', 'context', false, 'Run anhedral link --help.');
439
- const file = options.value('--credential-file');
440
- emit({
441
- ...identity,
442
- context: {
443
- apiOrigin: { value: origin, source: options.has('--api-url') ? 'flag' : 'default' },
444
- identityVerification: 'live-platform',
445
- credential: {
446
- source: file ? 'flag' : dependencies.store ? 'injected' : 'os-secret-store',
447
- kind: file
448
- ? 'owner-only-file'
449
- : dependencies.store
450
- ? 'injected'
451
- : process.platform === 'darwin'
452
- ? 'macos-keychain'
453
- : process.platform === 'linux'
454
- ? 'linux-secret-service'
455
- : 'unsupported',
456
- },
457
- project: localLink && localLink.success
458
- ? {
459
- projectId: localLink.data.projectId,
460
- teamId: localLink.data.teamId,
461
- name: localLink.data.name,
462
- source: '.anhedral/platform/project.json',
463
- verification: 'saved-local-link',
464
- access: 'not-verified',
465
- }
466
- : null,
467
- },
468
- });
469
- return;
470
- }
471
- if (command === 'projects') {
472
- const selectedTeam = options.value('--team') ?? actor.teamId;
473
- if (options.positional[0] === 'list') {
474
- const query = cliProjectListQuerySchema.parse({
475
- ...(options.has('--limit') ? { limit: options.value('--limit') } : {}),
476
- ...(options.has('--cursor') ? { cursor: options.value('--cursor') } : {}),
477
- });
478
- const params = new URLSearchParams({ limit: String(query.limit) });
479
- if (query.cursor)
480
- params.set('cursor', query.cursor);
481
- const result = cliProjectListSchema.parse(await request(`/projects?${params}`, 'GET', undefined, token, selectedTeam ?? undefined));
482
- if (result.principalId !== actor.principalId ||
483
- (selectedTeam && result.team?.id !== selectedTeam) ||
484
- result.projects.some((project) => project.teamId !== result.team?.id))
485
- throw platformFailure('Project list identity differs.');
486
- emit(result);
487
- return;
488
- }
489
- if (!selectedTeam)
490
- throw platformFailure('No team is selected. Run anhedral projects list to discover available teams, then use --team <uuid>.');
491
- await withProjectLock(stateDir, async () => {
492
- const journalPath = join(stateDir, 'project-create.json');
493
- const previous = await readPrivate(journalPath);
494
- let state = previous === null ? null : projectCreateState.parse(previous);
495
- if (state &&
496
- !options.has('--new') &&
497
- (state.origin !== origin ||
498
- state.principalId !== actor.principalId ||
499
- state.teamId !== selectedTeam ||
500
- state.input.name !== projectInput.name ||
501
- state.input.summary !== projectInput.summary))
502
- throw platformFailure('Saved project creation belongs to different input or context. Restore the original options to retry, or explicitly use --new to create another project.');
503
- if (!state || options.has('--new'))
504
- state = {
505
- origin,
506
- principalId: actor.principalId,
507
- teamId: selectedTeam,
508
- input: cliProjectCreateInputSchema.parse({
509
- protocol: 1,
510
- requestId: randomUUID(),
511
- ...projectInput,
512
- }),
513
- };
514
- const checkLink = async () => {
515
- const value = await readPrivate(linkPath);
516
- if (value === null)
517
- return;
518
- const existing = linkSchema.parse(value);
519
- if (existing.origin !== origin ||
520
- existing.principalId !== actor.principalId ||
521
- existing.teamId !== selectedTeam ||
522
- existing.projectId !== state.input.requestId)
523
- throw platformFailure('A different local project link exists. Use another working directory or explicitly unlink before creating with --link.');
524
- };
525
- if (options.has('--link'))
526
- await checkLink();
527
- await writePrivate(journalPath, state);
528
- const receipt = cliProjectCreateReceiptSchema.parse(await request('/projects', 'POST', state.input, token, selectedTeam));
529
- if (receipt.requestId !== state.input.requestId ||
530
- receipt.projectId !== state.input.requestId ||
531
- receipt.principalId !== actor.principalId ||
532
- receipt.teamId !== selectedTeam ||
533
- receipt.name !== state.input.name ||
534
- receipt.summary !== state.input.summary)
535
- throw platformFailure('Project creation receipt identity or input differs. Preserve saved retry state.');
536
- state = { ...state, receipt };
537
- await writePrivate(journalPath, state);
538
- if (options.has('--link')) {
539
- await checkLink();
540
- const link = cliLinkSchema.parse(await request('/link', 'POST', { projectId: receipt.projectId, teamId: selectedTeam }, token, selectedTeam));
541
- if (link.principalId !== actor.principalId ||
542
- link.projectId !== receipt.projectId ||
543
- link.teamId !== selectedTeam)
544
- throw platformFailure('Project link identity differs.');
545
- await checkLink();
546
- await writePrivate(linkPath, { ...link, origin });
547
- }
548
- emit({ ...receipt, linked: options.has('--link') });
549
- });
550
- return;
551
- }
552
- if (command === 'link') {
553
- await withProjectLock(stateDir, async () => {
554
- const input = z
555
- .object({ projectId: z.uuid(), teamId: z.uuid() })
556
- .parse({ projectId: options.value('--project'), teamId: options.value('--team') });
557
- if (options.positional.length)
558
- throw commandArgumentError(command, 'Use --project and --team.');
559
- const link = cliLinkSchema.parse(await request('/link', 'POST', input, token, input.teamId));
560
- if (link.principalId !== actor.principalId ||
561
- link.projectId !== input.projectId ||
562
- link.teamId !== input.teamId)
563
- throw platformFailure('Project link identity differs.');
564
- await writePrivate(linkPath, { ...link, origin });
565
- emit({ ...link, origin });
566
- });
567
- return;
568
- }
569
- if (['env', 'staging', 'production', 'logs'].includes(command)) {
570
- const link = linkSchema.parse(await readPrivate(linkPath));
571
- if (link.origin !== origin || link.principalId !== actor.principalId)
572
- throw platformFailure('Link this project to the selected API origin and signed-in identity.');
573
- const operation = command === 'env'
574
- ? runEnvironmentCommand
575
- : command === 'staging'
576
- ? runStagingCommand
577
- : command === 'production'
578
- ? runProductionCommand
579
- : runLogsCommand;
580
- return operation(args, output, { origin, principalId: actor.principalId, projectId: link.projectId, teamId: link.teamId }, (path, method, body) => request(path, method, body, token, link.teamId));
581
- }
582
- if (!['source', 'deploy'].includes(command) ||
583
- options.positional.length !== 1 ||
584
- !(command === 'deploy' ? ['plan', 'prepare', 'status'] : ['upload', 'status']).includes(options.positional[0]))
585
- throw commandArgumentError(command, 'Use source upload/status or deploy plan/prepare/status.');
586
- const link = linkSchema.parse(await readPrivate(linkPath));
587
- if (link.origin !== origin || link.principalId !== actor.principalId)
588
- throw platformFailure('Link this project to the selected API origin and signed-in identity.');
589
- if (command === 'deploy') {
590
- const localPath = join(stateDir, 'deployment.json');
591
- const stateSchema = z
592
- .object({
593
- origin: z.string(),
594
- principalId: z.uuid(),
595
- projectId: z.uuid(),
596
- planInput: cliPlanInputSchema,
597
- plan: cliPlanSchema.optional(),
598
- prepareRequestId: z.uuid().optional(),
599
- candidateId: z.uuid().optional(),
600
- })
601
- .strict();
602
- const stored = stateSchema.safeParse(await readPrivate(localPath));
603
- const state = stored.success &&
604
- stored.data.origin === origin &&
605
- stored.data.principalId === actor.principalId &&
606
- stored.data.projectId === link.projectId
607
- ? stored.data
608
- : null;
609
- const persist = (v) => writePrivate(localPath, v);
610
- const checkedPlan = (plan, input) => {
611
- const { digest, ...unsigned } = plan;
612
- if (hash(new TextEncoder().encode(canonicalCliJson(unsigned))) !== digest ||
613
- plan.projectId !== link.projectId ||
614
- plan.uploadId !== input.uploadId ||
615
- plan.requestId !== input.requestId ||
616
- canonicalCliJson(plan.manifest) !== canonicalCliJson(input.manifest))
617
- throw platformFailure('Deployment plan identity or integrity differs.');
618
- return plan;
619
- };
620
- if (state?.plan)
621
- checkedPlan(state.plan, state.planInput);
622
- if (options.positional[0] === 'plan') {
623
- const upload = uploadState.parse(await readPrivate(uploadPath));
624
- if (upload.origin !== origin ||
625
- upload.principalId !== actor.principalId ||
626
- upload.input.projectId !== link.projectId ||
627
- !upload.uploadId)
628
- throw platformFailure('Choose a sealed upload for this linked identity.');
629
- const receipt = sourceUploadReceiptSchema.parse(await request(`/uploads/${upload.uploadId}`, 'GET', undefined, token, link.teamId));
630
- if (receipt.state !== 'sealed' ||
631
- receipt.sourceRevision !== upload.input.archiveDigest ||
632
- receipt.projectId !== link.projectId)
633
- throw platformFailure('The saved source upload is not sealed.');
634
- const file = options.value('--manifest');
635
- if (!file)
636
- throw commandArgumentError(command, 'Use deploy plan --manifest <file>.');
637
- const handle = await import('node:fs/promises').then((fs) => fs.open(resolve(file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
638
- let manifest;
639
- try {
640
- const info = await handle.stat();
641
- if (!info.isFile() || info.size > 32768)
642
- throw platformFailure('Deployment manifest exceeds its limit.');
643
- try {
644
- manifest = JSON.parse(await handle.readFile('utf8'));
645
- }
646
- catch {
647
- throw commandArgumentError(command, 'The deployment manifest is not valid JSON. Review it before retrying.');
648
- }
649
- }
650
- finally {
651
- await handle.close();
652
- }
653
- const checkedManifest = deploymentManifestSchema.safeParse(manifest);
654
- if (!checkedManifest.success)
655
- throw commandArgumentError(command, 'The deployment manifest must match its foundation, capabilities, identity and runtime profile. TanStack Start uses the anhedral-stack runtime profile.');
656
- const compared = cliPlanInputSchema.parse({
657
- protocol: 1,
658
- requestId: state && !options.has('--new') ? state.planInput.requestId : randomUUID(),
659
- uploadId: upload.uploadId,
660
- manifest: checkedManifest.data,
661
- });
662
- if (state &&
663
- !options.has('--new') &&
664
- canonicalCliJson(state.planInput) !== canonicalCliJson(compared))
665
- throw platformFailure('Plan inputs changed. Use deploy plan --new to create a new request.');
666
- const local = {
667
- origin,
668
- principalId: actor.principalId,
669
- projectId: link.projectId,
670
- planInput: compared,
671
- };
672
- // Persist before POST so lost plan responses can be recovered by the same request identity.
673
- await persist({
674
- ...local,
675
- ...(state?.prepareRequestId && !options.has('--new')
676
- ? { prepareRequestId: state.prepareRequestId, candidateId: state.candidateId }
677
- : {}),
678
- });
679
- const plan = cliPlanSchema.parse(await request('/plans', 'POST', compared, token, link.teamId));
680
- const { digest, ...unsigned } = plan;
681
- if (hash(new TextEncoder().encode(canonicalCliJson(unsigned))) !== digest ||
682
- plan.projectId !== link.projectId ||
683
- plan.uploadId !== compared.uploadId ||
684
- plan.requestId !== compared.requestId ||
685
- canonicalCliJson(plan.manifest) !== canonicalCliJson(compared.manifest) ||
686
- plan.sourceRevision !== receipt.sourceRevision)
687
- throw platformFailure('Deployment plan identity or integrity differs.');
688
- await persist({
689
- ...local,
690
- plan,
691
- ...(state?.prepareRequestId && !options.has('--new')
692
- ? { prepareRequestId: state.prepareRequestId, candidateId: state.candidateId }
693
- : {}),
694
- });
695
- emit(plan);
696
- return;
697
- }
698
- if (!state?.plan)
699
- throw platformFailure('Create a deployment plan for this linked identity first.');
700
- if (options.positional[0] === 'status') {
701
- if (state.candidateId) {
702
- const result = cliPreparationSchema.parse(await request(`/candidates/${state.candidateId}`, 'GET', undefined, token, link.teamId));
703
- if (result.planId !== state.plan.id ||
704
- result.planDigest !== state.plan.digest ||
705
- result.candidateId !== state.candidateId ||
706
- result.sourceRevision !== state.plan.sourceRevision)
707
- throw platformFailure('Candidate receipt identity differs.');
708
- emit(result);
709
- }
710
- else {
711
- const plan = checkedPlan(cliPlanSchema.parse(await request(`/plans/${state.plan.id}`, 'GET', undefined, token, link.teamId)), state.planInput);
712
- if (plan.digest !== state.plan.digest || plan.id !== state.plan.id)
713
- throw platformFailure('Plan receipt identity differs.');
714
- emit(plan);
715
- }
716
- return;
717
- }
718
- if (state.plan.admission && state.plan.blockers.length) {
719
- const issue = state.plan.admission.diagnostics[0];
720
- throw platformFailure(issue
721
- ? `[${issue.code}] ${visible(issue.message)}`
722
- : 'This source is not eligible for candidate preparation.', 'conflict', false, issue ? visible(issue.action) : 'Review anhedral deploy plan output before preparing.');
723
- }
724
- const requestId = state.prepareRequestId ?? randomUUID();
725
- await persist({ ...state, prepareRequestId: requestId });
726
- const prepared = cliPreparationSchema.parse(await request('/candidates', 'POST', { protocol: 1, requestId, planId: state.plan.id, planDigest: state.plan.digest }, token, link.teamId));
727
- if (prepared.planId !== state.plan.id ||
728
- prepared.planDigest !== state.plan.digest ||
729
- prepared.sourceRevision !== state.plan.sourceRevision)
730
- throw platformFailure('Candidate receipt identity differs.');
731
- await persist({ ...state, prepareRequestId: requestId, candidateId: prepared.candidateId });
732
- emit(prepared);
733
- return;
734
- }
735
- const state = uploadState.safeParse(await readPrivate(uploadPath));
736
- const checkedState = state.success &&
737
- state.data.origin === origin &&
738
- state.data.principalId === actor.principalId &&
739
- state.data.input.projectId === link.projectId &&
740
- state.data.input.teamId === link.teamId
741
- ? state.data
742
- : null;
743
- if (options.positional[0] === 'status') {
744
- if (!checkedState?.uploadId)
745
- throw platformFailure('No resumable upload is saved for this project.');
746
- emit(sourceUploadReceiptSchema.parse(await request(`/uploads/${checkedState.uploadId}`, 'GET', undefined, token, link.teamId)));
747
- return;
748
- }
749
- const source = await packageSource(root), archiveDigest = hash(source.archive);
750
- if (checkedState && checkedState.input.archiveDigest !== archiveDigest && !options.has('--new'))
751
- throw platformFailure('Source changed since the saved upload. Restore those files or explicitly use source upload --new.');
752
- const chunks = Array.from({ length: Math.ceil(source.archive.length / SOURCE_LIMITS.chunkBytes) }, (_, i) => source.archive.subarray(i * SOURCE_LIMITS.chunkBytes, (i + 1) * SOURCE_LIMITS.chunkBytes));
753
- const input = sourceUploadInputSchema.parse({
754
- protocol: 1,
755
- requestId: checkedState && !options.has('--new') ? checkedState.input.requestId : randomUUID(),
756
- projectId: link.projectId,
757
- teamId: link.teamId,
758
- archiveDigest,
759
- archiveBytes: source.archive.length,
760
- inventoryDigest: source.inventoryDigest,
761
- cliVersion: source.cliVersion,
762
- chunks: chunks.map(hash),
763
- });
764
- // Persist the request identity before the first network mutation, including lost responses.
765
- const local = { origin, principalId: actor.principalId, input };
766
- await writePrivate(uploadPath, local);
767
- const receipt = sourceUploadReceiptSchema.parse(await request('/uploads', 'POST', input, token, link.teamId));
768
- if (receipt.projectId !== link.projectId ||
769
- receipt.requestId !== input.requestId ||
770
- receipt.archiveDigest !== input.archiveDigest ||
771
- receipt.inventoryDigest !== input.inventoryDigest)
772
- throw platformFailure('Upload receipt identity differs.');
773
- await writePrivate(uploadPath, { ...local, uploadId: receipt.id });
774
- if (receipt.state === 'cancelled')
775
- throw platformFailure('Upload was cancelled. Start source upload --new.');
776
- if (receipt.state !== 'sealed') {
777
- for (let i = 0; i < chunks.length; i++)
778
- if (!receipt.received.includes(i))
779
- await request(`/uploads/${receipt.id}/chunks/${i}`, 'PUT', chunks[i], token, link.teamId);
780
- }
781
- const complete = sourceUploadReceiptSchema.parse(await request(`/uploads/${receipt.id}/complete`, 'POST', {}, token, link.teamId));
782
- if (complete.id !== receipt.id ||
783
- complete.sourceRevision !== archiveDigest ||
784
- complete.state !== 'sealed')
785
- throw platformFailure('Source completion was not sealed. Resume this upload.');
786
- emit({ ...complete, hostedAdmission: false });
787
- }