@blinkhost/cli 2.3.0 → 2.5.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 (43) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/README.md +251 -3
  3. package/dist/api.d.ts +1 -0
  4. package/dist/api.js +129 -2
  5. package/dist/assistant.d.ts +7 -0
  6. package/dist/assistant.js +460 -0
  7. package/dist/auth.d.ts +1 -0
  8. package/dist/auth.js +21 -24
  9. package/dist/cli.js +39 -13
  10. package/dist/compatibility.d.ts +1 -0
  11. package/dist/compatibility.js +43 -0
  12. package/dist/config.d.ts +2 -0
  13. package/dist/config.js +9 -1
  14. package/dist/credential-process.d.ts +19 -0
  15. package/dist/credential-process.js +75 -0
  16. package/dist/credentials.d.ts +4 -0
  17. package/dist/credentials.js +45 -46
  18. package/dist/device-flow.d.ts +24 -0
  19. package/dist/device-flow.js +76 -0
  20. package/dist/guidance.d.ts +1 -1
  21. package/dist/guidance.js +68 -5
  22. package/dist/macos-keychain-input.d.ts +6 -0
  23. package/dist/macos-keychain-input.js +22 -0
  24. package/dist/module-build.d.ts +7 -0
  25. package/dist/module-build.js +37 -0
  26. package/dist/peer-review.d.ts +8 -0
  27. package/dist/peer-review.js +55 -0
  28. package/dist/project-export.d.ts +1 -0
  29. package/dist/project-export.js +79 -0
  30. package/dist/research.d.ts +1 -0
  31. package/dist/research.js +42 -0
  32. package/dist/starter.d.ts +11 -0
  33. package/dist/starter.js +45 -0
  34. package/dist/templates.js +10 -8
  35. package/dist/terminal.d.ts +2 -0
  36. package/dist/terminal.js +12 -0
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/dist/windows-vault-command.d.ts +12 -0
  40. package/dist/windows-vault-command.js +42 -0
  41. package/dist/workflows.d.ts +17 -1
  42. package/dist/workflows.js +76 -4
  43. package/package.json +2 -2
package/dist/api.js CHANGED
@@ -4,6 +4,56 @@ import { deleteRefreshCredential, getRefreshCredential, setRefreshCredential } f
4
4
  import { CliError, EXIT } from './errors.js';
5
5
  import { VERSION } from './version.js';
6
6
  const REQUEST_TIMEOUT_MS = 30_000;
