@dreamlake/dreamlake-cli 0.104.4 → 0.104.5

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.
@@ -3,8 +3,7 @@ export declare class HttpError extends Error {
3
3
  status: number;
4
4
  body: string;
5
5
  /**
6
- * The typed fields of a Source v1 error envelope, absent on every other
7
- * shape.
6
+ * Typed fields from nested v1 or flat API error envelopes.
8
7
  *
9
8
  * Kept as fields rather than folded into the message because they are what a
10
9
  * caller BRANCHES on. `code` is the stable identity of a failure — the
@@ -13,13 +12,14 @@ export declare class HttpError extends Error {
13
12
  * help", which no client can derive from a status alone: a 503 from a rate
14
13
  * limiter and a 503 from a misconfigured binding look the same on the wire.
15
14
  *
16
- * `undefined` means "this response was not a v1 envelope", never "the server
15
+ * `undefined` means "this field was not provided", never "the server
17
16
  * said no". A caller that must fail closed has to treat undefined as
18
17
  * unknown rather than as false.
19
18
  */
20
19
  code?: string;
21
20
  retryable?: boolean;
22
21
  requestId?: string;
22
+ details?: Record<string, unknown>;
23
23
  constructor(status: number, body: string);
24
24
  /**
25
25
  * Pull a human message, and any typed fields, out of an error body.
package/dist/api/http.js CHANGED
@@ -5,8 +5,7 @@ export class HttpError extends Error {
5
5
  status;
6
6
  body;
7
7
  /**
8
- * The typed fields of a Source v1 error envelope, absent on every other
9
- * shape.
8
+ * Typed fields from nested v1 or flat API error envelopes.
10
9
  *
11
10
  * Kept as fields rather than folded into the message because they are what a
12
11
  * caller BRANCHES on. `code` is the stable identity of a failure — the
@@ -15,13 +14,14 @@ export class HttpError extends Error {
15
14
  * help", which no client can derive from a status alone: a 503 from a rate
16
15
  * limiter and a 503 from a misconfigured binding look the same on the wire.
17
16
  *
18
- * `undefined` means "this response was not a v1 envelope", never "the server
17
+ * `undefined` means "this field was not provided", never "the server
19
18
  * said no". A caller that must fail closed has to treat undefined as
20
19
  * unknown rather than as false.
21
20
  */
22
21
  code;
23
22
  retryable;
24
23
  requestId;
24
+ details;
25
25
  constructor(status, body) {
26
26
  const parsed = HttpError.parse(body);
27
27
  super(`(${status}) ${parsed.message}`);
@@ -31,6 +31,7 @@ export class HttpError extends Error {
31
31
  this.code = parsed.code;
32
32
  this.retryable = parsed.retryable;
33
33
  this.requestId = parsed.requestId;
34
+ this.details = parsed.details;
34
35
  }
35
36
  /**
36
37
  * Pull a human message, and any typed fields, out of an error body.
@@ -69,20 +70,34 @@ export class HttpError extends Error {
69
70
  out.retryable = e.retryable;
70
71
  if (typeof e.requestId === "string")
71
72
  out.requestId = e.requestId;
73
+ if (e.details && typeof e.details === 'object' && !Array.isArray(e.details))
74
+ out.details = e.details;
72
75
  return out;
73
76
  }
74
77
  // Email-allowlist rejections put the human text in `message`
75
78
  // (`error` is just "Forbidden").
76
79
  if (parsed.code === "email_domain_not_allowed" && parsed.message) {
77
- return { message: parsed.message };
80
+ return { message: parsed.message, code: parsed.code };
78
81
  }
82
+ // Legacy routes also carry stable codes. Do not mistake a human sentence
83
+ // in `error` for a code, and never infer retryability from an HTTP status.
84
+ const code = typeof parsed.code === 'string' ? parsed.code
85
+ : typeof parsed.error === 'string' && /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/.test(parsed.error) ? parsed.error : undefined;
86
+ const fields = {
87
+ ...(code ? { code } : {}),
88
+ ...(typeof parsed.retryable === 'boolean' ? { retryable: parsed.retryable } : {}),
89
+ ...(typeof parsed.requestId === 'string' ? { requestId: parsed.requestId } : {}),
90
+ ...(parsed.details && typeof parsed.details === 'object' && !Array.isArray(parsed.details) ? { details: parsed.details } : {}),
91
+ };
79
92
  if (typeof parsed.error === "string" && parsed.error) {
80
93
  const detail = typeof parsed.message === "string" && parsed.message && parsed.message !== parsed.error
81
94
  ? `: ${parsed.message}` : "";
82
- return { message: parsed.error + detail };
95
+ return { message: parsed.error + detail, ...fields };
83
96
  }
84
- if (parsed.message)
85
- return { message: parsed.message };
97
+ if (typeof parsed.message === 'string' && parsed.message)
98
+ return { message: parsed.message, ...fields };
99
+ if (code)
100
+ return { message: code, ...fields };
86
101
  }
87
102
  catch {
88
103
  // not JSON
@@ -1,4 +1,4 @@
1
- import { telemetryHeaders } from './telemetry.js';
1
+ import { telemetryHeaders, recordHttpFailure } from './telemetry.js';
2
2
  import { noteAgentHeaders, resourceSessionHeaders } from "./agent-identity.js";
3
3
  import { affiliateSuccessfulWrite } from './session-affiliation.js';
4
4
  // Thin fetch wrapper for dreamlake-server and BSS. Zero-dependency —
@@ -74,7 +74,9 @@ export async function requestJson(base, path, opts = {}) {
74
74
  catch { }
75
75
  if (!res.ok) {
76
76
  const body = await res.text().catch(() => "");
77
- throw new HttpError(res.status, body);
77
+ const error = new HttpError(res.status, body);
78
+ recordHttpFailure(error.status, error.code);
79
+ throw error;
78
80
  }
79
81
  const text = await res.text();
80
82
  if (!text)
@@ -123,7 +125,9 @@ export async function requestRaw(url, opts = {}) {
123
125
  }
124
126
  if (!res.ok) {
125
127
  const body = await res.text().catch(() => "");
126
- throw new HttpError(res.status, body);
128
+ const error = new HttpError(res.status, body);
129
+ recordHttpFailure(error.status, error.code);
130
+ throw error;
127
131
  }
128
132
  return res;
129
133
  }
@@ -5,6 +5,8 @@
5
5
  // upgrades to an Error with the server's message when the caller
6
6
  // doesn't need the status.
7
7
  import { fail } from "../helpers.js";
8
+ import { HttpError } from '../../api/http.js';
9
+ import { recordHttpFailure } from '../telemetry.js';
8
10
  import { affiliateSuccessfulWrite } from '../session-affiliation.js';
9
11
  import { noteAgentHeaders, resourceSessionHeaders } from '../agent-identity.js';
10
12
  import { resolveNamespace } from "./ctx.js";
@@ -52,6 +54,8 @@ export async function jsonRequest(method, url, token, body) {
52
54
  catch {
53
55
  /* leave raw text */
54
56
  }
57
+ if (!res.ok)
58
+ recordHttpFailure(res.status, new HttpError(res.status, text).code);
55
59
  if (res.ok)
56
60
  await affiliateSuccessfulWrite(url, method, token, parsed, body);
57
61
  return { status: res.status, body: parsed };
@@ -0,0 +1,6 @@
1
+ /** Report a failure without losing its machine-readable identity or claiming an
2
+ * uncertain write did not happen. Never include the raw response or arguments. */
3
+ export declare function reportCommandFailure(error: unknown, options: {
4
+ json?: boolean;
5
+ attempted: boolean;
6
+ }): void;
@@ -0,0 +1,34 @@
1
+ import { recordOperationFailure } from './telemetry.js';
2
+ import { HttpError } from '../api/http.js';
3
+ import { emitJson, fail } from './helpers.js';
4
+ const guidance = {
5
+ NOTE_TRANSFER_UNAVAILABLE: 'This move crosses workspaces. Preview the separate notes transfer workflow; ordinary notes move only files within the current workspace.',
6
+ NOTE_METADATA_PRINCIPAL_UNSUPPORTED: 'An existing project filing has a team, service-account, or unsupported access grant that this transfer cannot preserve. Inspect the source project grants and service-account grants. Do not remove access just to force the transfer.',
7
+ NOTE_METADATA_TRANSFER_DISABLED: 'The server has disabled Note ownership transfers. Updating the CLI alone cannot enable them.',
8
+ NOTE_METADATA_PRIVATE_REQUIRED: 'This transfer currently supports private Notes only. Review the existing audience before changing visibility.',
9
+ };
10
+ /** Report a failure without losing its machine-readable identity or claiming an
11
+ * uncertain write did not happen. Never include the raw response or arguments. */
12
+ export function reportCommandFailure(error, options) {
13
+ const http = error instanceof HttpError ? error : undefined;
14
+ const code = http?.code ?? 'command_failed';
15
+ recordOperationFailure(code, options.attempted && (!http || http.status >= 500) ? 'uncertain' : 'failed');
16
+ const nextAction = options.attempted
17
+ ? 'Inspect the exact saved request and operation before resubmitting; no mutation was retried.'
18
+ : guidance[code];
19
+ const message = error instanceof Error ? error.message : 'Command failed';
20
+ const reason = http?.details?.reason;
21
+ const safeReason = typeof reason === 'string' && ['grant_inventory_limit', 'team_project_grant', 'invalid_project_grant', 'service_account_project_grant'].includes(reason) ? reason : undefined;
22
+ if (options.json)
23
+ emitJson({ ok: false, error: {
24
+ code, message, ...(http ? { status: http.status } : {}),
25
+ ...(http?.retryable === undefined ? {} : { retryable: http.retryable }),
26
+ ...(http?.requestId ? { requestId: http.requestId } : {}),
27
+ ...(safeReason ? { reason: safeReason } : {}),
28
+ // This is dispatch state, not a claim about whether a remote write committed.
29
+ submissionAttempted: options.attempted,
30
+ ...(nextAction ? { nextAction } : {}),
31
+ } });
32
+ else
33
+ fail(`${message}${nextAction ? `\n${nextAction}` : ''}`);
34
+ }
@@ -1,3 +1,4 @@
1
+ import { recordOperationFailure } from '../telemetry.js';
1
2
  import { HttpError, requestJson } from "../client.js";
2
3
  import { resolveCtx } from "../compat/ctx.js";
3
4
  import { withConnFlags } from "../compat/flags.js";
@@ -82,6 +83,8 @@ export async function runNotesMove(ref, opts) {
82
83
  ? "Nothing changed. Repeat without --dry-run to apply; permissions and conflicts will be checked again.\n"
83
84
  : "Nothing changed. This destination cannot be applied by the current server.\n");
84
85
  }
