@promptframe/creation 0.3.9 → 0.3.10

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.
@@ -9,7 +9,7 @@
9
9
  "source": {
10
10
  "source": "npm",
11
11
  "package": "@promptframe/creation",
12
- "version": "0.3.9",
12
+ "version": "0.3.10",
13
13
  "registry": "https://registry.npmjs.org/"
14
14
  },
15
15
  "policy": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptframe-creation",
3
- "version": "0.3.9",
3
+ "version": "0.3.10",
4
4
  "description": "通过 PromptFrame 的共用工具、作品和任务创作视频。",
5
5
  "author": {
6
6
  "name": "PromptFrame"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptframe-creation",
3
- "version": "0.3.9",
3
+ "version": "0.3.10",
4
4
  "description": "使用自己的推理,通过 PromptFrame 的共用工具、作品和任务创作视频。",
5
5
  "author": {
6
6
  "name": "PromptFrame"
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  <!-- creation-install-command -->
10
10
  ```bash
11
- npx --yes @promptframe/creation@0.3.9 connect --endpoint <Studio提供的API地址>
11
+ npx --yes @promptframe/creation@0.3.10 connect --endpoint <Studio提供的API地址>
12
12
  ```
13
13
  <!-- /creation-install-command -->
14
14
 
package/dist/cli.mjs CHANGED
@@ -7519,12 +7519,56 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7519
7519
  // lib/local-upload-transfer.mjs
7520
7520
  import { Readable as Readable2 } from "node:stream";
7521
7521
  import { finished as finished2 } from "node:stream/promises";
7522
+ import { performance as performance2 } from "node:perf_hooks";
7522
7523
  var fail = (code) => {
7523
7524
  throw new CreationClientError("creation.local_upload." + code);
7524
7525
  };
7525
7526
  var positive = (value2) => Number.isSafeInteger(value2) && value2 > 0;
7526
7527
  var forbiddenHeader = /^(?:authorization|cookie|host|connection|upgrade|proxy-.*)$/i;
7527
7528
  var defaultBudget = { totalMs: 3e5, firstProgressMs: 3e4, idleMs: 6e4 };
7529
+ var stages = /* @__PURE__ */ new Set(["validating", "checking_file", "opening_stream", "streaming", "awaiting_response", "finishing_stream", "reading_receipt"]);
7530
+ var causes = /* @__PURE__ */ new Set([
7531
+ "local_read_failed",
7532
+ "local_file_changed",
7533
+ "local_read_cancelled",
7534
+ "dns_failure",
7535
+ "connection_refused",
7536
+ "connection_interrupted",
7537
+ "network_timeout",
7538
+ "tls_rejected",
7539
+ "transport_unconfirmed",
7540
+ "http_rejected",
7541
+ "byte_count_mismatch",
7542
+ "etag_missing",
7543
+ "cancelled",
7544
+ "first_progress_timeout",
7545
+ "idle_timeout",
7546
+ "deadline_elapsed",
7547
+ "validation_refused",
7548
+ "stream_unconfirmed"
7549
+ ]);
7550
+ var localCause = (error4) => error4 instanceof CreationClientError ? {
7551
+ "creation.local_upload.file_read_failed": "local_read_failed",
7552
+ "creation.local_upload.file_changed": "local_file_changed",
7553
+ "creation.local_upload.file_read_cancelled": "local_read_cancelled"
7554
+ }[error4.message] : void 0;
7555
+ var networkCause = (error4) => {
7556
+ const code = typeof error4?.cause?.code === "string" ? error4.cause.code : error4?.code;
7557
+ if (["ENOTFOUND", "EAI_AGAIN"].includes(code)) return "dns_failure";
7558
+ if (code === "ECONNREFUSED") return "connection_refused";
7559
+ if (["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"].includes(code)) return "connection_interrupted";
7560
+ if (["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"].includes(code)) return "network_timeout";
7561
+ if (["ERR_TLS_CERT_ALTNAME_INVALID", "CERT_HAS_EXPIRED", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "DEPTH_ZERO_SELF_SIGNED_CERT"].includes(code)) return "tls_rejected";
7562
+ return "transport_unconfirmed";
7563
+ };
7564
+ function safePartTransferDiagnostic(value2) {
7565
+ if (!value2 || !stages.has(value2.stage) || !causes.has(value2.causeCode)) return;
7566
+ const result = { stage: value2.stage, causeCode: value2.causeCode };
7567
+ for (const key of ["requestId", "uploadId", "assetId"]) if (typeof value2[key] === "string" && /^[A-Za-z0-9_.:-]{1,200}$/.test(value2[key])) result[key] = value2[key];
7568
+ for (const key of ["partNumber", "expectedBytes", "bytesRead", "elapsedMs"]) if (Number.isSafeInteger(value2[key]) && value2[key] >= 0) result[key] = value2[key];
7569
+ if (Number.isInteger(value2.httpStatus) && value2.httpStatus >= 100 && value2.httpStatus <= 599) result.httpStatus = value2.httpStatus;
7570
+ return Object.freeze(result);
7571
+ }
7528
7572
  async function transferGrantedPart(file, authorization, grant, {
7529
7573
  expectedUploadId,
7530
7574
  expectedAssetId,
@@ -7533,6 +7577,8 @@ async function transferGrantedPart(file, authorization, grant, {
7533
7577
  fetch: fetchPart = globalThis.fetch,
7534
7578
  now = Date.now,
7535
7579
  onProgress = () => {
7580
+ },
7581
+ onTransferState = () => {
7536
7582
  }
7537
7583
  } = {}) {
7538
7584
  const session = authorization?.session;
@@ -7553,6 +7599,14 @@ async function transferGrantedPart(file, authorization, grant, {
7553
7599
  fail("transfer_budget_invalid");
7554
7600
  const start = (grant.partNumber - 1) * session.partSizeBytes;
7555
7601
  const sizeBytes = Math.min(session.partSizeBytes, file.sizeBytes - start);
7602
+ const report = (stage, extra = {}) => onTransferState({
7603
+ stage,
7604
+ uploadId: session.uploadId,
7605
+ assetId: session.assetId,
7606
+ partNumber: grant.partNumber,
7607
+ expectedBytes: sizeBytes,
7608
+ ...extra
7609
+ });
7556
7610
  const headers = new Headers();
7557
7611
  if (!grant.requiredHeaders || typeof grant.requiredHeaders !== "object" || Array.isArray(grant.requiredHeaders) || Object.keys(grant.requiredHeaders).length > 64) fail("grant_invalid");
7558
7612
  for (const [name, value2] of Object.entries(grant.requiredHeaders)) {
@@ -7567,12 +7621,24 @@ async function transferGrantedPart(file, authorization, grant, {
7567
7621
  headers.set("content-length", String(sizeBytes));
7568
7622
  const deadline = Math.min(now() + budget.totalMs, ...expires, deadlineAtMs);
7569
7623
  if (!Number.isFinite(deadline) || deadline <= now()) fail("transfer_deadline_expired");
7570
- await file.assertUnchanged();
7624
+ report("checking_file", { bytesRead: 0 });
7625
+ try {
7626
+ await file.assertUnchanged();
7627
+ } catch (error4) {
7628
+ report("checking_file", { causeCode: localCause(error4) ?? "local_read_failed" });
7629
+ throw error4;
7630
+ }
7571
7631
  if (signal?.aborted) fail("transfer_cancelled");
7572
7632
  const controller = new AbortController();
7573
7633
  let reason, firstTimer, idleTimer, totalTimer, bytesRead = 0;
7574
7634
  const abort = (code) => {
7575
7635
  reason ??= code;
7636
+ onTransferState({ bytesRead, causeCode: {
7637
+ transfer_cancelled: "cancelled",
7638
+ transfer_first_progress_timeout: "first_progress_timeout",
7639
+ transfer_idle_timeout: "idle_timeout",
7640
+ transfer_timeout: "deadline_elapsed"
7641
+ }[reason] });
7576
7642
  controller.abort();
7577
7643
  };
7578
7644
  const cancel = () => abort("transfer_cancelled");
@@ -7585,19 +7651,30 @@ async function transferGrantedPart(file, authorization, grant, {
7585
7651
  };
7586
7652
  firstTimer = timer(() => abort("transfer_first_progress_timeout"), budget.firstProgressMs);
7587
7653
  totalTimer = timer(() => abort("transfer_timeout"), Math.max(1, deadline - now()));
7588
- let input, body, bodyDone, inputDone, response;
7654
+ let input, body, bodyDone, inputDone, response, closing = false, streamFailure = false;
7589
7655
  async function* chunks() {
7590
- for await (const chunk of input) {
7591
- if (controller.signal.aborted) fail(reason ?? "transfer_cancelled");
7592
- clearTimeout(firstTimer);
7593
- clearTimeout(idleTimer);
7594
- idleTimer = timer(() => abort("transfer_idle_timeout"), budget.idleMs);
7595
- bytesRead += chunk.length;
7596
- onProgress({ partNumber: grant.partNumber, bytesRead, sizeBytes });
7597
- yield chunk;
7656
+ try {
7657
+ for await (const chunk of input) {
7658
+ if (controller.signal.aborted) fail(reason ?? "transfer_cancelled");
7659
+ clearTimeout(firstTimer);
7660
+ clearTimeout(idleTimer);
7661
+ idleTimer = timer(() => abort("transfer_idle_timeout"), budget.idleMs);
7662
+ bytesRead += chunk.length;
7663
+ report("streaming", { bytesRead });
7664
+ onProgress({ partNumber: grant.partNumber, bytesRead, sizeBytes });
7665
+ yield chunk;
7666
+ }
7667
+ report("awaiting_response", { bytesRead });
7668
+ } catch (error4) {
7669
+ if (!reason && !closing) {
7670
+ streamFailure = true;
7671
+ report("streaming", { bytesRead, causeCode: localCause(error4) ?? (["EIO", "EACCES", "EPERM", "ESTALE", "EBADF"].includes(error4?.code) ? "local_read_failed" : "stream_unconfirmed") });
7672
+ }
7673
+ throw error4;
7598
7674
  }
7599
7675
  }
7600
7676
  try {
7677
+ report("opening_stream", { bytesRead });
7601
7678
  input = file.streamPart({ start, sizeBytes, signal: controller.signal });
7602
7679
  body = Readable2.from(chunks(), { objectMode: false, highWaterMark: LOCAL_UPLOAD_READ_BYTES });
7603
7680
  bodyDone = finished2(body);
@@ -7607,19 +7684,41 @@ async function transferGrantedPart(file, authorization, grant, {
7607
7684
  inputDone.catch(() => {
7608
7685
  });
7609
7686
  response = await fetchPart(destination, { method: "PUT", headers, body, duplex: "half", redirect: "error", signal: controller.signal });
7610
- if (!response.ok) fail("part_target_rejected");
7687
+ report("finishing_stream", { bytesRead, httpStatus: response.status });
7688
+ if (!response.ok) {
7689
+ report("finishing_stream", { bytesRead, httpStatus: response.status, causeCode: "http_rejected" });
7690
+ fail("part_target_rejected");
7691
+ }
7611
7692
  await bodyDone;
7612
7693
  await inputDone;
7613
- if (bytesRead !== sizeBytes) fail("part_transfer_unconfirmed");
7614
- await file.assertUnchanged();
7694
+ if (bytesRead !== sizeBytes) {
7695
+ report("finishing_stream", { bytesRead, causeCode: "byte_count_mismatch" });
7696
+ fail("part_transfer_unconfirmed");
7697
+ }
7698
+ report("checking_file", { bytesRead });
7699
+ try {
7700
+ await file.assertUnchanged();
7701
+ } catch (error4) {
7702
+ report("checking_file", { bytesRead, causeCode: localCause(error4) ?? "local_read_failed" });
7703
+ throw error4;
7704
+ }
7705
+ report("reading_receipt", { bytesRead });
7615
7706
  const etag = response.headers.get("etag");
7616
- if (!etag || etag.length > 512 || /[\x00-\x1f\x7f]/.test(etag)) fail("part_receipt_unconfirmed");
7707
+ if (!etag || etag.length > 512 || /[\x00-\x1f\x7f]/.test(etag)) {
7708
+ report("reading_receipt", { bytesRead, causeCode: "etag_missing" });
7709
+ fail("part_receipt_unconfirmed");
7710
+ }
7617
7711
  return { partNumber: grant.partNumber, etag, sizeBytes };
7618
7712
  } catch (error4) {
7619
7713
  if (reason) fail(reason);
7620
- if (error4 instanceof CreationClientError) throw error4;
7714
+ if (error4 instanceof CreationClientError) {
7715
+ if (localCause(error4)) onTransferState({ causeCode: localCause(error4) });
7716
+ throw error4;
7717
+ }
7718
+ if (!streamFailure) onTransferState({ causeCode: networkCause(error4) });
7621
7719
  fail("part_transfer_unconfirmed");
7622
7720
  } finally {
7721
+ closing = true;
7623
7722
  controller.abort();
7624
7723
  clearTimeout(firstTimer);
7625
7724
  clearTimeout(idleTimer);
@@ -7633,16 +7732,27 @@ async function transferGrantedPart(file, authorization, grant, {
7633
7732
  }
7634
7733
  }
7635
7734
  var effects = /* @__PURE__ */ new WeakMap();
7735
+ var diagnostics = /* @__PURE__ */ new WeakMap();
7636
7736
  var readPartTransferEffect = (error4) => error4 && typeof error4 === "object" ? effects.get(error4) : void 0;
7737
+ var readPartTransferDiagnostic = (error4) => error4 && typeof error4 === "object" ? diagnostics.get(error4) : void 0;
7637
7738
  async function uploadGrantedPart(file, authorization, grant, options = {}) {
7638
- let dispatched = false;
7739
+ let dispatched = false, state = { stage: "validating", bytesRead: 0 };
7740
+ const monotonic = options.monotonicNow ?? (() => performance2.now()), started = monotonic();
7639
7741
  try {
7640
- return await transferGrantedPart(file, authorization, grant, { ...options, fetch: async (...args2) => {
7742
+ return await transferGrantedPart(file, authorization, grant, { ...options, onTransferState: (value2) => {
7743
+ state = { ...state, ...value2 };
7744
+ }, fetch: async (...args2) => {
7641
7745
  dispatched = true;
7642
7746
  return (options.fetch ?? globalThis.fetch)(...args2);
7643
7747
  } });
7644
7748
  } catch (error4) {
7645
7749
  if (error4 && typeof error4 === "object") effects.set(error4, dispatched ? "unknown" : "not_dispatched");
7750
+ if (error4 && typeof error4 === "object") diagnostics.set(error4, safePartTransferDiagnostic({
7751
+ ...state,
7752
+ requestId: options.requestId,
7753
+ causeCode: state.causeCode ?? (!dispatched && state.stage === "validating" ? "validation_refused" : networkCause(error4)),
7754
+ elapsedMs: Math.max(0, Math.floor(monotonic() - started))
7755
+ }));
7646
7756
  throw error4;
7647
7757
  }
7648
7758
  }
@@ -7940,6 +8050,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
7940
8050
  ...state.pendingPart ? { unconfirmedPart: state.pendingPart } : {},
7941
8051
  ...state.errorCode ? { errorCode: state.errorCode } : {},
7942
8052
  ...state.result ? { result: state.result } : {},
8053
+ ...safePartTransferDiagnostic(state.lastTransferDiagnostic) ? { lastTransferDiagnostic: safePartTransferDiagnostic(state.lastTransferDiagnostic) } : {},
7943
8054
  ...state.createObservation ? { creation: { outcome: state.createDisposition ?? "unconfirmed", ...state.createObservation } } : {},
7944
8055
  automaticReplayAllowed: false,
7945
8056
  next: job ? "Read status using this same key." : terminalNext[state.phase] ?? (state.phase === "derivatives_pending" ? "Read status for the original asset validation and derivatives." : "Observe status or explicitly resume/cancel this same key. Do not create a replacement upload.")
@@ -8094,6 +8205,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8094
8205
  part = await uploadGrantedPart(file, envelope, grant, {
8095
8206
  expectedUploadId: state.uploadId,
8096
8207
  expectedAssetId: state.assetId,
8208
+ requestId: state.request.idempotencyKey,
8097
8209
  signal: abort.signal,
8098
8210
  deadlineAtMs: state.deadlineAtMs,
8099
8211
  fetch: fetch2,
@@ -8103,6 +8215,8 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8103
8215
  }
8104
8216
  });
8105
8217
  } catch (error4) {
8218
+ const diagnostic = readPartTransferDiagnostic(error4);
8219
+ if (diagnostic) state.lastTransferDiagnostic = diagnostic;
8106
8220
  if (readPartTransferEffect(error4) === "not_dispatched") {
8107
8221
  delete state.pendingPart;
8108
8222
  await save();
@@ -8113,6 +8227,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8113
8227
  state.parts.sort((a, b2) => a.partNumber - b2.partNumber);
8114
8228
  job.progress = 0;
8115
8229
  delete state.pendingPart;
8230
+ delete state.lastTransferDiagnostic;
8116
8231
  await save();
8117
8232
  }
8118
8233
  await binding.assertCurrent();
@@ -8314,7 +8429,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8314
8429
  }
8315
8430
 
8316
8431
  // lib/version.mjs
8317
- var CLIENT_VERSION = "0.3.9";
8432
+ var CLIENT_VERSION = "0.3.10";
8318
8433
  var CLIENT_PROTOCOL = "creation-client/v1";
8319
8434
 
8320
8435
  // lib/cli.mjs
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "creation-install-guidance/v1",
3
3
  "package": "@promptframe/creation",
4
- "version": "0.3.9",
4
+ "version": "0.3.10",
5
5
  "hosts": [
6
6
  {
7
7
  "kind": "codex",
@@ -6,7 +6,7 @@
6
6
 
7
7
  <!-- creation-install-command -->
8
8
  ```bash
9
- npx --yes @promptframe/creation@0.3.9 connect --endpoint <Studio提供的API地址>
9
+ npx --yes @promptframe/creation@0.3.10 connect --endpoint <Studio提供的API地址>
10
10
  ```
11
11
  <!-- /creation-install-command -->
12
12
 
@@ -26,7 +26,7 @@ npx --yes @promptframe/creation@0.3.9 connect --endpoint <Studio提供的API地
26
26
 
27
27
  <!-- creation-install-command -->
28
28
  ```bash
29
- npx --yes @promptframe/creation@0.3.9 connect --host claude-code --endpoint <Studio提供的API地址>
29
+ npx --yes @promptframe/creation@0.3.10 connect --host claude-code --endpoint <Studio提供的API地址>
30
30
  ```
31
31
  <!-- /creation-install-command -->
32
32
 
@@ -46,7 +46,7 @@ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别
46
46
 
47
47
  <!-- creation-install-command -->
48
48
  ```bash
49
- npx --yes @promptframe/creation@0.3.9 connect --profile work-account --endpoint <另一环境API地址>
49
+ npx --yes @promptframe/creation@0.3.10 connect --profile work-account --endpoint <另一环境API地址>
50
50
  ```
51
51
  <!-- /creation-install-command -->
52
52
 
@@ -0,0 +1,7 @@
1
+ # 0.3.10
2
+
3
+ 本机文件上传失败时,返回 `lastTransferDiagnostic`,包含原上传、分片和请求的关联、失败阶段、单调耗时、本地读取字节、预期字节和实际取得的 HTTP 状态。
4
+
5
+ 原因采用固定分类,区分本地读取失败、DNS/连接中断、TLS 拒绝、HTTP 拒绝、字节数不符、缺失 ETag、取消和超时。不输出签名 URL、请求头、异常原文或堆栈。本地读完不代表对象端已完整接收。
6
+
7
+ 不确定的分片效果继续保留在原上传身份下。状态读取不自动重发 PUT,也不自动重新完成上传;恢复仍观察原请求和分片回执。
@@ -1,5 +1,6 @@
1
1
  import {Readable} from 'node:stream';
2
2
  import {finished} from 'node:stream/promises';
3
+ import {performance} from 'node:perf_hooks';
3
4
  import {CreationClientError} from './credentials.mjs';
4
5
  import {LOCAL_UPLOAD_READ_BYTES} from './local-upload-file.mjs';
5
6
 
@@ -7,12 +8,40 @@ const fail=code=>{throw new CreationClientError('creation.local_upload.'+code);}
7
8
  const positive=value=>Number.isSafeInteger(value)&&value>0;
8
9
  const forbiddenHeader=/^(?:authorization|cookie|host|connection|upgrade|proxy-.*)$/i;
9
10
  const defaultBudget={totalMs:300_000,firstProgressMs:30_000,idleMs:60_000};
11
+ const stages=new Set(['validating','checking_file','opening_stream','streaming','awaiting_response','finishing_stream','reading_receipt']);
12
+ const causes=new Set(['local_read_failed','local_file_changed','local_read_cancelled','dns_failure','connection_refused',
13
+ 'connection_interrupted','network_timeout','tls_rejected','transport_unconfirmed','http_rejected','byte_count_mismatch',
14
+ 'etag_missing','cancelled','first_progress_timeout','idle_timeout','deadline_elapsed','validation_refused','stream_unconfirmed']);
15
+ const localCause=error=>error instanceof CreationClientError?({
16
+ 'creation.local_upload.file_read_failed':'local_read_failed','creation.local_upload.file_changed':'local_file_changed',
17
+ 'creation.local_upload.file_read_cancelled':'local_read_cancelled',
18
+ })[error.message]:undefined;
19
+ const networkCause=error=>{
20
+ const code=typeof error?.cause?.code==='string'?error.cause.code:error?.code;
21
+ if(['ENOTFOUND','EAI_AGAIN'].includes(code))return 'dns_failure';
22
+ if(code==='ECONNREFUSED')return 'connection_refused';
23
+ if(['ECONNRESET','EPIPE','UND_ERR_SOCKET'].includes(code))return 'connection_interrupted';
24
+ if(['ETIMEDOUT','UND_ERR_CONNECT_TIMEOUT','UND_ERR_HEADERS_TIMEOUT','UND_ERR_BODY_TIMEOUT'].includes(code))return 'network_timeout';
25
+ if(['ERR_TLS_CERT_ALTNAME_INVALID','CERT_HAS_EXPIRED','UNABLE_TO_VERIFY_LEAF_SIGNATURE','DEPTH_ZERO_SELF_SIGNED_CERT'].includes(code))return 'tls_rejected';
26
+ return 'transport_unconfirmed';
27
+ };
28
+ /** Copy only measured, bounded fields. Never serialize the original Error,
29
+ * target URL, arbitrary cause/message/stack, headers or signed grant. */
30
+ export function safePartTransferDiagnostic(value){
31
+ if(!value||!stages.has(value.stage)||!causes.has(value.causeCode))return;
32
+ const result={stage:value.stage,causeCode:value.causeCode};
33
+ for(const key of ['requestId','uploadId','assetId'])if(typeof value[key]==='string'&&/^[A-Za-z0-9_.:-]{1,200}$/.test(value[key]))result[key]=value[key];
34
+ for(const key of ['partNumber','expectedBytes','bytesRead','elapsedMs'])if(Number.isSafeInteger(value[key])&&value[key]>=0)result[key]=value[key];
35
+ if(Number.isInteger(value.httpStatus)&&value.httpStatus>=100&&value.httpStatus<=599)result.httpStatus=value.httpStatus;
36
+ return Object.freeze(result);
37
+ }
10
38
 
11
39
  /** Consume an authenticated platform grant, never a model-supplied destination.
12
40
  * A successful PUT is a part receipt; asset readiness belongs to the platform. */
13
41
  async function transferGrantedPart(file,authorization,grant,{
14
42
  expectedUploadId,expectedAssetId,signal,deadlineAtMs=Infinity,
15
43
  fetch:fetchPart=globalThis.fetch,now=Date.now,onProgress=()=>{},
44
+ onTransferState=()=>{},
16
45
  }={}){
17
46
  const session=authorization?.session;
18
47
  if(authorization?.contractVersion!=='direct-object-upload.v2'
@@ -38,6 +67,8 @@ async function transferGrantedPart(file,authorization,grant,{
38
67
  fail('transfer_budget_invalid');
39
68
  const start=(grant.partNumber-1)*session.partSizeBytes;
40
69
  const sizeBytes=Math.min(session.partSizeBytes,file.sizeBytes-start);
70
+ const report=(stage,extra={})=>onTransferState({stage,uploadId:session.uploadId,assetId:session.assetId,
71
+ partNumber:grant.partNumber,expectedBytes:sizeBytes,...extra});
41
72
  const headers=new Headers();
42
73
  if(!grant.requiredHeaders||typeof grant.requiredHeaders!=='object'||Array.isArray(grant.requiredHeaders)
43
74
  ||Object.keys(grant.requiredHeaders).length>64)fail('grant_invalid');
@@ -49,44 +80,56 @@ async function transferGrantedPart(file,authorization,grant,{
49
80
  headers.set('content-length',String(sizeBytes));
50
81
  const deadline=Math.min(now()+budget.totalMs,...expires,deadlineAtMs);
51
82
  if(!Number.isFinite(deadline)||deadline<=now())fail('transfer_deadline_expired');
52
- await file.assertUnchanged();
83
+ report('checking_file',{bytesRead:0});
84
+ try{await file.assertUnchanged();}catch(error){report('checking_file',{causeCode:localCause(error)??'local_read_failed'});throw error;}
53
85
  if(signal?.aborted)fail('transfer_cancelled');
54
86
  const controller=new AbortController();let reason,firstTimer,idleTimer,totalTimer,bytesRead=0;
55
- const abort=code=>{reason??=code;controller.abort();};
87
+ const abort=code=>{reason??=code;onTransferState({bytesRead,causeCode:({transfer_cancelled:'cancelled',transfer_first_progress_timeout:'first_progress_timeout',
88
+ transfer_idle_timeout:'idle_timeout',transfer_timeout:'deadline_elapsed'})[reason]});controller.abort();};
56
89
  const cancel=()=>abort('transfer_cancelled');
57
90
  if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
58
91
  const timer=(callback,ms)=>{const id=setTimeout(callback,ms);id.unref?.();return id;};
59
92
  firstTimer=timer(()=>abort('transfer_first_progress_timeout'),budget.firstProgressMs);
60
93
  totalTimer=timer(()=>abort('transfer_timeout'),Math.max(1,deadline-now()));
61
- let input,body,bodyDone,inputDone,response;
94
+ let input,body,bodyDone,inputDone,response,closing=false,streamFailure=false;
62
95
  async function* chunks(){
63
- for await(const chunk of input){
96
+ try{for await(const chunk of input){
64
97
  if(controller.signal.aborted)fail(reason??'transfer_cancelled');
65
98
  clearTimeout(firstTimer);clearTimeout(idleTimer);
66
99
  idleTimer=timer(()=>abort('transfer_idle_timeout'),budget.idleMs);
67
- bytesRead+=chunk.length;onProgress({partNumber:grant.partNumber,bytesRead,sizeBytes});
100
+ bytesRead+=chunk.length;report('streaming',{bytesRead});onProgress({partNumber:grant.partNumber,bytesRead,sizeBytes});
68
101
  yield chunk;
102
+ }report('awaiting_response',{bytesRead});}catch(error){
103
+ if(!reason&&!closing){streamFailure=true;report('streaming',{bytesRead,causeCode:localCause(error)
104
+ ??(['EIO','EACCES','EPERM','ESTALE','EBADF'].includes(error?.code)?'local_read_failed':'stream_unconfirmed')});}
105
+ throw error;
69
106
  }
70
107
  }
71
108
  try{
109
+ report('opening_stream',{bytesRead});
72
110
  input=file.streamPart({start,sizeBytes,signal:controller.signal});
73
111
  body=Readable.from(chunks(),{objectMode:false,highWaterMark:LOCAL_UPLOAD_READ_BYTES});
74
112
  bodyDone=finished(body);bodyDone.catch(()=>{});
75
113
  inputDone=finished(input);inputDone.catch(()=>{});
76
114
  response=await fetchPart(destination,{method:'PUT',headers,body,duplex:'half',redirect:'error',signal:controller.signal});
77
- if(!response.ok)fail('part_target_rejected');
115
+ report('finishing_stream',{bytesRead,httpStatus:response.status});
116
+ if(!response.ok){report('finishing_stream',{bytesRead,httpStatus:response.status,causeCode:'http_rejected'});fail('part_target_rejected');}
78
117
  await bodyDone;await inputDone;
79
- if(bytesRead!==sizeBytes)fail('part_transfer_unconfirmed');
80
- await file.assertUnchanged();
118
+ if(bytesRead!==sizeBytes){report('finishing_stream',{bytesRead,causeCode:'byte_count_mismatch'});fail('part_transfer_unconfirmed');}
119
+ report('checking_file',{bytesRead});
120
+ try{await file.assertUnchanged();}catch(error){report('checking_file',{bytesRead,causeCode:localCause(error)??'local_read_failed'});throw error;}
121
+ report('reading_receipt',{bytesRead});
81
122
  const etag=response.headers.get('etag');
82
- if(!etag||etag.length>512||/[\x00-\x1f\x7f]/.test(etag))fail('part_receipt_unconfirmed');
123
+ if(!etag||etag.length>512||/[\x00-\x1f\x7f]/.test(etag)){report('reading_receipt',{bytesRead,causeCode:'etag_missing'});fail('part_receipt_unconfirmed');}
83
124
  return {partNumber:grant.partNumber,etag,sizeBytes};
84
125
  }catch(error){
85
126
  if(reason)fail(reason);
86
- if(error instanceof CreationClientError)throw error;
127
+ if(error instanceof CreationClientError){if(localCause(error))onTransferState({causeCode:localCause(error)});throw error;}
87
128
  // Fetch errors can include the signed URL. Keep only a safe classification.
129
+ if(!streamFailure)onTransferState({causeCode:networkCause(error)});
88
130
  fail('part_transfer_unconfirmed');
89
131
  }finally{
132
+ closing=true;
90
133
  controller.abort();clearTimeout(firstTimer);clearTimeout(idleTimer);clearTimeout(totalTimer);
91
134
  signal?.removeEventListener('abort',cancel);
92
135
  body?.destroy();input?.destroy();
@@ -96,13 +139,19 @@ async function transferGrantedPart(file,authorization,grant,{
96
139
  }
97
140
 
98
141
  const effects=new WeakMap();
142
+ const diagnostics=new WeakMap();
99
143
  export const readPartTransferEffect=error=>error&&typeof error==='object'?effects.get(error):undefined;
144
+ export const readPartTransferDiagnostic=error=>error&&typeof error==='object'?diagnostics.get(error):undefined;
100
145
  export async function uploadGrantedPart(file,authorization,grant,options={}){
101
- let dispatched=false;
102
- try{return await transferGrantedPart(file,authorization,grant,{...options,fetch:async(...args)=>{
146
+ let dispatched=false,state={stage:'validating',bytesRead:0};
147
+ const monotonic=options.monotonicNow??(()=>performance.now()),started=monotonic();
148
+ try{return await transferGrantedPart(file,authorization,grant,{...options,onTransferState:value=>{state={...state,...value};},fetch:async(...args)=>{
103
149
  dispatched=true;return(options.fetch??globalThis.fetch)(...args);
104
150
  }});}catch(error){
105
151
  if(error&&typeof error==='object')effects.set(error,dispatched?'unknown':'not_dispatched');
152
+ if(error&&typeof error==='object')diagnostics.set(error,safePartTransferDiagnostic({...state,requestId:options.requestId,
153
+ causeCode:state.causeCode??(!dispatched&&state.stage==='validating'?'validation_refused':networkCause(error)),
154
+ elapsedMs:Math.max(0,Math.floor(monotonic()-started))}));
106
155
  throw error;
107
156
  }
108
157
  }
@@ -3,7 +3,7 @@ import {hostname,platform} from 'node:os';
3
3
  import path from 'node:path';
4
4
  import {CreationClientError} from './credentials.mjs';
5
5
  import {openLocalUploadFile} from './local-upload-file.mjs';
6
- import {uploadGrantedPart,readPartTransferEffect} from './local-upload-transfer.mjs';
6
+ import {uploadGrantedPart,readPartTransferEffect,readPartTransferDiagnostic,safePartTransferDiagnostic} from './local-upload-transfer.mjs';
7
7
  import {localUploadState} from './local-upload-state.mjs';
8
8
 
9
9
  export const LOCAL_UPLOAD_PROTOCOL='creation-local-file-upload/v1';
@@ -77,6 +77,7 @@ export function createLocalUploadManager({stateRoot,fetch=globalThis.fetch,now=D
77
77
  progress:{uploadedBytes:state.parts.reduce((sum,p)=>sum+p.sizeBytes,0)+(job?.progress??0),totalBytes:state.file.sizeBytes},
78
78
  ...(state.jobId?{jobId:state.jobId}:{}),...(state.pendingPart?{unconfirmedPart:state.pendingPart}:{}),...(state.errorCode?{errorCode:state.errorCode}:{}),
79
79
  ...(state.result?{result:state.result}:{}),
80
+ ...(safePartTransferDiagnostic(state.lastTransferDiagnostic)?{lastTransferDiagnostic:safePartTransferDiagnostic(state.lastTransferDiagnostic)}:{}),
80
81
  ...(state.createObservation?{creation:{outcome:state.createDisposition??'unconfirmed',...state.createObservation}}:{}),
81
82
  automaticReplayAllowed:false,
82
83
  next:job?'Read status using this same key.':terminalNext[state.phase]??(
@@ -183,12 +184,13 @@ export function createLocalUploadManager({stateRoot,fetch=globalThis.fetch,now=D
183
184
  state.phase='transferring';state.pendingPart=grant.partNumber;await save();
184
185
  let part;
185
186
  try{part=await uploadGrantedPart(file,envelope,grant,{expectedUploadId:state.uploadId,expectedAssetId:state.assetId,
186
- signal:abort.signal,deadlineAtMs:state.deadlineAtMs,fetch,now,onProgress:progress=>{job.progress=progress.bytesRead;}});
187
+ requestId:state.request.idempotencyKey,signal:abort.signal,deadlineAtMs:state.deadlineAtMs,fetch,now,onProgress:progress=>{job.progress=progress.bytesRead;}});
187
188
  }catch(error){
189
+ const diagnostic=readPartTransferDiagnostic(error);if(diagnostic)state.lastTransferDiagnostic=diagnostic;
188
190
  if(readPartTransferEffect(error)==='not_dispatched'){delete state.pendingPart;await save();}
189
191
  throw error;
190
192
  }
191
- state.parts.push(part);state.parts.sort((a,b)=>a.partNumber-b.partNumber);job.progress=0;delete state.pendingPart;await save();
193
+ state.parts.push(part);state.parts.sort((a,b)=>a.partNumber-b.partNumber);job.progress=0;delete state.pendingPart;delete state.lastTransferDiagnostic;await save();
192
194
  }
193
195
  await binding.assertCurrent();abort.signal.throwIfAborted();
194
196
  envelope=(await rpc(send,{action:'resume',uploadId:state.uploadId})).authorization;
package/lib/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
- export const CLIENT_VERSION = "0.3.9";
1
+ export const CLIENT_VERSION = "0.3.10";
2
2
  export const CLIENT_PROTOCOL = "creation-client/v1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptframe/creation",
3
- "version": "0.3.9",
3
+ "version": "0.3.10",
4
4
  "private": false,
5
5
  "description": "PromptFrame video creation Skill, Codex plugin and MCP client bridge.",
6
6
  "repository": {
@@ -10,11 +10,11 @@ description: 安装、连接或升级 PromptFrame Creation,复用平台创作
10
10
  先确认使用 Codex 还是 Claude Code。Claude 接入使用 `connect --host claude-code`,两种宿主可共用同一 profile 凭据,插件登记分别核实。使用 Studio 对当前环境提供的固定版本;旧版入口不会因平台更新自动改变。Claude 桌面版远程连接 WSL 时,在同一 WSL 安装;没有终端命令时可通过 `--claude-bin <实际可执行文件>` 指定桌面版提供的入口,不固定桌面构建文件名。
11
11
 
12
12
  <!-- creation-install-command -->
13
- 在用户本机终端运行 `npx --yes @promptframe/creation@0.3.9 connect --endpoint <Studio提供的API地址>`。需要隔离另一个环境或账号时显式加 `--profile <用户选择的名称>`;正在运行的桥不会切换。此命令管理用户级版本和 Codex 插件,不向当前项目安装依赖。优先使用 Studio 当前提供的固定推荐版本;每次重新进入此入口比较已安装版本,不后台追踪 latest,也不把旧聊天里的命令当最新版本。已安装更新版不默认降级。
13
+ 在用户本机终端运行 `npx --yes @promptframe/creation@0.3.10 connect --endpoint <Studio提供的API地址>`。需要隔离另一个环境或账号时显式加 `--profile <用户选择的名称>`;正在运行的桥不会切换。此命令管理用户级版本和 Codex 插件,不向当前项目安装依赖。优先使用 Studio 当前提供的固定推荐版本;每次重新进入此入口比较已安装版本,不后台追踪 latest,也不把旧聊天里的命令当最新版本。已安装更新版不默认降级。
14
14
  <!-- /creation-install-command -->
15
15
 
16
16
  <!-- creation-install-command -->
17
- Claude Code 使用 `npx --yes @promptframe/creation@0.3.9 connect --host claude-code --endpoint <Studio提供的API地址>`。桌面版远程连接 WSL 时,在该 WSL 执行;保留相同 profile 和有效凭据。
17
+ Claude Code 使用 `npx --yes @promptframe/creation@0.3.10 connect --host claude-code --endpoint <Studio提供的API地址>`。桌面版远程连接 WSL 时,在该 WSL 执行;保留相同 profile 和有效凭据。
18
18
  <!-- /creation-install-command -->
19
19
 
20
20
  命令会复用并验证有效凭据。首次授权或明确更换已失效凭据时,由用户在 Studio 登录并在终端的不回显输入框提供 Token;不要要求用户把 Token 粘进聊天,也不要把它写进命令参数、URL或日志。网络失败不等于授权失效,不自动轮换或覆盖凭据。