7
+ // Only locally written guidance may reach terminal output. Never echo server
8
+ // details, filenames or arbitrary codes from a source-export error response.
9
+ const EXPORT_GUIDANCE = {
10
+ project_template_unsupported: { status: 400, message: 'Portable export needs a supported frontend configuration. Backend-only projects can use projects export PROJECT_UUID --source-only --output ./source.zip to download source without generating or validating build configuration. This command has not changed your source.' },
11
+ committed_secret_detected: { status: 409, message: 'Source export was blocked by credential screening. Review possible credentials in your project before sharing it, and rotate any exposed values. Do not paste credentials into a support request.' },
12
+ html_package_invalid: { status: 409, message: 'Source export could not read the HTML project package configuration. Check that package.json is valid JSON and its scripts field is an object.' },
13
+ dependency_lockfile_missing: { status: 409, message: 'Source export needs package-lock.json for this HTML project. Review the project dependencies, then use its normal dependency-install workflow to create the lockfile. This command has not installed or run anything.' },
14
+ };
15
+ async function exportErrorGuidance(response) {
16
+ const limit = 8192;
17
+ if (![400, 409].includes(response.status)
18
+ || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json'
19
+ || !response.body)
20
+ return;
21
+ const length = response.headers.get('content-length');
22
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > limit))
23
+ return;
24
+ const reader = response.body.getReader();
25
+ try {
26
+ let size = 0;
27
+ const chunks = [];
28
+ while (true) {
29
+ const chunk = await reader.read();
30
+ if (chunk.done)
31
+ break;
32
+ size += chunk.value.byteLength;
33
+ if (size > limit)
34
+ return;
35
+ chunks.push(Buffer.from(chunk.value));
36
+ }
37
+ if (length !== null && Number(length) !== size)
38
+ return;
39
+ const payload = JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
40
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
41
+ return;
42
+ const code = payload.code;
43
+ if (typeof code !== 'string' || !Object.hasOwn(EXPORT_GUIDANCE, code))
44
+ return;
45
+ const guidance = EXPORT_GUIDANCE[code];
46
+ if (guidance.status === response.status)
47
+ return { code, message: guidance.message };
48
+ }
49
+ catch {
50
+ // Malformed, incomplete and failed error bodies retain the generic HTTP error.
51
+ }
52
+ finally {
53
+ await reader.cancel().catch(() => undefined);
54
+ reader.releaseLock();
55
+ }
56
+ }
7
57
  function messageFrom(payload, fallback) {
8
58
  if (payload && typeof payload === 'object') {
9
59
  const candidate = payload;
@@ -29,11 +79,15 @@ export async function publicRequest(apiOrigin, path, init = {}) {
29
79
  const controller = new AbortController();
30
80
  const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
31
81
  try {
82
+ // Headers are case-insensitive. Object-spreading normalized caller headers
83
+ // into mixed-case defaults makes fetch combine Content-Type values.
84
+ const headers = new Headers({ Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': `BlinkHost-CLI/${VERSION}` });
85
+ new Headers(init.headers).forEach((value, name) => headers.set(name, value));
32
86
  const response = await fetch(new URL(path, `${apiOrigin}/`), {
33
87
  ...init,
34
88
  redirect: 'error',
35
89
  signal: controller.signal,
36
- headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': `BlinkHost-CLI/${VERSION}`, ...Object.fromEntries(new Headers(init.headers).entries()) },
90
+ headers,
37
91
  });
38
92
  return { response, data: await parseResponse(response) };
39
93
  }
@@ -89,7 +143,7 @@ export class ApiClient {
89
143
  const refresh = process.env.BLINKHOST_REFRESH_TOKEN || await getRefreshCredential(selected.name);
90
144
  if (!refresh)
91
145
  throw new CliError('Sign in with `blinkhost auth login` or provide BLINKHOST_ACCESS_TOKEN for CI.', EXIT.auth, 'not_authenticated');
92
- const result = await publicRequest(selected.profile.apiOrigin, '/api/cli/v2/token/refresh/', { method: 'POST', body: JSON.stringify({ refresh_token: refresh }) });
146
+ const result = await publicRequest(selected.profile.apiOrigin, '/api/cli/v2/token/refresh/', { method: 'POST', body: JSON.stringify({ refresh_token: refresh, client_version: VERSION }) });
93
147
  if (!result.response.ok) {
94
148
  if (!process.env.BLINKHOST_REFRESH_TOKEN)
95
149
  await deleteRefreshCredential(selected.name);
@@ -103,6 +157,79 @@ export class ApiClient {
103
157
  static fromAccessToken(profileName, profile, accessToken) {
104
158
  return new ApiClient(profileName, profile, accessToken, true);
105
159
  }
160
+ async projectArchive(projectId, mode = 'portable') {
161
+ if (!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(projectId)) {
162
+ throw new CliError('A valid project UUID is required.', EXIT.usage, 'invalid_project_id');
163
+ }
164
+ if (mode !== 'portable' && mode !== 'source')
165
+ throw new CliError('Choose portable or source export mode.', EXIT.usage, 'export_mode_invalid');
166
+ const controller = new AbortController();
167
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
168
+ const requestId = randomUUID();
169
+ const limit = 32 * 1024 * 1024;
170
+ let reader;
171
+ try {
172
+ const response = await fetch(new URL(`/api/source-control/connections/project-export/?project=${projectId}${mode === 'source' ? '&mode=source' : ''}`, this.profile.apiOrigin), {
173
+ method: 'GET', redirect: 'error', signal: controller.signal,
174
+ // Allow the API's JSON error renderer during content negotiation.
175
+ // Successful responses must still pass ZIP-only validation below.
176
+ headers: { Accept: 'application/zip, application/json', Authorization: `Bearer ${this.accessToken}`,
177
+ 'X-Request-ID': requestId, 'User-Agent': `BlinkHost-CLI/${VERSION}` },
178
+ });
179
+ if (!response.ok) {
180
+ const guidance = await exportErrorGuidance(response);
181
+ throw new CliError(guidance?.message || `Project export returned HTTP ${response.status}. Check your access and the project's export status in BlinkHost.`, [401, 403].includes(response.status) ? EXIT.auth : response.status === 409 ? EXIT.conflict : EXIT.remote, `api_${response.status}`, [`Request ID: ${requestId}`, ...(guidance ? [`Export reason: ${guidance.code}`] : [])]);
182
+ }
183
+ // An older API may ignore an unknown query parameter. Never silently
184
+ // save generated configuration when an exact source export was requested.
185
+ if (mode === 'source' && response.headers.get('x-blinkhost-export-mode') !== 'source') {
186
+ await response.body?.cancel().catch(() => undefined);
187
+ throw new CliError('The server did not confirm a source-only export. No archive was saved. Check server support before trying again.', EXIT.validation, 'export_mode_unconfirmed');
188
+ }
189
+ const length = response.headers.get('content-length');
190
+ if (response.status !== 200 || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/zip'
191
+ || (length !== null && (!/^\d+$/.test(length) || Number(length) > limit)) || !response.body) {
192
+ throw new CliError('The export did not return a supported ZIP archive (maximum 32 MiB).', EXIT.validation, 'invalid_project_archive');
193
+ }
194
+ reader = response.body.getReader();
195
+ const chunks = [];
196
+ let size = 0;
197
+ while (true) {
198
+ const chunk = await reader.read();
199
+ if (chunk.done)
200
+ break;
201
+ size += chunk.value.byteLength;
202
+ if (size > limit)
203
+ throw new CliError('The project ZIP exceeds the CLI download limit of 32 MiB.', EXIT.validation, 'archive_too_large');
204
+ chunks.push(Buffer.from(chunk.value));
205
+ }
206
+ const body = Buffer.concat(chunks, size);
207
+ // The canonical exporter writes a single-disk ZIP without an archive
208
+ // comment. Check its closing directory record too, not just the prefix.
209
+ const end = size - 22;
210
+ if ((length !== null && Number(length) !== size) || size < 22 || !['504b0304', '504b0506'].includes(body.subarray(0, 4).toString('hex'))
211
+ || body.subarray(end, end + 4).toString('hex') !== '504b0506'
212
+ || body.readUInt16LE(end + 4) !== 0 || body.readUInt16LE(end + 6) !== 0
213
+ || body.readUInt16LE(end + 8) !== body.readUInt16LE(end + 10)
214
+ || body.readUInt16LE(end + 20) !== 0
215
+ || body.readUInt32LE(end + 12) + body.readUInt32LE(end + 16) !== end) {
216
+ throw new CliError('The export response is not a ZIP archive.', EXIT.validation, 'invalid_project_archive');
217
+ }
218
+ return body;
219
+ }
220
+ catch (error) {
221
+ if (error instanceof CliError)
222
+ throw error;
223
+ const timedOut = controller.signal.aborted;
224
+ throw new CliError(timedOut ? 'The project export timed out. No archive was saved.' : 'The project export could not be downloaded. No archive was saved.', EXIT.network, timedOut ? 'request_timeout' : 'network_error');
225
+ }
226
+ finally {
227
+ controller.abort();
228
+ if (reader)
229
+ await reader.cancel().catch(() => undefined);
230
+ clearTimeout(timeout);
231
+ }
232
+ }
106
233
  async request(path, init = {}) {
107
234
  const headers = new Headers(init.headers);
108
235
  headers.set('Authorization', `Bearer ${this.accessToken}`);
@@ -0,0 +1,7 @@
1
+ export declare function readAssistantRequest(path: string | undefined): Promise<Record<string, unknown>>;
2
+ export declare function readWorkflowPlan(path: string | undefined): Promise<Record<string, unknown>>;
3
+ export declare function readProjectGuidance(path: string | undefined): Promise<string>;
4
+ export declare function runAssistant(input: string[], profile?: string): Promise<{
5
+ message: string;
6
+ data: unknown;
7
+ }>;
@@ -0,0 +1,460 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { ApiClient } from './api.js';
4
+ import { CliError, EXIT } from './errors.js';
5
+ import { validateCompatibility } from './compatibility.js';
6
+ import { validateResearchCatalog } from './research.js';
7
+ import { validateModuleBuild } from './module-build.js';
8
+ import { validatePeerResponse } from './peer-review.js';
9
+ import { starterName, starterLanguage, validateStarter } from './starter.js';
10
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
+ const digest = /^[0-9a-f]{64}$/;
12
+ function option(args, flag) {
13
+ const index = args.indexOf(flag);
14
+ if (index < 0)
15
+ return undefined;
16
+ const value = args[index + 1];
17
+ if (!value || value.startsWith('--'))
18
+ throw new CliError(`${flag} needs a value.`, EXIT.usage, 'missing_option_value');
19
+ args.splice(index, 2);
20
+ return value;
21
+ }
22
+ function identifier(value) {
23
+ if (!value || !uuid.test(value))
24
+ throw new CliError('Provide a valid project or task UUID.', EXIT.usage, 'invalid_identifier');
25
+ return value;
26
+ }
27
+ function noExtra(args) {
28
+ if (args.length)
29
+ throw new CliError('Unexpected assistant argument. Use blinkhost help ai.', EXIT.usage, 'unexpected_argument');
30
+ }
31
+ async function readRequestObject(path) {
32
+ if (!path?.startsWith('@') || path.length < 2)
33
+ throw new CliError('Use --request @request.json. Do not put prompts or credentials in command arguments.', EXIT.usage, 'request_file_required');
34
+ const handle = await open(path.slice(1), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => {
35
+ throw new CliError('The request file could not be opened safely.', EXIT.filesystem, 'request_file_unavailable');
36
+ });
37
+ try {
38
+ const metadata = await handle.stat();
39
+ if (!metadata.isFile() || metadata.size > 16384)
40
+ throw new CliError('Use a regular request file no larger than 16 KiB.', EXIT.validation, 'request_file_invalid');
41
+ const buffer = Buffer.alloc(16385);
42
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
43
+ if (bytesRead > 16384)
44
+ throw new CliError('The request file exceeds 16 KiB.', EXIT.validation, 'request_file_invalid');
45
+ let value;
46
+ try {
47
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytesRead)));
48
+ }
49
+ catch {
50
+ throw new CliError('The request file must contain a UTF-8 JSON object.', EXIT.validation, 'request_invalid');
51
+ }
52
+ if (!value || typeof value !== 'object' || Array.isArray(value))
53
+ throw new CliError('The request must be a JSON object.', EXIT.validation, 'request_invalid');
54
+ return value;
55
+ }
56
+ finally {
57
+ await handle.close();
58
+ }
59
+ }
60
+ export async function readAssistantRequest(path) {
61
+ const body = await readRequestObject(path);
62
+ const allowed = new Set(['project_id', 'client_request_id', 'prompt', 'mode', 'model', 'maximum_units', 'source_paths', 'research_source_ids']);
63
+ if (Object.keys(body).some(key => !allowed.has(key)) || typeof body.project_id !== 'string' || !uuid.test(body.project_id)
64
+ || typeof body.client_request_id !== 'string' || !uuid.test(body.client_request_id)
65
+ || typeof body.prompt !== 'string' || !body.prompt.trim() || Buffer.byteLength(body.prompt) > 8192
66
+ || !Number.isInteger(body.maximum_units) || Number(body.maximum_units) < 1 || Number(body.maximum_units) > 2000) {
67
+ throw new CliError('Include project_id, a stable client_request_id UUID, prompt and maximum_units (1–2000). Review blinkhost docs ai.', EXIT.validation, 'request_invalid');
68
+ }
69
+ if (body.source_paths !== undefined && (!Array.isArray(body.source_paths) || body.source_paths.length > 8
70
+ || new Set(body.source_paths).size !== body.source_paths.length
71
+ || body.source_paths.some(path => typeof path !== 'string' || !path || Buffer.byteLength(path) > 500
72
+ || /[\\:\x00-\x1f]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..')))) {
73
+ throw new CliError('source_paths must contain up to eight unique project-relative file paths. Only these remote workspace files are shared; no local files are uploaded.', EXIT.validation, 'source_selection_invalid');
74
+ }
75
+ if (body.research_source_ids !== undefined && (!Array.isArray(body.research_source_ids)
76
+ || body.research_source_ids.length > 4 || new Set(body.research_source_ids).size !== body.research_source_ids.length
77
+ || body.research_source_ids.some(id => typeof id !== 'string' || !digest.test(id))
78
+ || (body.research_source_ids.length > 0 && body.mode !== 'research'))) {
79
+ throw new CliError('research_source_ids must contain up to four unique IDs from ai sources, only in research mode. These select reviewed excerpts, not a live web search.', EXIT.validation, 'research_selection_invalid');
80
+ }
81
+ return body;
82
+ }
83
+ export async function readWorkflowPlan(path) {
84
+ const body = await readRequestObject(path);
85
+ const allowed = new Set(['steps', 'maximum_units', 'maximum_context_units']);
86
+ if (Object.keys(body).some(key => !allowed.has(key))
87
+ || !Number.isSafeInteger(body.maximum_units) || Number(body.maximum_units) < 1 || Number(body.maximum_units) > 2000
88
+ || !Number.isSafeInteger(body.maximum_context_units) || Number(body.maximum_context_units) < 1 || Number(body.maximum_context_units) > 393216
89
+ || !Array.isArray(body.steps) || body.steps.length < 1 || body.steps.length > 3
90
+ || body.steps.some(step => !step || typeof step !== 'object' || Array.isArray(step)
91
+ || Object.keys(step).sort().join(',') !== 'maximum_units,mode,model'
92
+ || !['plan', 'diagnose', 'review'].includes(step.mode)
93
+ || !['gpt-6-luna', 'gpt-5.6-terra', 'gpt-6-sol', 'gpt-5.6-luna', 'gpt-5.6-sol'].includes(step.model)
94
+ || !Number.isSafeInteger(step.maximum_units) || step.maximum_units < 1 || step.maximum_units > 2000)
95
+ || body.steps.reduce((total, step) => total + step.maximum_units, 0) >= Number(body.maximum_units)) {
96
+ throw new CliError('Use one to three plan, diagnose or review steps, valid models and whole-number credit limits. The total must also cover the original task. See blinkhost docs ai.', EXIT.validation, 'workflow_plan_invalid');
97
+ }
98
+ return body;
99
+ }
100
+ function planVersion(args) {
101
+ const revision = option(args, '--expected-revision');
102
+ const value = option(args, '--digest');
103
+ if (!revision || !/^[1-9][0-9]{0,2}$/.test(revision) || Number(revision) > 100 || !value || !digest.test(value)) {
104
+ throw new CliError('Pass --expected-revision and --digest from the saved plan you inspected with workflow-status. Review again if the plan changes.', EXIT.usage, 'workflow_version_required');
105
+ }
106
+ return { expected_revision: Number(revision), plan_digest: value };
107
+ }
108
+ export async function readProjectGuidance(path) {
109
+ if (!path?.startsWith('@') || path.length < 2)
110
+ throw new CliError('Use --file @guidance.txt. Do not put guidance or credentials in command arguments.', EXIT.usage, 'guidance_file_required');
111
+ const handle = await open(path.slice(1), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => {
112
+ throw new CliError('The guidance file could not be opened safely.', EXIT.filesystem, 'guidance_file_unavailable');
113
+ });
114
+ try {
115
+ const metadata = await handle.stat();
116
+ if (!metadata.isFile() || metadata.size > 4096)
117
+ throw new CliError('Use a regular UTF-8 text file no larger than 4 KiB.', EXIT.validation, 'guidance_file_invalid');
118
+ const buffer = Buffer.alloc(4097);
119
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
120
+ if (bytesRead > 4096)
121
+ throw new CliError('The guidance file exceeds 4 KiB.', EXIT.validation, 'guidance_file_invalid');
122
+ let content;
123
+ try {
124
+ content = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytesRead));
125
+ }
126
+ catch {
127
+ throw new CliError('The guidance file must be valid UTF-8 text.', EXIT.validation, 'guidance_file_invalid');
128
+ }
129
+ if (!content.trim() || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(content))
130
+ throw new CliError('Use nonempty text without control characters. Use memory-clear to remove saved guidance.', EXIT.validation, 'guidance_file_invalid');
131
+ return content;
132
+ }
133
+ finally {
134
+ await handle.close();
135
+ }
136
+ }
137
+ export async function runAssistant(input, profile) {
138
+ const args = [...input];
139
+ const action = args.shift();
140
+ let path;
141
+ let body;
142
+ let method = 'POST';
143
+ let message;
144
+ let moduleBuildExpected;
145
+ let starterExpected;
146
+ let peerExpected;
147
+ if (['peer-inbox', 'peer-options', 'peer-invite', 'peer-review', 'peer-approve', 'peer-decline', 'peer-withdraw'].includes(action ?? '')) {
148
+ const project = identifier(option(args, '--project')).toLowerCase();
149
+ peerExpected = { project };
150
+ if (action === 'peer-inbox') {
151
+ path = `/api/idam/projects/${project}/peer-reviews/`;
152
+ message = 'Reviews shared with you loaded. Open each review to check current source and access.';
153
+ }
154
+ else {
155
+ const id = identifier(args.shift()).toLowerCase();
156
+ const requester = ['peer-options', 'peer-invite', 'peer-withdraw'].includes(action);
157
+ path = requester ? `/api/idam/tasks/${id}/peer-review/` : `/api/idam/peer-reviews/${id}/`;
158
+ if (requester)
159
+ peerExpected.task = id;
160
+ else
161
+ peerExpected.peer = id;
162
+ message = action === 'peer-options' ? 'Eligible reviewers, workspace review requirement and current sharing status loaded.'
163
+ : 'Review these selected changes before deciding. This is not a save, build or deployment.';
164
+ if (!['peer-options', 'peer-review'].includes(action)) {
165
+ if (option(args, '--confirm')?.toLowerCase() !== id)
166
+ throw new CliError('Repeat the task or peer review UUID with --confirm before sharing code or recording a decision.', EXIT.usage, 'confirmation_required');
167
+ if (action === 'peer-withdraw') {
168
+ peerExpected.peer = identifier(option(args, '--peer')).toLowerCase();
169
+ path += 'withdraw/';
170
+ body = { peer_id: peerExpected.peer };
171
+ message = 'Review withdrawn. Its history is retained. Any review required by your workspace still applies before saving.';
172
+ }
173
+ else {
174
+ const value = option(args, '--digest');
175
+ if (!value || !digest.test(value))
176
+ throw new CliError('Pass the exact digest from the code review you inspected.', EXIT.usage, 'review_digest_required');
177
+ peerExpected.digest = value;
178
+ if (action === 'peer-invite') {
179
+ const reviewer = option(args, '--reviewer');
180
+ if (!reviewer || !/^[1-9][0-9]*$/.test(reviewer) || !Number.isSafeInteger(Number(reviewer)))
181
+ throw new CliError('Select a reviewer ID from peer-options.', EXIT.usage, 'reviewer_required');
182
+ peerExpected.reviewer = Number(reviewer);
183
+ body = { reviewer_id: Number(reviewer), action_digest: value };
184
+ message = 'Selected code shared with the named reviewer. Conversation and other proposed files remain private. No source saved.';
185
+ }
186
+ else {
187
+ path += 'approve/';
188
+ body = { review_digest: value, approve: action === 'peer-approve' };
189
+ message = 'Peer decision recorded for this version. It does not save, build or publish code.';
190
+ }
191
+ }
192
+ }
193
+ }
194
+ noExtra(args);
195
+ }
196
+ else if (['starters', 'starter-review', 'starter-status', 'starter-approve'].includes(action ?? '')) {
197
+ const project = identifier(option(args, '--project')).toLowerCase();
198
+ path = `/api/idam/projects/${project}/starters/`;
199
+ starterExpected = { project };
200
+ if (action === 'starters') {
201
+ message = 'Available backend starters. No files have been saved or built.';
202
+ }
203
+ else if (action === 'starter-review') {
204
+ const name = option(args, '--name');
205
+ const language = option(args, '--language');
206
+ const revision = option(args, '--revision');
207
+ const requestId = identifier(option(args, '--request-id')).toLowerCase();
208
+ if (!starterName(name) || !starterLanguage(language) || !revision || !digest.test(revision)) {
209
+ throw new CliError('Use a lowercase module name (1–64 letters, digits or hyphens), --language from starters and its --revision. Retain your --request-id UUID.', EXIT.usage, 'starter_request_invalid');
210
+ }
211
+ path += 'review/';
212
+ body = { name, language, revision, client_request_id: requestId };
213
+ starterExpected = { project, name, language, revision };
214
+ message = 'Starter review prepared. Inspect every file, the project, module name and expiry before approving. No source has been saved; no build or AI credits are used.';
215
+ }
216
+ else {
217
+ const review = identifier(args.shift()).toLowerCase();
218
+ path += `reviews/${review}/`;
219
+ starterExpected = { project, review };
220
+ if (action === 'starter-approve') {
221
+ if (option(args, '--confirm') !== review)
222
+ throw new CliError('Repeat the exact review UUID with --confirm to save the reviewed starter.', EXIT.usage, 'confirmation_required');
223
+ const value = option(args, '--digest');
224
+ if (!value || !digest.test(value))
225
+ throw new CliError('Pass --digest from the starter review you inspected.', EXIT.usage, 'review_digest_required');
226
+ path += 'apply/';
227
+ body = { action_digest: value };
228
+ starterExpected.digest = value;
229
+ message = 'Starter source saved, not built or published. Use build-modules for the next review. Normal project limits apply; no AI credits were used.';
230
+ }
231
+ else
232
+ message = 'Starter review and save receipt loaded. A historical receipt does not establish current source, build or deployment health.';
233
+ }
234
+ noExtra(args);
235
+ }
236
+ else if (['build-modules', 'build-review', 'build-status', 'build-approve'].includes(action ?? '')) {
237
+ const project = identifier(option(args, '--project')).toLowerCase();
238
+ path = `/api/idam/projects/${project}/module-builds/`;
239
+ moduleBuildExpected = { project };
240
+ if (action === 'build-modules') {
241
+ message = 'Saved backend modules and compiler availability. No build has been requested.';
242
+ }
243
+ else if (action === 'build-review') {
244
+ const module = identifier(option(args, '--module')).toLowerCase();
245
+ const revision = option(args, '--revision');
246
+ if (!revision || !digest.test(revision))
247
+ throw new CliError('Use --revision from build-modules for the saved source you inspected.', EXIT.usage, 'source_revision_required');
248
+ const requestId = identifier(option(args, '--request-id')).toLowerCase();
249
+ path += 'review/';
250
+ body = { module_id: module, revision, client_request_id: requestId };
251
+ moduleBuildExpected = { project, module, revision };
252
+ message = 'Build review prepared, not started. Approval uses the normal build allowance, configured overages and duration usage; no AI credits. Inspect saved source in the IDE before approving. This never publishes.';
253
+ }
254
+ else {
255
+ const review = identifier(args.shift()).toLowerCase();
256
+ path += `reviews/${review}/`;
257
+ moduleBuildExpected = { project, review };
258
+ if (action === 'build-approve') {
259
+ if (option(args, '--confirm') !== review)
260
+ throw new CliError('Repeat the exact review UUID with --confirm to request one metered build.', EXIT.usage, 'confirmation_required');
261
+ const value = option(args, '--digest');
262
+ if (!value || !digest.test(value))
263
+ throw new CliError('Pass --digest from the build review you inspected.', EXIT.usage, 'review_digest_required');
264
+ path += 'apply/';
265
+ body = { action_digest: value };
266
+ moduleBuildExpected.digest = value;
267
+ message = 'Build request recorded, not published. Check build-status for progress and the IDE for diagnostics. Normal build usage applies; no AI credits.';
268
+ }
269
+ else
270
+ message = 'Build review and receipt loaded. A receipt is not proof of successful compilation or deployment.';
271
+ }
272
+ noExtra(args);
273
+ }
274
+ else if (action === 'compatibility') {
275
+ const project = identifier(option(args, '--project')).toLowerCase();
276
+ noExtra(args);
277
+ path = `/api/idam/projects/${project}/compatibility/`;
278
+ message = 'Declared dependencies reviewed, not execution-tested. No findings is not a compatibility pass. No code changes, model calls or credit reservations were made. Review before sharing project metadata.';
279
+ }
280
+ else if (action === 'memory-show' || action === 'memory-save' || action === 'memory-clear') {
281
+ const project = identifier(option(args, '--project'));
282
+ path = `/api/idam/projects/${project}/memory/`;
283
+ if (action === 'memory-show') {
284
+ noExtra(args);
285
+ message = 'Your private project guidance. Review before sharing this output.';
286
+ }
287
+ else {
288
+ const version = option(args, '--expected-version');
289
+ if (!version || !/^(0|[1-9][0-9]{0,15})$/.test(version) || !Number.isSafeInteger(Number(version)) || Number(version) >= Number.MAX_SAFE_INTEGER) {
290
+ throw new CliError('Use --expected-version from memory-show. A changed saved version requires another review.', EXIT.usage, 'guidance_version_required');
291
+ }
292
+ if (option(args, '--confirm') !== project)
293
+ throw new CliError('Repeat the project UUID with --confirm to change your guidance for future tasks.', EXIT.usage, 'confirmation_required');
294
+ const file = action === 'memory-save' ? option(args, '--file') : undefined;
295
+ noExtra(args);
296
+ body = { expected_version: Number(version), content: action === 'memory-save' ? await readProjectGuidance(file) : '' };
297
+ method = 'PUT';
298
+ message = action === 'memory-save'
299
+ ? 'Guidance saved for your future tasks with the model. Project permissions and hosting limits are unchanged.'
300
+ : 'Guidance cleared for future tasks. Existing task copies and backups are not erased.';
301
+ }
302
+ }
303
+ else if (action === 'start') {
304
+ const file = option(args, '--request');
305
+ noExtra(args);
306
+ body = await readAssistantRequest(file);
307
+ path = '/api/idam/tasks/';
308
+ message = 'Task accepted. Check its status; acceptance does not mean work has completed.';
309
+ }
310
+ else if (action === 'sources') {
311
+ const project = identifier(option(args, '--project'));
312
+ noExtra(args);
313
+ path = `/api/idam/projects/${project}/research-sources/`;
314
+ message = 'Reviewed public excerpts, not a live search. Select up to four IDs in research_source_ids for a research request. Source text counts toward the credit estimate; availability is checked again before work starts.';
315
+ }
316
+ else if (action === 'list') {
317
+ const project = identifier(option(args, '--project'));
318
+ noExtra(args);
319
+ path = `/api/idam/tasks/?project_id=${project}`;
320
+ message = 'Your assistant tasks for this project.';
321
+ }
322
+ else if (['workflow-plan', 'workflow-start', 'workflow-revise', 'workflow-approve', 'workflow-status', 'workflow-cancel'].includes(action ?? '')) {
323
+ const id = identifier(args.shift());
324
+ if (action === 'workflow-status') {
325
+ path = `/api/idam/workflows/${id}/`;
326
+ message = 'Connected review loaded. Open each linked task to inspect its draft and credit record.';
327
+ }
328
+ else {
329
+ if (option(args, '--confirm') !== id)
330
+ throw new CliError('Repeat the exact task or workflow ID with --confirm.', EXIT.usage, 'confirmation_required');
331
+ if (action === 'workflow-revise' || action === 'workflow-approve') {
332
+ const version = planVersion(args);
333
+ const file = action === 'workflow-revise' ? option(args, '--request') : undefined;
334
+ noExtra(args);
335
+ path = `/api/idam/workflows/${id}/${action === 'workflow-approve' ? 'approve/' : ''}`;
336
+ method = action === 'workflow-revise' ? 'PATCH' : 'POST';
337
+ body = { ...(action === 'workflow-revise' ? await readWorkflowPlan(file) : {}), ...version };
338
+ message = action === 'workflow-revise'
339
+ ? 'Revised draft saved. Inspect workflow-status and approve the new saved version before follow-ups can start.'
340
+ : 'Plan approval recorded. Follow-ups can start within the saved limits after each prior step finishes. Inspect workflow-status; approval does not mean work has completed.';
341
+ }
342
+ else if (action === 'workflow-plan' || action === 'workflow-start') {
343
+ const ceiling = option(args, '--maximum-units');
344
+ if (!ceiling || !/^[1-9][0-9]{0,3}$/.test(ceiling) || Number(ceiling) < 161 || Number(ceiling) > 2000) {
345
+ throw new CliError('Set --maximum-units (161–2000) to cover the original task limit plus 160 additional credits. Inspect ai status first.', EXIT.usage, 'workflow_budget_invalid');
346
+ }
347
+ path = `/api/idam/tasks/${id}/workflow/`;
348
+ body = { steps: [{ mode: 'diagnose', model: 'gpt-6-luna', maximum_units: 80 },
349
+ { mode: 'review', model: 'gpt-6-luna', maximum_units: 80 }],
350
+ maximum_units: Number(ceiling), maximum_context_units: 200000 };
351
+ message = 'Draft plan saved, not approved. Your original task continues independently; no follow-up credits were reserved. Inspect workflow-status, revise if needed, then use workflow-approve with the saved revision and digest. No tests, source edits or deployment were requested.';
352
+ }
353
+ else {
354
+ path = `/api/idam/workflows/${id}/cancel/`;
355
+ body = {};
356
+ message = 'Sequence stop recorded. Later steps will not start; already dispatched work may incur usage. Inspect each task for remaining reservations.';
357
+ }
358
+ }
359
+ noExtra(args);
360
+ }
361
+ else {
362
+ if (!action || !['status', 'events', 'export', 'review', 'approve', 'rollback-review', 'rollback-approve', 'cancel', 'resume'].includes(action)) {
363
+ throw new CliError('Choose an assistant command, such as ai start, ai status, ai review or ai peer-inbox. Run blinkhost docs ai for the full command list, approval steps and examples.', EXIT.usage, 'unknown_action');
364
+ }
365
+ const id = identifier(args.shift());
366
+ path = `/api/idam/tasks/${id}/`;
367
+ message = 'Assistant task loaded.';
368
+ if (action === 'export') {
369
+ const sourceIndex = args.indexOf('--include-source');
370
+ const includeSource = sourceIndex >= 0;
371
+ if (includeSource)
372
+ args.splice(sourceIndex, 1);
373
+ path += `export/${includeSource ? '?include_source=1' : ''}`;
374
+ message = 'Private task snapshot exported. Review before sharing; this is not a project backup or proof of deployment.';
375
+ }
376
+ else if (action === 'review') {
377
+ const paths = [];
378
+ while (args.includes('--path'))
379
+ paths.push(option(args, '--path'));
380
+ if (paths.length > 20)
381
+ throw new CliError('Review at most 20 paths at a time.', EXIT.usage, 'selection_invalid');
382
+ body = paths.length ? { paths } : {};
383
+ path += 'review/';
384
+ message = 'Compare these exact changes before approving. No source has been changed.';
385
+ }
386
+ else if (action === 'rollback-review') {
387
+ body = {};
388
+ path += 'rollback/review/';
389
+ message = 'Review each file to restore or delete before approving this undo. No source has been changed.';
390
+ }
391
+ else if (action === 'approve' || action === 'rollback-approve' || action === 'cancel' || action === 'resume') {
392
+ const confirmation = option(args, '--confirm');
393
+ if (confirmation !== id)
394
+ throw new CliError(`Repeat the task ID with --confirm to ${action} this task.`, EXIT.usage, 'confirmation_required');
395
+ if (action === 'approve' || action === 'rollback-approve') {
396
+ const value = option(args, '--digest');
397
+ if (!value || !digest.test(value))
398
+ throw new CliError('Pass the action_digest from the review you inspected.', EXIT.usage, 'review_digest_required');
399
+ body = { action_digest: value };
400
+ path += action === 'rollback-approve' ? 'rollback/apply/' : 'apply/';
401
+ message = action === 'rollback-approve'
402
+ ? 'Source undo recorded. This does not undo a deployment or change charges. Check your workspace before building or publishing.'
403
+ : 'Source save recorded. Check the task and workspace for later edits or an undo. Build, test and preview before publishing.';
404
+ }
405
+ else {
406
+ body = {};
407
+ path += `${action}/`;
408
+ message = action === 'resume'
409
+ ? 'Continuation requested for the existing task within its original credit limit. Active work and retry delays are preserved. Inspect status for progress; this does not restart a stopped task or approve changes.'
410
+ : 'Stop request recorded. Unknown provider usage may remain reserved until reconciled.';
411
+ }
412
+ }
413
+ noExtra(args);
414
+ }
415
+ const client = await ApiClient.create(profile);
416
+ const result = await client.request(path, body === undefined ? {} : { method, body: JSON.stringify(body) });
417
+ if (moduleBuildExpected)
418
+ validateModuleBuild(result, moduleBuildExpected, action);
419
+ if (starterExpected)
420
+ validateStarter(result, starterExpected, action);
421
+ if (peerExpected)
422
+ validatePeerResponse(result, peerExpected, action);
423
+ if (action === 'resume') {
424
+ const response = result;
425
+ if (!response || typeof response !== 'object'
426
+ || !response.task || typeof response.task !== 'object'
427
+ || response.task.id !== path.split('/')[4]
428
+ || !['queued', 'running'].includes(String(response.task.status))
429
+ || !Number.isSafeInteger(response.task.maximum_units) || Number(response.task.maximum_units) < 1
430
+ || !['requested', 'already_scheduled'].includes(String(response.continuation))) {
431
+ throw new CliError('The continuation response could not be verified. Check ai status before deciding whether to try again; do not retry automatically.', EXIT.remote, 'continuation_response_invalid');
432
+ }
433
+ if (response.continuation === 'already_scheduled') {
434
+ message = 'This task is already running or scheduled. No additional work was queued. Check ai status for progress; its original credit limit remains unchanged.';
435
+ }
436
+ }
437
+ if (action === 'compatibility')
438
+ validateCompatibility(result, path.split('/')[4]);
439
+ if (action === 'sources')
440
+ validateResearchCatalog(result, path.split('/')[4]);
441
+ if (action?.startsWith('memory-')) {
442
+ const memory = result;
443
+ if (!memory || typeof memory !== 'object' || memory.project_id !== path.split('/')[4]
444
+ || !Number.isSafeInteger(memory.version) || Number(memory.version) < 0
445
+ || typeof memory.content !== 'string' || Buffer.byteLength(memory.content) > 4096
446
+ || memory.max_bytes !== 4096 || memory.trust !== 'untrusted_user_guidance' || memory.visibility !== 'requester_private'
447
+ || (memory.updated_at !== null && (typeof memory.updated_at !== 'string' || !Number.isFinite(Date.parse(memory.updated_at))))
448
+ || (body && (memory.content !== body.content || Number(memory.version) < Number(body.expected_version)
449
+ || Number(memory.version) > Number(body.expected_version) + 1))) {
450
+ throw new CliError('The saved guidance could not be verified. Run memory-show and compare the saved version before making another change. Do not retry a write automatically.', EXIT.remote, 'guidance_response_invalid');
451
+ }
452
+ }
453
+ if (action === 'events' && result && typeof result === 'object') {
454
+ return { message: 'Task activity loaded.', data: result.events ?? [] };
455
+ }
456
+ // Export writes only to the command's normal output; no implicit local files,
457
+ // source edits, model calls, retries, package execution or worker access.
458
+ return { message, data: result };
459
+ }
460
+ //# sourceMappingURL=assistant.js.map
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export declare function login(options: {
2
2
  profile?: string;
3
3
  apiOrigin?: string;
4
+ scopes?: string[];
4
5
  openBrowser?: boolean;
5
6
  progress?: (line: string) => void;
6
7
  }): Promise<unknown>;