86
+ if (!receipt.executable)
87
+ recordOperationFailure(receipt.blockers[0]?.code ?? 'note_move_blocked', 'blocked');
85
88
  return receipt.executable ? 0 : 3;
86
89
  }
87
90
  catch (error) {
@@ -90,6 +93,8 @@ export async function runNotesMove(ref, opts) {
90
93
  let status;
91
94
  if (error instanceof HttpError) {
92
95
  status = error.status;
96
+ if (error.code)
97
+ code = error.code;
93
98
  try {
94
99
  const body = JSON.parse(error.body);
95
100
  if (typeof body.error === "string")
@@ -99,6 +104,7 @@ export async function runNotesMove(ref, opts) {
99
104
  }
100
105
  catch { /* Preserve transport diagnostic. */ }
101
106
  }
107
+ recordOperationFailure(code, attempted && (status === undefined || status >= 500) ? 'uncertain' : 'failed');
102
108
  if (attempted && (status === undefined || status >= 500))
103
109
  message += "; the outcome may be uncertain: resolve the note by ID and inspect its workspace and projects before resubmitting; no retry was performed";
104
110
  if (opts.json)
@@ -226,6 +232,8 @@ export async function runNotesFolderMove(ref, opts) {
226
232
  let status = error.status;
227
233
  if (error instanceof HttpError) {
228
234
  status = error.status;
235
+ if (error.code)
236
+ code = error.code;
229
237
  try {
230
238
  const body = JSON.parse(error.body);
231
239
  if (typeof body.error === "string")
@@ -241,6 +249,7 @@ export async function runNotesFolderMove(ref, opts) {
241
249
  else if (status === 404)
242
250
  code = "not_found";
243
251
  }
252
+ recordOperationFailure(code, attempted && (status === undefined || status >= 500) ? 'uncertain' : 'failed');
244
253
  if (attempted && (status === undefined || status >= 500))
245
254
  message += `; the outcome may be uncertain: check \`dreamlake list --episode <project>@<namespace>\` before resubmitting; no retry was performed`;
246
255
  if (opts.json)
@@ -1,3 +1,4 @@
1
+ import { recordOperationFailure } from '../telemetry.js';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { readFileSync, writeFileSync } from 'node:fs';
3
4
  import { performance } from 'node:perf_hooks';
@@ -6,6 +7,7 @@ import { resolveCtx } from '../compat/ctx.js';
6
7
  import { withConnFlags } from '../compat/flags.js';
7
8
  import { fail } from '../helpers.js';
8
9
  import { emitProjectResult } from '../project/output.js';
10
+ import { reportCommandFailure } from '../failure-report.js';
9
11
  const adapters = { note: { capability: 'noteTransfer', label: 'Note' }, artifact: { capability: 'artifactTransfer', label: 'Artifact' }, env: { capability: 'envTransfer', label: 'Env/Scene' }, annotation: { capability: 'annotationTransfer', label: 'Annotation' }, pipeline: { capability: 'pipelineTransfer', label: 'Pipeline' }, source: { capability: 'sourceTransfer', label: 'Source' } };
10
12
  const id = (v) => typeof v === 'string' && /^[a-f0-9]{24}$/i.test(v);
11
13
  const text = (v) => typeof v === 'string' && !!v.trim();
@@ -99,6 +101,8 @@ export async function runMetadataTransfer(requestedType, resourceId, opts) {
99
101
  const review = { kind: `${type}-transfer`, source, destination, ready, plan, request, preview };
100
102
  if (opts.out)
101
103
  writeFileSync(opts.out, JSON.stringify(review, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
104
+ if (!ready)
105
+ recordOperationFailure(preview.blockers[0]?.code ?? 'transfer_preview_blocked', 'blocked');
102
106
  if (!opts.confirm || !ready) {
103
107
  emitProjectResult(review, () => `${adapter.label} ${resourceId}: ${source} → ${destination}: ${ready ? 'ready for review' : 'unavailable'}.\nMetadata only; IDs, content and history stay in place. Recipient acceptance is required.\n${preview.blockers.map(b => `${b.code}: ${b.action}`).join('\n')}\nNothing moved.`, opts.json);
104
108
  return ready ? 0 : 3;
@@ -135,7 +139,7 @@ export async function runMetadataTransfer(requestedType, resourceId, opts) {
135
139
  return failed.has(operation.state) ? 3 : 0;
136
140
  }
137
141
  catch (error) {
138
- fail(error.message + (attempted ? '; no mutation was retried. Inspect the exact saved request/operation before resubmitting' : ''));
142
+ reportCommandFailure(error, { json: opts.json, attempted });
139
143
  return 1;
140
144
  }
141
145
  }
@@ -15,9 +15,21 @@ export interface Completion {
15
15
  platform: string;
16
16
  exit_code: number;
17
17
  duration_ms: number;
18
+ last_http_status?: number;
19
+ last_http_error_code?: string;
20
+ operation_error_code?: string;
21
+ operation_outcome?: string;
18
22
  }
23
+ declare let operationFailure: Pick<Completion, 'operation_error_code' | 'operation_outcome'>;
24
+ export declare function operationFailureFields(code: unknown, outcome: unknown): typeof operationFailure;
25
+ export declare function recordOperationFailure(code: string, outcome: 'failed' | 'blocked' | 'partial' | 'uncertain'): void;
26
+ export declare function httpFailureFields(status: unknown, code: unknown): Pick<Completion, 'last_http_status' | 'last_http_error_code'>;
27
+ /** A handled HTTP failure is context, not necessarily the command's final cause.
28
+ * Never collect response bodies, error messages, URLs, arguments or credentials. */
29
+ export declare function recordHttpFailure(status: number, code?: string): void;
19
30
  /** Bind queued records to their original API and account, without storing a credential. */
20
31
  export declare function telemetryScope(remote: string, token: string): string;
21
32
  export declare function startCommandTelemetry(command: string): void;
22
33
  /** Retry in a detached process with a bounded lifetime. Each event triggers an attempt. */
23
34
  export declare function deliverTelemetry(scope: string): Promise<void>;
35
+ export {};
@@ -105,6 +105,34 @@ export function commandPath(command) {
105
105
  parts.unshift(current.name());
106
106
  return parts.join(' ');
107
107
  }
108
+ let operationFailure = {};
109
+ export function operationFailureFields(code, outcome) {
110
+ const machineCode = httpFailureFields(400, code).last_http_error_code;
111
+ return machineCode && typeof outcome === 'string' && ['failed', 'blocked', 'partial', 'uncertain'].includes(outcome) ? { operation_error_code: machineCode, operation_outcome: outcome } : {};
112
+ }
113
+ export function recordOperationFailure(code, outcome) {
114
+ try {
115
+ if (telemetryEnabled())
116
+ operationFailure = operationFailureFields(code, outcome);
117
+ }
118
+ catch { }
119
+ }
120
+ let lastHttpFailure = {};
121
+ export function httpFailureFields(status, code) {
122
+ if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599)
123
+ return {};
124
+ return { last_http_status: status,
125
+ ...(typeof code === 'string' && code.length <= 100 && /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/.test(code) ? { last_http_error_code: code } : {}) };
126
+ }
127
+ /** A handled HTTP failure is context, not necessarily the command's final cause.
128
+ * Never collect response bodies, error messages, URLs, arguments or credentials. */
129
+ export function recordHttpFailure(status, code) {
130
+ try {
131
+ if (telemetryEnabled())
132
+ lastHttpFailure = httpFailureFields(status, code);
133
+ }
134
+ catch { /* Reporting must not replace the original command failure. */ }
135
+ }
108
136
  function journal() { return new TelemetryJournal(path.join(dreamlakeDir(), 'telemetry-events')); }
109
137
  /** Bind queued records to their original API and account, without storing a credential. */
110
138
  export function telemetryScope(remote, token) {
@@ -140,6 +168,8 @@ function launchUpload(scope) {
140
168
  child.unref();
141
169
  }
142
170
  export function startCommandTelemetry(command) {
171
+ lastHttpFailure = {};
172
+ operationFailure = {};
143
173
  if (!telemetryEnabled()) {
144
174
  try {
145
175
  journal().clear();
@@ -172,7 +202,8 @@ export function startCommandTelemetry(command) {
172
202
  const event = { uuid: randomUUID(), timestamp: new Date().toISOString(), command, version: VERSION,
173
203
  platform: ['linux', 'darwin', 'win32'].includes(process.platform) ? process.platform : 'other',
174
204
  exit_code: Math.max(0, Math.min(255, code)),
175
- duration_ms: Math.min(604800000, Math.max(0, Math.round(performance.now() - start))) };
205
+ duration_ms: Math.min(604800000, Math.max(0, Math.round(performance.now() - start))),
206
+ ...(code === 0 ? {} : { ...lastHttpFailure, ...operationFailure }) };
176
207
  // Synchronous local commit is required here: Node cannot await exit handlers.
177
208
  journal().append(scope, event);
178
209
  launchUpload(scope);
@@ -239,7 +270,8 @@ export async function deliverTelemetry(scope) {
239
270
  const response = await fetch(`${target.remote}/telemetry/events`, {
240
271
  method: 'POST', redirect: 'error', signal: AbortSignal.timeout(Math.min(1500, Math.max(1, deadline - Date.now()))),
241
272
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${target.token}` },
242
- body: JSON.stringify({ uuid, timestamp, command, version, platform, exit_code, duration_ms }),
273
+ body: JSON.stringify({ uuid, timestamp, command, version, platform, exit_code, duration_ms,
274
+ ...(exit_code === 0 ? {} : { ...httpFailureFields(parsed.last_http_status, parsed.last_http_error_code), ...operationFailureFields(parsed.operation_error_code, parsed.operation_outcome) }) }),
243
275
  });
244
276
  await response.body?.cancel();
245
277
  if (response.status !== 204)
@@ -1 +1 @@
1
- export declare const VERSION = "0.104.4";
1
+ export declare const VERSION = "0.104.5";
@@ -6,4 +6,4 @@
6
6
  // value means a binary that re-installs the same version forever.
7
7
  //
8
8
  // Editing this by hand does nothing for a release; bump package.json.
9
- export const VERSION = "0.104.4";
9
+ export const VERSION = "0.104.5";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamlake/dreamlake-cli",
3
- "version": "0.104.4",
3
+ "version": "0.104.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
@@ -36,13 +36,13 @@
36
36
  "node": ">=18"
37
37
  },
38
38
  "optionalDependencies": {
39
- "@dreamlake/dreamlake-cli-darwin-arm64": "0.104.4",
40
- "@dreamlake/dreamlake-cli-darwin-x64": "0.104.4",
41
- "@dreamlake/dreamlake-cli-linux-x64": "0.104.4",
42
- "@dreamlake/dreamlake-cli-linux-arm64": "0.104.4",
43
- "@dreamlake/dreamlake-cli-linux-x64-musl": "0.104.4",
44
- "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.104.4",
45
- "@dreamlake/dreamlake-cli-win32-x64": "0.104.4",
46
- "@dreamlake/dreamlake-cli-win32-arm64": "0.104.4"
39
+ "@dreamlake/dreamlake-cli-darwin-arm64": "0.104.5",
40
+ "@dreamlake/dreamlake-cli-darwin-x64": "0.104.5",
41
+ "@dreamlake/dreamlake-cli-linux-x64": "0.104.5",
42
+ "@dreamlake/dreamlake-cli-linux-arm64": "0.104.5",
43
+ "@dreamlake/dreamlake-cli-linux-x64-musl": "0.104.5",
44
+ "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.104.5",
45
+ "@dreamlake/dreamlake-cli-win32-x64": "0.104.5",
46
+ "@dreamlake/dreamlake-cli-win32-arm64": "0.104.5"
47
47
  }
48
48
  }