@gaoding/cli 1.8.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/operations/agent.send/input.schema.json +1 -1
- package/contracts/operations/agent.send/output.schema.json +1 -1
- package/contracts/operations/model.get/input.schema.json +6 -0
- package/contracts/operations/model.get/output.schema.json +10 -1
- package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +42 -0
- package/contracts/operations/tool.call/models/image-edit-standard.schema.json +33 -0
- package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +27 -0
- package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +27 -0
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +76 -0
- package/contracts/operations/tool.call/models/image-expand-standard.schema.json +61 -0
- package/contracts/operations/tool.call/models/image-layers-layout.schema.json +21 -0
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +28 -0
- package/contracts/operations/tool.call/models/image-matting-smart.schema.json +37 -0
- package/contracts/operations/tool.call/models/image-matting-standard.schema.json +26 -0
- package/contracts/operations/tool.call/models/image-ocr.schema.json +21 -0
- package/contracts/operations/tool.call/models/image-remove-smart.schema.json +32 -0
- package/contracts/operations/tool.call/models/image-remove-standard.schema.json +27 -0
- package/contracts/operations/tool.call/models/image-text-edit.schema.json +46 -0
- package/contracts/operations/tool.call/models/image-vectorize.schema.json +21 -0
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +76 -0
- package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +33 -0
- package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +27 -0
- package/contracts/operations/tool.call/ocr-payload.schema.json +66 -0
- package/contracts/operations/tool.call/output.schema.json +38 -0
- package/contracts/operations/tool.call/template-payload.schema.json +96 -0
- package/dist/bin/gd-cli.js +31 -24
- package/dist/bin/insmind-cli.js +31 -24
- package/dist/bin/task-worker.js +4 -1
- package/dist/src/analytics/device.js +2 -2
- package/dist/src/bootstrap/create-cli.js +7 -0
- package/dist/src/bootstrap/create-runtime.js +53 -30
- package/dist/src/bootstrap/run-task-worker.js +5 -1
- package/dist/src/bootstrap/validators.js +11 -4
- package/dist/src/cli/agent-commands.js +1 -0
- package/dist/src/cli/dam-commands.js +3 -3
- package/dist/src/cli/errors.js +63 -15
- package/dist/src/cli/model-commands.js +6 -3
- package/dist/src/cli/observed-errors.js +3 -1
- package/dist/src/cli/tool-commands.js +2 -0
- package/dist/src/contracts/schema.js +4 -1
- package/dist/src/features/agent/creative-agent-adapter.js +37 -11
- package/dist/src/features/agent/creative-protocol.js +31 -10
- package/dist/src/features/agent/creative-stream.js +54 -6
- package/dist/src/features/agent/resource-authorizer.js +1 -0
- package/dist/src/features/agent/result-reader.js +3 -1
- package/dist/src/features/agent/use-cases.js +15 -5
- package/dist/src/features/auth/credential-store.js +6 -10
- package/dist/src/features/auth/sso-service.js +22 -6
- package/dist/src/features/auth/state.js +6 -0
- package/dist/src/features/auth/use-cases.js +90 -32
- package/dist/src/features/dam/asset-projection.js +10 -1
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/input.js +23 -0
- package/dist/src/features/dam/use-cases.js +32 -22
- package/dist/src/features/task/store.js +5 -5
- package/dist/src/features/task/task-background.js +67 -19
- package/dist/src/features/task/use-cases.js +38 -9
- package/dist/src/features/tool/canvas-copy.js +61 -0
- package/dist/src/features/tool/canvas-media.js +248 -0
- package/dist/src/features/tool/canvas-models.js +109 -0
- package/dist/src/features/tool/canvas-pricing.js +81 -0
- package/dist/src/features/tool/canvas-recovery.js +68 -0
- package/dist/src/features/tool/canvas-results.js +144 -0
- package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
- package/dist/src/features/tool/canvas-video.js +84 -0
- package/dist/src/features/tool/catalog.js +35 -13
- package/dist/src/features/tool/dynamic-schema.js +55 -25
- package/dist/src/features/tool/matting-billing.js +115 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
- package/dist/src/features/tool/resource-authorizer.js +34 -0
- package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
- package/dist/src/features/tool/tool-api-adapter.js +29 -17
- package/dist/src/features/tool/use-cases.js +28 -3
- package/dist/src/platform/file-lock.js +58 -15
- package/dist/src/platform/input-uri.js +105 -0
- package/dist/src/platform/local-json-file.js +7 -4
- package/dist/src/platform/remote-error-evidence.js +23 -1
- package/dist/src/platform/safe-upload-file.js +18 -4
- package/dist/src/platform/schema-issues.js +18 -0
- package/dist/src/platform/signed-http-transport.js +77 -16
- package/dist/src/platform/text-output.js +55 -13
- package/dist/src/product/config.js +12 -1
- package/dist/src/telemetry/failure-summary.js +53 -2
- package/dist/src/telemetry/host-diagnostics.js +95 -0
- package/dist/src/telemetry/invocation.js +24 -3
- package/dist/src/telemetry/process-errors.js +2 -1
- package/dist/src/telemetry/sls-sink.js +66 -18
- package/package.json +5 -4
- package/skills/gd-cli/SKILL.md +2 -0
- package/skills/gd-cli/references/creation.md +2 -0
- package/skills/gd-cli/references/generation-constraints.md +3 -1
- package/skills/gd-cli/references/matting.md +29 -0
- package/skills/gd-cli/references/media-tools.md +40 -0
- package/skills/gd-cli/references/tool.md +4 -4
|
@@ -203,8 +203,25 @@ function inferMediaType(url) {
|
|
|
203
203
|
webp: "image/webp"
|
|
204
204
|
}[extension ?? ""] ?? "application/octet-stream";
|
|
205
205
|
}
|
|
206
|
-
function
|
|
207
|
-
|
|
206
|
+
function isBillingMetadataText(text, message) {
|
|
207
|
+
if (message.role !== "function")
|
|
208
|
+
return false;
|
|
209
|
+
const extra = record(message.extra);
|
|
210
|
+
const amount = extra?.deduct_points;
|
|
211
|
+
if (nonEmptyString(extra?.task_id) === undefined
|
|
212
|
+
|| nonEmptyString(extra?.scene_code) === undefined
|
|
213
|
+
|| typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
|
|
214
|
+
return false;
|
|
215
|
+
// The Agent appends this exact metadata mirror as tool text. Require matching
|
|
216
|
+
// structured billing evidence; ordinary JSON and assistant text remain intact.
|
|
217
|
+
const fields = record(parseJson(text));
|
|
218
|
+
return fields !== undefined && Object.keys(fields).length === 2
|
|
219
|
+
&& fields.deduct_points === amount
|
|
220
|
+
&& typeof fields.balance_points === "number"
|
|
221
|
+
&& Number.isFinite(fields.balance_points) && fields.balance_points >= 0;
|
|
222
|
+
}
|
|
223
|
+
function functionResponseParts(message) {
|
|
224
|
+
const parsed = parseJson(contentOf(message)?.text);
|
|
208
225
|
const values = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];
|
|
209
226
|
const parts = [];
|
|
210
227
|
for (const value of values) {
|
|
@@ -212,7 +229,7 @@ function functionResponseParts(raw) {
|
|
|
212
229
|
if (item === undefined)
|
|
213
230
|
continue;
|
|
214
231
|
const text = nonEmptyString(item.text);
|
|
215
|
-
if (text !== undefined)
|
|
232
|
+
if (text !== undefined && !isBillingMetadataText(text, message))
|
|
216
233
|
parts.push({ text });
|
|
217
234
|
const url = nonEmptyString(item.uri ?? item.url);
|
|
218
235
|
if (url === undefined)
|
|
@@ -255,7 +272,7 @@ export function restoreCreativeResourceUrls(messages, streamed) {
|
|
|
255
272
|
const content = contentOf(message);
|
|
256
273
|
if (content?.type !== "function_response")
|
|
257
274
|
continue;
|
|
258
|
-
for (const part of functionResponseParts(
|
|
275
|
+
for (const part of functionResponseParts(message)) {
|
|
259
276
|
if (!("url" in part) || !hasAuthKey(part.url))
|
|
260
277
|
continue;
|
|
261
278
|
const identity = resourceUrlIdentity(part.url);
|
|
@@ -378,7 +395,7 @@ function dedupeParts(parts) {
|
|
|
378
395
|
return true;
|
|
379
396
|
});
|
|
380
397
|
}
|
|
381
|
-
export function normalizeCreativeMessages(messages) {
|
|
398
|
+
export function normalizeCreativeMessages(messages, onUsageModelMissing) {
|
|
382
399
|
const contextId = creativeContextId(messages);
|
|
383
400
|
const latest = new Map();
|
|
384
401
|
const anonymous = [];
|
|
@@ -402,7 +419,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
402
419
|
parts.push({ text });
|
|
403
420
|
}
|
|
404
421
|
else if (content.type === "function_response") {
|
|
405
|
-
parts.push(...functionResponseParts(
|
|
422
|
+
parts.push(...functionResponseParts(message));
|
|
406
423
|
}
|
|
407
424
|
}
|
|
408
425
|
else {
|
|
@@ -423,6 +440,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
423
440
|
if (publicParts.length === 0)
|
|
424
441
|
return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
|
|
425
442
|
const usageItems = [];
|
|
443
|
+
let totalCost = 0;
|
|
426
444
|
for (const message of normalized) {
|
|
427
445
|
if (contentOf(message)?.type !== "function_response")
|
|
428
446
|
continue;
|
|
@@ -432,11 +450,14 @@ export function normalizeCreativeMessages(messages) {
|
|
|
432
450
|
continue;
|
|
433
451
|
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
|
|
434
452
|
return fail();
|
|
453
|
+
totalCost += amount;
|
|
454
|
+
const model = nonEmptyString(extra?.scene_code);
|
|
455
|
+
if (model === undefined) {
|
|
456
|
+
onUsageModelMissing?.();
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
435
459
|
if (amount === 0)
|
|
436
460
|
continue;
|
|
437
|
-
const model = nonEmptyString(extra?.scene_code);
|
|
438
|
-
if (model === undefined)
|
|
439
|
-
return fail("AGENT_USAGE_MODEL_MISSING", { messageCount: normalized.length, publicPartCount: publicParts.length });
|
|
440
461
|
usageItems.push({ model, cost: { unit: "gaodou", amount } });
|
|
441
462
|
}
|
|
442
463
|
return {
|
|
@@ -448,7 +469,7 @@ export function normalizeCreativeMessages(messages) {
|
|
|
448
469
|
usage: {
|
|
449
470
|
cost: {
|
|
450
471
|
unit: "gaodou",
|
|
451
|
-
amount:
|
|
472
|
+
amount: totalCost
|
|
452
473
|
},
|
|
453
474
|
items: usageItems
|
|
454
475
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
2
3
|
function isMessage(value) {
|
|
3
4
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
5
|
}
|
|
@@ -87,12 +88,24 @@ function parseSequence(payload) {
|
|
|
87
88
|
}
|
|
88
89
|
return values;
|
|
89
90
|
}
|
|
90
|
-
export async function parseCreativeStream(stream, signal, onContextId) {
|
|
91
|
+
export async function parseCreativeStream(stream, signal, onContextId, diagnostics = {}) {
|
|
91
92
|
signal.throwIfAborted();
|
|
92
93
|
const reader = stream.getReader();
|
|
93
94
|
const decoder = new TextDecoder();
|
|
94
95
|
let raw = "";
|
|
95
96
|
let contextReported = false;
|
|
97
|
+
const now = diagnostics.now ?? Date.now;
|
|
98
|
+
const startedAt = diagnostics.startedAt ?? now();
|
|
99
|
+
let receivedBytes = 0;
|
|
100
|
+
let firstByteMs;
|
|
101
|
+
let terminalReason = "canceled";
|
|
102
|
+
const summary = () => ({
|
|
103
|
+
streamHadBytes: receivedBytes > 0,
|
|
104
|
+
streamReceivedBytes: receivedBytes,
|
|
105
|
+
...(firstByteMs === undefined ? {} : { streamFirstByteMs: firstByteMs }),
|
|
106
|
+
streamTerminalReason: terminalReason,
|
|
107
|
+
abortSource: signal.aborted ? "caller" : "none"
|
|
108
|
+
});
|
|
96
109
|
const onAbort = () => {
|
|
97
110
|
void reader.cancel(signal.reason).catch(() => undefined);
|
|
98
111
|
};
|
|
@@ -100,10 +113,25 @@ export async function parseCreativeStream(stream, signal, onContextId) {
|
|
|
100
113
|
try {
|
|
101
114
|
while (true) {
|
|
102
115
|
signal.throwIfAborted();
|
|
103
|
-
|
|
116
|
+
let result;
|
|
117
|
+
try {
|
|
118
|
+
result = await reader.read();
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (signal.aborted)
|
|
122
|
+
throw signal.reason;
|
|
123
|
+
terminalReason = "error";
|
|
124
|
+
throw new RemoteRequestError(diagnostics.httpStatus, false, {}, error, "AGENT_STREAM_READ_FAILED", summary());
|
|
125
|
+
}
|
|
126
|
+
if (!result.done && result.value.byteLength) {
|
|
127
|
+
receivedBytes = Math.min(Number.MAX_SAFE_INTEGER, receivedBytes + result.value.byteLength);
|
|
128
|
+
firstByteMs ??= Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now() - startedAt));
|
|
129
|
+
}
|
|
104
130
|
signal.throwIfAborted();
|
|
105
|
-
if (result.done)
|
|
131
|
+
if (result.done) {
|
|
132
|
+
terminalReason = "eof";
|
|
106
133
|
break;
|
|
134
|
+
}
|
|
107
135
|
raw += decoder.decode(result.value, { stream: true });
|
|
108
136
|
if (onContextId && !contextReported) {
|
|
109
137
|
const contextId = messagesFrom(raw).find(message => typeof message.thread_id === "string" && message.thread_id)?.thread_id;
|
|
@@ -115,16 +143,36 @@ export async function parseCreativeStream(stream, signal, onContextId) {
|
|
|
115
143
|
}
|
|
116
144
|
raw += decoder.decode();
|
|
117
145
|
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
try {
|
|
148
|
+
if (error instanceof Error && Object.isExtensible(error)) {
|
|
149
|
+
const previous = error.diagnosticSummary;
|
|
150
|
+
Object.assign(error, { diagnosticSummary: {
|
|
151
|
+
...(previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {}), ...summary()
|
|
152
|
+
} });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch { /* Diagnostic attachment cannot replace the original failure. */ }
|
|
156
|
+
if (terminalReason === "canceled")
|
|
157
|
+
void reader.cancel(error).catch(() => undefined);
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
118
160
|
finally {
|
|
119
161
|
signal.removeEventListener("abort", onAbort);
|
|
120
162
|
reader.releaseLock();
|
|
163
|
+
try {
|
|
164
|
+
diagnostics.onDiagnostics?.(summary());
|
|
165
|
+
}
|
|
166
|
+
catch { /* Diagnostics cannot replace a result or primary error. */ }
|
|
121
167
|
}
|
|
122
168
|
const messages = messagesFrom(raw);
|
|
123
169
|
if (messages.length === 0) {
|
|
124
170
|
const payloads = extractPayloads(raw);
|
|
125
|
-
throw new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
|
|
126
|
-
|
|
127
|
-
streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING")
|
|
171
|
+
throw Object.assign(new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
|
|
172
|
+
...summary(), streamPayloadCount: Math.min(payloads.length, 100_000),
|
|
173
|
+
streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING"), {
|
|
174
|
+
...(diagnostics.httpStatus === undefined ? {} : { status: diagnostics.httpStatus }), diagnosticSummary: summary()
|
|
175
|
+
});
|
|
128
176
|
}
|
|
129
177
|
return messages;
|
|
130
178
|
}
|
|
@@ -8,6 +8,7 @@ function unsignedPrivateUrl(value) {
|
|
|
8
8
|
throw new RemoteProtocolError();
|
|
9
9
|
}
|
|
10
10
|
const isPrivate = /^gd-ai-[a-z0-9-]+\.dancf\.com$/iu.test(url.hostname)
|
|
11
|
+
|| /^gdesign-dam(?:-[a-z0-9-]+)?\.dancf\.com$/iu.test(url.hostname)
|
|
11
12
|
|| url.hostname === "dify-grsai.dancf.com"
|
|
12
13
|
|| url.hostname === "dify-aiznt.dancf.com";
|
|
13
14
|
if (!isPrivate || url.searchParams.get("auth_key")?.trim())
|
|
@@ -20,7 +20,9 @@ export async function readAgentResult(transport, request) {
|
|
|
20
20
|
if (!turn.some(m => m.role !== "user" && m.content))
|
|
21
21
|
return { connectionState: connection.state };
|
|
22
22
|
try {
|
|
23
|
-
|
|
23
|
+
let usageModelMissing = false;
|
|
24
|
+
const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; });
|
|
25
|
+
return { connectionState: connection.state, partialResult, ...(usageModelMissing ? { usageModelMissing: true } : {}) };
|
|
24
26
|
}
|
|
25
27
|
catch (error) {
|
|
26
28
|
if (error instanceof RemoteProtocolError)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findModel, ToolInputError } from "../tool/catalog.js";
|
|
2
2
|
import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
|
|
3
|
+
import { canvasRemoteControlArguments } from "../tool/canvas-models.js";
|
|
3
4
|
import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
4
5
|
export class AgentInputError extends Error {
|
|
5
6
|
reason;
|
|
@@ -50,6 +51,7 @@ export function createAgentUseCases(dependencies) {
|
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
if (generation?.model !== undefined) {
|
|
54
|
+
const requested = generation;
|
|
53
55
|
dependencies.telemetry.annotate({ model_id: generation.model });
|
|
54
56
|
const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
|
|
55
57
|
signal.throwIfAborted();
|
|
@@ -60,15 +62,23 @@ export function createAgentUseCases(dependencies) {
|
|
|
60
62
|
await dependencies.telemetry.stage("input", async () => {
|
|
61
63
|
let model;
|
|
62
64
|
try {
|
|
63
|
-
model = findModel(catalog,
|
|
65
|
+
model = findModel(catalog, requested.model);
|
|
64
66
|
}
|
|
65
67
|
catch (error) {
|
|
66
68
|
if (error instanceof ToolInputError)
|
|
67
69
|
throw new AgentInputError(error.reason, "/generation/model", error);
|
|
68
70
|
throw error;
|
|
69
71
|
}
|
|
70
|
-
if (!modelControlArgumentsAreValid(model,
|
|
72
|
+
if (!modelControlArgumentsAreValid(model, requested.arguments ?? {}))
|
|
71
73
|
throw new AgentInputError("model_parameters", "/generation/arguments");
|
|
74
|
+
if (model.execution?.kind === "canvas") {
|
|
75
|
+
generation = {
|
|
76
|
+
model: model.execution.code,
|
|
77
|
+
...(requested.arguments === undefined ? {} : {
|
|
78
|
+
arguments: canvasRemoteControlArguments(model.model, requested.arguments)
|
|
79
|
+
})
|
|
80
|
+
};
|
|
81
|
+
}
|
|
72
82
|
});
|
|
73
83
|
}
|
|
74
84
|
const prepare = async () => {
|
|
@@ -128,10 +138,10 @@ export function createAgentUseCases(dependencies) {
|
|
|
128
138
|
prepared.push({
|
|
129
139
|
kind: "generation",
|
|
130
140
|
data: {
|
|
131
|
-
...(
|
|
132
|
-
...(
|
|
141
|
+
...(generation?.model === undefined ? {} : { model: generation.model }),
|
|
142
|
+
...(generation?.arguments === undefined
|
|
133
143
|
? {}
|
|
134
|
-
: { arguments: { ...
|
|
144
|
+
: { arguments: { ...generation.arguments } })
|
|
135
145
|
}
|
|
136
146
|
});
|
|
137
147
|
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { createLocalJsonFile } from "../../platform/local-json-file.js";
|
|
4
|
-
import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
|
|
4
|
+
import { AuthStateInvalidError, AuthStateUnavailableError, parseStoredAuthState } from "./state.js";
|
|
5
5
|
export function createLocalCredentialStore(options = {}) {
|
|
6
6
|
const file = options.file ?? createLocalJsonFile({
|
|
7
7
|
directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
|
|
8
|
-
filename: "credentials.json"
|
|
8
|
+
filename: "credentials.json",
|
|
9
|
+
role: "credentials"
|
|
9
10
|
});
|
|
10
11
|
return {
|
|
11
12
|
async read() {
|
|
@@ -28,7 +29,7 @@ export function createLocalCredentialStore(options = {}) {
|
|
|
28
29
|
catch (cause) {
|
|
29
30
|
if (cause instanceof AuthStateInvalidError)
|
|
30
31
|
throw cause;
|
|
31
|
-
throw
|
|
32
|
+
throw new AuthStateUnavailableError({ cause });
|
|
32
33
|
}
|
|
33
34
|
},
|
|
34
35
|
async write(state) {
|
|
@@ -39,7 +40,7 @@ export function createLocalCredentialStore(options = {}) {
|
|
|
39
40
|
catch (cause) {
|
|
40
41
|
if (cause instanceof AuthStateInvalidError)
|
|
41
42
|
throw cause;
|
|
42
|
-
throw
|
|
43
|
+
throw new AuthStateUnavailableError({ cause });
|
|
43
44
|
}
|
|
44
45
|
},
|
|
45
46
|
async remove() {
|
|
@@ -47,7 +48,7 @@ export function createLocalCredentialStore(options = {}) {
|
|
|
47
48
|
await file.remove();
|
|
48
49
|
}
|
|
49
50
|
catch (cause) {
|
|
50
|
-
throw
|
|
51
|
+
throw new AuthStateUnavailableError({ cause });
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
54
|
};
|
|
@@ -55,8 +56,3 @@ export function createLocalCredentialStore(options = {}) {
|
|
|
55
56
|
function serialize(state) {
|
|
56
57
|
return `${JSON.stringify(state, null, 2)}\n`;
|
|
57
58
|
}
|
|
58
|
-
function invalidState(cause) {
|
|
59
|
-
return new AuthStateInvalidError({
|
|
60
|
-
cause, reason: "local_io"
|
|
61
|
-
});
|
|
62
|
-
}
|
|
@@ -35,6 +35,15 @@ export function createSsoService(options) {
|
|
|
35
35
|
if (!baseUrl.pathname.endsWith("/"))
|
|
36
36
|
baseUrl.pathname += "/";
|
|
37
37
|
const requests = new WeakMap();
|
|
38
|
+
const requestStartedAt = new WeakMap();
|
|
39
|
+
function responseDiagnostics(response) {
|
|
40
|
+
const requestId = ["x-request-id", "x-gd-request-id", "request-id"].map(key => response.headers.get(key))
|
|
41
|
+
.find((value) => value !== null && /^[A-Za-z0-9_.:-]{1,128}$/u.test(value));
|
|
42
|
+
const startedAt = requestStartedAt.get(response);
|
|
43
|
+
return { requestTimeoutMs: options.timeoutMs ?? 30_000,
|
|
44
|
+
...(startedAt === undefined ? {} : { requestDurationMs: Math.max(0, Date.now() - startedAt) }),
|
|
45
|
+
...(requestId ? { requestId } : {}) };
|
|
46
|
+
}
|
|
38
47
|
async function responseError(response, networkError) {
|
|
39
48
|
let evidence = {};
|
|
40
49
|
if (!response.ok && !response.bodyUsed) {
|
|
@@ -51,16 +60,16 @@ export function createSsoService(options) {
|
|
|
51
60
|
...remoteErrorEvidence({ request: requests.get(response),
|
|
52
61
|
...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
|
|
53
62
|
...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
|
|
54
|
-
}, networkError);
|
|
63
|
+
}, networkError, responseDiagnostics(response));
|
|
55
64
|
}
|
|
56
65
|
function invalidFields(response, phase, fields) {
|
|
57
|
-
return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
|
|
66
|
+
return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ...responseDiagnostics(response), ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
|
|
58
67
|
}
|
|
59
68
|
async function responseRecord(response) {
|
|
60
69
|
if (!response.ok) {
|
|
61
|
-
// OAuth
|
|
70
|
+
// OAuth polling states can use HTTP 400 as well as HTTP 200.
|
|
62
71
|
const body = await response.clone().json().catch(() => undefined);
|
|
63
|
-
if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
|
|
72
|
+
if (isRecord(body) && ["authorization_pending", "slow_down", "expired_token"].includes(String(body.error).toLowerCase()))
|
|
64
73
|
return body;
|
|
65
74
|
throw await responseError(response);
|
|
66
75
|
}
|
|
@@ -78,22 +87,27 @@ export function createSsoService(options) {
|
|
|
78
87
|
signal.throwIfAborted();
|
|
79
88
|
const url = new URL(relativeUrl, baseUrl);
|
|
80
89
|
const requestInfo = { method, path: url.pathname };
|
|
90
|
+
const startedAt = Date.now();
|
|
91
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
92
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
81
93
|
try {
|
|
82
94
|
const response = await options.fetch(url, {
|
|
83
95
|
method,
|
|
84
96
|
headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
|
|
85
97
|
signal: AbortSignal.any([
|
|
86
98
|
signal,
|
|
87
|
-
|
|
99
|
+
timeoutSignal
|
|
88
100
|
])
|
|
89
101
|
});
|
|
90
102
|
requests.set(response, requestInfo);
|
|
103
|
+
requestStartedAt.set(response, startedAt);
|
|
91
104
|
return response;
|
|
92
105
|
}
|
|
93
106
|
catch (error) {
|
|
94
107
|
if (isInterruption(error, signal))
|
|
95
108
|
throw signal.reason;
|
|
96
|
-
throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error)
|
|
109
|
+
throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error, { requestTimeoutMs: timeoutMs, requestDurationMs: Math.max(0, Date.now() - startedAt),
|
|
110
|
+
abortSource: timeoutSignal.aborted ? "request_timeout" : "none" });
|
|
97
111
|
}
|
|
98
112
|
}
|
|
99
113
|
return {
|
|
@@ -126,6 +140,8 @@ export function createSsoService(options) {
|
|
|
126
140
|
return { status: "pending" };
|
|
127
141
|
if (error === "slow_down")
|
|
128
142
|
return { status: "slow_down" };
|
|
143
|
+
if (error === "expired_token")
|
|
144
|
+
return { status: "expired", httpStatus: response.status };
|
|
129
145
|
if (!response.ok)
|
|
130
146
|
throw await responseError(response);
|
|
131
147
|
const accessKey = nonEmptyString(body.ak);
|
|
@@ -6,6 +6,12 @@ export class AuthStateInvalidError extends Error {
|
|
|
6
6
|
this.reason = options?.reason ?? "invalid_data";
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
+
export class AuthStateUnavailableError extends Error {
|
|
10
|
+
constructor(options) {
|
|
11
|
+
super("无法访问本地登录状态,登录有效性未知。", options);
|
|
12
|
+
this.name = "AuthStateUnavailableError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
9
15
|
export function parseStoredAuthState(value) {
|
|
10
16
|
try {
|
|
11
17
|
if (!isRecord(value))
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { isInterruption } from "../../platform/interruption.js";
|
|
2
2
|
import { requireUserIdentity, UserIdentityMissingError } from "./state.js";
|
|
3
|
+
const AUTHORIZATION_WAIT_TIMEOUT_MS = 10 * 60 * 1000;
|
|
3
4
|
export class DeviceAuthorizationExpiredError extends Error {
|
|
4
|
-
|
|
5
|
+
expirationSource;
|
|
6
|
+
httpStatus;
|
|
7
|
+
constructor(commandName = "gd-cli", expirationSource = "cli_timeout", httpStatus) {
|
|
5
8
|
super(`Authorization expired. Run ${commandName} auth login again.`);
|
|
9
|
+
this.expirationSource = expirationSource;
|
|
10
|
+
this.httpStatus = httpStatus;
|
|
6
11
|
this.name = "DeviceAuthorizationExpiredError";
|
|
7
12
|
}
|
|
8
13
|
}
|
|
@@ -78,44 +83,97 @@ export function createAuthUseCases(dependencies) {
|
|
|
78
83
|
organizationSelected: existing.organization !== undefined
|
|
79
84
|
};
|
|
80
85
|
}
|
|
86
|
+
const authorizationStartedAt = dependencies.now().getTime();
|
|
87
|
+
const deadline = authorizationStartedAt + AUTHORIZATION_WAIT_TIMEOUT_MS;
|
|
88
|
+
const deadlineController = new AbortController();
|
|
89
|
+
const authorizationSignal = AbortSignal.any([input.signal, deadlineController.signal]);
|
|
90
|
+
const deadlineTimer = setTimeout(() => deadlineController.abort(new DeviceAuthorizationExpiredError(dependencies.commandName)), AUTHORIZATION_WAIT_TIMEOUT_MS);
|
|
91
|
+
const withinAuthorization = (run) => {
|
|
92
|
+
if (dependencies.now().getTime() >= deadline)
|
|
93
|
+
return Promise.reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
|
|
94
|
+
if (authorizationSignal.aborted)
|
|
95
|
+
return Promise.reject(authorizationSignal.reason);
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const abort = () => reject(authorizationSignal.reason);
|
|
98
|
+
authorizationSignal.addEventListener("abort", abort, { once: true });
|
|
99
|
+
Promise.resolve().then(() => { authorizationSignal.throwIfAborted(); return run(); }).then(result => {
|
|
100
|
+
if (dependencies.now().getTime() > deadline)
|
|
101
|
+
reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
|
|
102
|
+
else
|
|
103
|
+
resolve(result);
|
|
104
|
+
}, reject).finally(() => authorizationSignal.removeEventListener("abort", abort));
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
let pollCount = 0;
|
|
108
|
+
dependencies.telemetry.annotate({ auth_started_at_ms: authorizationStartedAt,
|
|
109
|
+
auth_wait_timeout_ms: AUTHORIZATION_WAIT_TIMEOUT_MS, auth_deadline_at_ms: deadline });
|
|
110
|
+
const recordResult = (result) => {
|
|
111
|
+
clearTimeout(deadlineTimer);
|
|
112
|
+
dependencies.telemetry.annotate({ auth_result: result,
|
|
113
|
+
auth_elapsed_ms: Math.max(0, dependencies.now().getTime() - authorizationStartedAt), auth_poll_count: pollCount });
|
|
114
|
+
};
|
|
115
|
+
const recordFailure = (cause) => {
|
|
116
|
+
recordResult(isInterruption(cause, input.signal) ? "interrupted"
|
|
117
|
+
: cause instanceof DeviceAuthorizationExpiredError ? cause.expirationSource : "failed");
|
|
118
|
+
throw cause;
|
|
119
|
+
};
|
|
81
120
|
const authorization = await dependencies.telemetry.stage("authorize", async () => {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
121
|
+
try {
|
|
122
|
+
const authorization = await withinAuthorization(() => dependencies.sso.startDeviceAuthorization(authorizationSignal));
|
|
123
|
+
dependencies.telemetry.annotate({ auth_server_expires_in_s: authorization.expiresInSeconds });
|
|
124
|
+
const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
|
|
125
|
+
authorizationUrl.searchParams.set("code", authorization.authorizeCode);
|
|
126
|
+
await withinAuthorization(() => input.interaction.showAuthorization(authorizationUrl));
|
|
127
|
+
if (!input.noBrowser) {
|
|
128
|
+
try {
|
|
129
|
+
await dependencies.telemetry.stage("browser", () => withinAuthorization(() => input.interaction.openBrowser(authorizationUrl)));
|
|
130
|
+
}
|
|
131
|
+
catch (cause) {
|
|
132
|
+
if (isInterruption(cause, input.signal))
|
|
133
|
+
throw input.signal.reason;
|
|
134
|
+
if (cause instanceof DeviceAuthorizationExpiredError)
|
|
135
|
+
throw cause;
|
|
136
|
+
if (input.requireBrowser)
|
|
137
|
+
throw new BrowserOpenError(cause);
|
|
138
|
+
input.interaction.warn(insmind
|
|
139
|
+
? "Could not open the browser. Open the authorization URL manually."
|
|
140
|
+
: "无法自动打开浏览器,请手动访问授权链接。");
|
|
141
|
+
}
|
|
98
142
|
}
|
|
143
|
+
return authorization;
|
|
144
|
+
}
|
|
145
|
+
catch (cause) {
|
|
146
|
+
return recordFailure(cause);
|
|
99
147
|
}
|
|
100
|
-
return authorization;
|
|
101
148
|
});
|
|
102
|
-
const deadline = dependencies.now().getTime() + authorization.expiresInSeconds * 1000;
|
|
103
149
|
let interval = authorization.intervalSeconds * 1000;
|
|
104
150
|
const token = await dependencies.telemetry.stage("wait", async () => {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
151
|
+
try {
|
|
152
|
+
while (dependencies.now().getTime() < deadline) {
|
|
153
|
+
const remaining = deadline - dependencies.now().getTime();
|
|
154
|
+
await withinAuthorization(() => dependencies.sleep(Math.min(interval, remaining), authorizationSignal));
|
|
155
|
+
input.signal.throwIfAborted();
|
|
156
|
+
// Wait through the deadline without polling faster than the server permits.
|
|
157
|
+
if (remaining < interval || dependencies.now().getTime() >= deadline)
|
|
158
|
+
break;
|
|
159
|
+
pollCount += 1;
|
|
160
|
+
const result = await withinAuthorization(() => dependencies.sso.pollDeviceToken(authorization.deviceCode, authorizationSignal));
|
|
161
|
+
if (result.status === "pending")
|
|
162
|
+
continue;
|
|
163
|
+
if (result.status === "slow_down") {
|
|
164
|
+
interval += 5_000;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (result.status === "expired") {
|
|
168
|
+
throw new DeviceAuthorizationExpiredError(dependencies.commandName, "server_expired", result.httpStatus);
|
|
169
|
+
}
|
|
170
|
+
recordResult("authorized");
|
|
171
|
+
return result;
|
|
108
172
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
continue;
|
|
114
|
-
if (result.status === "slow_down") {
|
|
115
|
-
interval += 5_000;
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
return result;
|
|
173
|
+
throw new DeviceAuthorizationExpiredError(dependencies.commandName);
|
|
174
|
+
}
|
|
175
|
+
catch (cause) {
|
|
176
|
+
return recordFailure(cause);
|
|
119
177
|
}
|
|
120
178
|
});
|
|
121
179
|
let state = {
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { isSensitiveKey } from "../../platform/redact.js";
|
|
2
2
|
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
3
|
+
const sourcePresence = new WeakMap();
|
|
4
|
+
/** Internal presence evidence survives public URL safety filtering without exposing the URL. */
|
|
5
|
+
export function damAssetSourcePresent(asset) {
|
|
6
|
+
return sourcePresence.get(asset) ?? (typeof asset.url === "string" && asset.url.trim() !== "");
|
|
7
|
+
}
|
|
3
8
|
const publicAssetTypes = new Set([
|
|
4
9
|
"image",
|
|
5
10
|
"video",
|
|
@@ -230,7 +235,7 @@ export function projectDamAssetDetail(value, fallback) {
|
|
|
230
235
|
const asset = normalizeAsset(value, fallback);
|
|
231
236
|
if (asset === undefined)
|
|
232
237
|
return undefined;
|
|
233
|
-
|
|
238
|
+
const result = compact({
|
|
234
239
|
asset_id: asset.asset_id,
|
|
235
240
|
title: asset.title,
|
|
236
241
|
description: asset.description,
|
|
@@ -251,6 +256,10 @@ export function projectDamAssetDetail(value, fallback) {
|
|
|
251
256
|
created_at: asset.created_at,
|
|
252
257
|
updated_at: asset.updated_at
|
|
253
258
|
});
|
|
259
|
+
const item = findAssetRecord(value);
|
|
260
|
+
const origin = record(item?.origin_info) ?? record(item?.originInfo);
|
|
261
|
+
sourcePresence.set(result, [origin?.url, item?.origin_url, item?.url].some(value => nonblank(value) !== undefined));
|
|
262
|
+
return result;
|
|
254
263
|
}
|
|
255
264
|
export function projectDamAssetSummary(value) {
|
|
256
265
|
const asset = normalizeAsset(value);
|