@deployxai/dxc 0.3.1 → 0.3.3

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.
@@ -0,0 +1,2345 @@
1
+ import { createRequire as __dxcCreateRequire } from "node:module"; const require = __dxcCreateRequire(import.meta.url);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __esm = (fn, res, err) => function __init() {
15
+ if (err) throw err[0];
16
+ try {
17
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ } catch (e) {
19
+ throw err = [e], e;
20
+ }
21
+ };
22
+ var __commonJS = (cb, mod) => function __require2() {
23
+ try {
24
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
25
+ } catch (e) {
26
+ throw mod = 0, e;
27
+ }
28
+ };
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, { get: all[name], enumerable: true });
32
+ };
33
+ var __copyProps = (to, from, except, desc) => {
34
+ if (from && typeof from === "object" || typeof from === "function") {
35
+ for (let key of __getOwnPropNames(from))
36
+ if (!__hasOwnProp.call(to, key) && key !== except)
37
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
38
+ }
39
+ return to;
40
+ };
41
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
42
+ // If the importer is in node compatibility mode or this is not an ESM
43
+ // file that has been converted to a CommonJS file using a Babel-
44
+ // compatible transform (i.e. "__esModule" has not been set), then set
45
+ // "default" to the CommonJS "module.exports" for node compatibility.
46
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
47
+ mod
48
+ ));
49
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
+
51
+ // packages/contracts/src/content-workflow.ts
52
+ import { z } from "zod";
53
+ var CONTENT_WORKFLOW_ID = "dxc-article@1";
54
+ var CONTENT_PROFILE_QUESTIONNAIRE_VERSION = "dxc-onboarding@1";
55
+ var CONTENT_ARTIFACT_KINDS = [
56
+ "research",
57
+ "brief",
58
+ "outline",
59
+ "article",
60
+ "titles",
61
+ "visual-plan",
62
+ "quality-review",
63
+ "delivery"
64
+ ];
65
+ var contentArtifactKindSchema = z.enum(CONTENT_ARTIFACT_KINDS);
66
+ var DXC_STAGE_SKILL_NAMES = [
67
+ "dxc-research",
68
+ "dxc-content-brief",
69
+ "dxc-article-outline",
70
+ "dxc-article-write",
71
+ "dxc-title-write",
72
+ "dxc-visual-plan",
73
+ "dxc-content-review",
74
+ "dxc-wechat-publisher"
75
+ ];
76
+ var dxcStageSkillNameSchema = z.enum(DXC_STAGE_SKILL_NAMES);
77
+ var CONTENT_STAGE_DEFINITIONS = {
78
+ article: {
79
+ inputs: { optional: [], required: ["research", "brief", "outline"] },
80
+ output: "article",
81
+ skill: "dxc-article-write",
82
+ stage: "article"
83
+ },
84
+ brief: {
85
+ inputs: { optional: [], required: ["research"] },
86
+ output: "brief",
87
+ skill: "dxc-content-brief",
88
+ stage: "brief"
89
+ },
90
+ delivery: {
91
+ inputs: { optional: [], required: ["article", "titles", "visual-plan", "quality-review"] },
92
+ output: "delivery",
93
+ skill: "dxc-wechat-publisher",
94
+ stage: "delivery"
95
+ },
96
+ outline: {
97
+ inputs: { optional: [], required: ["research", "brief"] },
98
+ output: "outline",
99
+ skill: "dxc-article-outline",
100
+ stage: "outline"
101
+ },
102
+ "quality-review": {
103
+ inputs: { optional: ["visual-plan"], required: ["research", "article", "titles"] },
104
+ output: "quality-review",
105
+ skill: "dxc-content-review",
106
+ stage: "quality-review"
107
+ },
108
+ research: {
109
+ inputs: { optional: [], required: [] },
110
+ output: "research",
111
+ skill: "dxc-research",
112
+ stage: "research"
113
+ },
114
+ titles: {
115
+ inputs: { optional: ["brief"], required: ["article"] },
116
+ output: "titles",
117
+ skill: "dxc-title-write",
118
+ stage: "titles"
119
+ },
120
+ "visual-plan": {
121
+ inputs: { optional: ["outline"], required: ["article", "titles"] },
122
+ output: "visual-plan",
123
+ skill: "dxc-visual-plan",
124
+ stage: "visual-plan"
125
+ }
126
+ };
127
+ var contentWorkflowWorkItemIdSchema = z.string().regex(/^wi1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u);
128
+ var contentWorkflowChoiceIdSchema = z.string().regex(/^choice1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u);
129
+ var contentWorkflowSectionIdSchema = z.string().regex(/^sec_[0-9]{2}_[a-f0-9]{8}$/u);
130
+ var contentWorkflowAssetIdSchema = z.enum([
131
+ "cover",
132
+ ...Array.from({ length: 20 }, (_, index) => `inline-${String(index + 1).padStart(2, "0")}`)
133
+ ]);
134
+ var contentWorkflowChoiceSchema = z.object({
135
+ choiceId: contentWorkflowChoiceIdSchema,
136
+ label: z.string().trim().min(1).max(120)
137
+ }).strict();
138
+ var contentWorkflowAssetAssignmentSchema = z.object({
139
+ assetId: contentWorkflowAssetIdSchema,
140
+ path: z.string().trim().min(1).max(4096),
141
+ role: z.enum(["cover", "inline"]),
142
+ sectionId: contentWorkflowSectionIdSchema.optional()
143
+ }).strict();
144
+ var contentWorkflowNextActionSchema = z.discriminatedUnion("type", [
145
+ z.object({ type: z.literal("run-stage") }).strict(),
146
+ z.object({
147
+ assets: z.array(contentWorkflowAssetAssignmentSchema).min(1).max(21),
148
+ type: z.literal("generate-assets")
149
+ }).strict(),
150
+ z.object({
151
+ presentation: z.object({ path: z.string().trim().min(1).max(4096), type: z.literal("artifact") }).strict(),
152
+ preview: z.object({ path: z.string().trim().min(1).max(4096), type: z.literal("local-preview") }).strict().optional(),
153
+ type: z.literal("confirm-stage")
154
+ }).strict(),
155
+ z.object({
156
+ choices: z.array(contentWorkflowChoiceSchema).min(2).max(100),
157
+ purpose: z.literal("wechat-account"),
158
+ type: z.literal("select-choice")
159
+ }).strict(),
160
+ z.object({ type: z.literal("preview") }).strict(),
161
+ z.object({
162
+ expiresAt: z.iso.datetime(),
163
+ type: z.literal("confirm-delivery")
164
+ }).strict(),
165
+ z.object({
166
+ items: z.array(z.object({ label: z.string().trim().min(1).max(300) }).strict()).min(1).max(20),
167
+ type: z.literal("confirm-knowledge-repair")
168
+ }).strict(),
169
+ z.object({ type: z.literal("completed") }).strict()
170
+ ]);
171
+ var contentWorkflowInputResourceSchema = z.discriminatedUnion("availability", [
172
+ z.object({ availability: z.literal("missing") }).strict(),
173
+ z.object({
174
+ availability: z.literal("present"),
175
+ path: z.string().trim().min(1).max(4096)
176
+ }).strict()
177
+ ]);
178
+ var contentWorkflowResourcesSchema = z.object({
179
+ inputs: z.record(z.string(), contentWorkflowInputResourceSchema),
180
+ output: z.object({
181
+ path: z.string().trim().min(1).max(4096),
182
+ scaffold: z.enum(["created", "existing", "not-applicable"])
183
+ }).strict()
184
+ }).strict();
185
+ var contentWorkflowConstraintsSchema = z.object({
186
+ authorMaxCharacters: z.number().int().positive().optional(),
187
+ coverMaxBytes: z.number().int().positive().optional(),
188
+ digestMaxCharacters: z.number().int().positive().optional(),
189
+ inlineImageMaxBytes: z.number().int().positive().optional(),
190
+ inlineImageMaxCount: z.number().int().positive().optional(),
191
+ supportedImageTypes: z.array(z.enum(["image/jpeg", "image/png"])).optional(),
192
+ titleMaxCharacters: z.number().int().positive().optional()
193
+ }).strict();
194
+ var contentWorkflowSectionSchema = z.object({
195
+ heading: z.string().trim().min(1).max(300),
196
+ sectionId: contentWorkflowSectionIdSchema
197
+ }).strict();
198
+ var contentWorkflowProjectSummarySchema = z.object({
199
+ projectId: z.uuid(),
200
+ title: z.string().trim().min(1).max(160)
201
+ }).strict();
202
+ var contentWorkflowProfileContextSchema = z.object({
203
+ contentValuePromise: z.string().trim().min(1).max(500),
204
+ coreValues: z.string().trim().min(1).max(500).optional(),
205
+ creatorRole: z.string().trim().min(1).max(120),
206
+ displayName: z.string().trim().min(1).max(120),
207
+ penName: z.string().trim().min(1).max(120).optional(),
208
+ pointOfView: z.string().trim().min(1).max(120).optional(),
209
+ primaryDomains: z.array(z.string().trim().min(1).max(120)).min(1).max(5),
210
+ redLines: z.string().trim().min(1).max(500).optional(),
211
+ targetAudience: z.string().trim().min(1).max(500),
212
+ titlePreferences: z.string().trim().min(1).max(500).optional(),
213
+ visualPreferences: z.string().trim().min(1).max(500).optional(),
214
+ writingVoice: z.string().trim().min(1).max(500).optional()
215
+ }).strict();
216
+ var contentWorkflowMemoryContextSchema = z.object({
217
+ content: z.string().trim().min(1).max(500),
218
+ expiresAt: z.iso.datetime().optional(),
219
+ id: z.uuid(),
220
+ kind: z.enum([
221
+ "audience-change",
222
+ "brand-context",
223
+ "business-context",
224
+ "temporary-campaign",
225
+ "writing-preference"
226
+ ])
227
+ }).strict();
228
+ var contentWorkflowAdoptedKnowledgeSchema = z.discriminatedUnion("sourceType", [
229
+ z.object({
230
+ heading: z.string().trim().min(1).max(300).nullable(),
231
+ knowledgeRef: z.string().regex(/^kr1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u),
232
+ label: z.string().trim().min(1).max(300),
233
+ snippet: z.string().trim().min(1).max(420),
234
+ sourceType: z.literal("history-article")
235
+ }).strict(),
236
+ z.object({
237
+ attribution: z.string().trim().min(1).max(300).nullable(),
238
+ knowledgeRef: z.string().regex(/^kr1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u),
239
+ label: z.string().trim().min(1).max(300),
240
+ snippet: z.string().trim().min(1).max(420),
241
+ sourceType: z.literal("quote"),
242
+ verbatimUse: z.enum(["original", "needs-verification", "permitted"])
243
+ }).strict()
244
+ ]);
245
+ var contentWorkflowContextSchema = z.object({
246
+ adoptedKnowledge: z.array(contentWorkflowAdoptedKnowledgeSchema).max(20),
247
+ memories: z.array(contentWorkflowMemoryContextSchema).max(20),
248
+ profile: contentWorkflowProfileContextSchema.nullable()
249
+ }).strict();
250
+ var contentWorkflowWorkItemSchema = z.object({
251
+ constraints: contentWorkflowConstraintsSchema.optional(),
252
+ context: contentWorkflowContextSchema.optional(),
253
+ nextAction: contentWorkflowNextActionSchema,
254
+ resources: contentWorkflowResourcesSchema.optional(),
255
+ sections: z.array(contentWorkflowSectionSchema).max(100).optional(),
256
+ skill: dxcStageSkillNameSchema,
257
+ stage: contentArtifactKindSchema,
258
+ workItemId: contentWorkflowWorkItemIdSchema
259
+ }).strict().superRefine((workItem, context) => {
260
+ if (workItem.stage === "visual-plan" && workItem.nextAction.type === "confirm-stage" && workItem.nextAction.preview === void 0) {
261
+ context.addIssue({
262
+ code: "custom",
263
+ message: "visual-plan confirmation requires a local preview",
264
+ path: ["nextAction", "preview"]
265
+ });
266
+ }
267
+ });
268
+ var contentWorkflowNextResultSchema = z.object({
269
+ command: z.literal("workflow.next"),
270
+ data: z.object({
271
+ project: contentWorkflowProjectSummarySchema,
272
+ workItem: contentWorkflowWorkItemSchema
273
+ }).strict(),
274
+ ok: z.literal(true)
275
+ }).strict();
276
+ function isPortableRelativePath(value) {
277
+ if (value.startsWith("/") || value.includes("\\") || /[:*?"<>|\0]/u.test(value)) {
278
+ return false;
279
+ }
280
+ return value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
281
+ }
282
+ var portableRelativePathSchema = z.string().trim().min(1).max(240).refine(isPortableRelativePath, "path must stay inside the project directory");
283
+ var contentProjectArtifactPathsSchema = z.object({
284
+ article: portableRelativePathSchema,
285
+ brief: portableRelativePathSchema,
286
+ delivery: portableRelativePathSchema,
287
+ outline: portableRelativePathSchema,
288
+ "quality-review": portableRelativePathSchema,
289
+ research: portableRelativePathSchema,
290
+ titles: portableRelativePathSchema,
291
+ "visual-plan": portableRelativePathSchema
292
+ }).strict();
293
+ var contentProjectManifestSchema = z.object({
294
+ artifacts: contentProjectArtifactPathsSchema,
295
+ assetsDirectory: portableRelativePathSchema,
296
+ // Persisted 0.1.x projects may contain this field. New projects do not create checkpoints.
297
+ checkpointsDirectory: portableRelativePathSchema.optional(),
298
+ createdAt: z.iso.datetime(),
299
+ projectId: z.uuid(),
300
+ schemaVersion: z.literal("1"),
301
+ title: z.string().trim().min(1).max(160),
302
+ workflowId: z.literal(CONTENT_WORKFLOW_ID)
303
+ }).strict();
304
+ var contentProjectIndexEntrySchema = z.object({
305
+ directory: z.string().trim().min(1).max(4096),
306
+ projectId: z.uuid(),
307
+ title: z.string().trim().min(1).max(160),
308
+ updatedAt: z.iso.datetime()
309
+ }).strict();
310
+ var contentProjectIndexSchema = z.object({
311
+ projects: z.array(contentProjectIndexEntrySchema).max(1e3),
312
+ schemaVersion: z.literal("1")
313
+ }).strict();
314
+ var contentProfileAnswerSchema = z.object({
315
+ note: z.string().trim().max(500).optional(),
316
+ questionId: z.string().regex(/^[a-z][a-z0-9.-]{1,63}$/u),
317
+ selectedOptionIds: z.array(z.string().regex(/^[a-z][a-z0-9._-]{1,95}$/u)).max(8).default([]),
318
+ text: z.string().trim().min(1).max(500).optional()
319
+ }).strict().refine((answer) => answer.selectedOptionIds.length > 0 || answer.text !== void 0, {
320
+ message: "profile answer requires choices or text"
321
+ });
322
+ var contentConfirmationPolicySchema = z.enum([
323
+ "guided",
324
+ "review-every-stage",
325
+ "auto-until-delivery"
326
+ ]);
327
+ var currentProfileUserSchema = z.object({
328
+ confirmationPolicy: contentConfirmationPolicySchema.default("guided"),
329
+ contentValuePromise: z.string().trim().min(1).max(500),
330
+ coreValues: z.string().trim().min(1).max(500).optional(),
331
+ creatorRole: z.string().trim().min(1).max(120),
332
+ displayName: z.string().trim().min(1).max(120),
333
+ historyDirectory: z.string().trim().min(1).max(4096).optional(),
334
+ penName: z.string().trim().min(1).max(120).optional(),
335
+ pointOfView: z.string().trim().min(1).max(120).optional(),
336
+ primaryDomains: z.array(z.string().trim().min(1).max(120)).min(1).max(5),
337
+ primaryPlatform: z.literal("wechat-official-account"),
338
+ publishingCadence: z.string().trim().min(1).max(120).optional(),
339
+ redLines: z.string().trim().min(1).max(500).optional(),
340
+ targetAudience: z.string().trim().min(1).max(500),
341
+ titlePreferences: z.string().trim().min(1).max(500).optional(),
342
+ visualPreferences: z.string().trim().min(1).max(500).optional(),
343
+ writingVoice: z.string().trim().min(1).max(500).optional()
344
+ }).strict();
345
+ var storedProfileUserSchema = currentProfileUserSchema.extend({
346
+ visualGenerationAuthorization: z.object({
347
+ maxImagesPerRun: z.number().int().min(1).max(20),
348
+ mode: z.literal("auto-within-limit")
349
+ }).strict().optional()
350
+ });
351
+ var contentProfileInputSchema = z.object({
352
+ answers: z.array(contentProfileAnswerSchema).max(32).default([]),
353
+ questionnaireVersion: z.literal(CONTENT_PROFILE_QUESTIONNAIRE_VERSION),
354
+ user: currentProfileUserSchema
355
+ }).strict();
356
+ var contentProfileSchema = z.object({
357
+ answers: z.array(contentProfileAnswerSchema).max(32),
358
+ createdAt: z.iso.datetime(),
359
+ profileId: z.uuid(),
360
+ questionnaireVersion: z.literal(CONTENT_PROFILE_QUESTIONNAIRE_VERSION),
361
+ schemaVersion: z.literal("1"),
362
+ updatedAt: z.iso.datetime(),
363
+ user: storedProfileUserSchema
364
+ }).strict();
365
+ var contentProfileViewSchema = currentProfileUserSchema.omit({ confirmationPolicy: true, historyDirectory: true, primaryPlatform: true }).extend({
366
+ confirmation: z.object({
367
+ label: z.enum(["\u5173\u952E\u5185\u5BB9\u8282\u70B9\u786E\u8BA4", "\u6BCF\u4E2A\u5185\u5BB9\u9636\u6BB5\u90FD\u5C55\u793A\u5E76\u7B49\u5F85\u786E\u8BA4", "\u81EA\u52A8\u63A8\u8FDB\u5230\u4EA4\u4ED8\u524D\u786E\u8BA4"]),
368
+ reviewEveryStage: z.boolean()
369
+ }).strict()
370
+ }).strict();
371
+ var contentProfileResultDataSchema = z.object({ profile: contentProfileViewSchema }).strict();
372
+ var contentProfileStatusResultSchema = z.object({
373
+ command: z.literal("profile.status"),
374
+ data: z.discriminatedUnion("configured", [
375
+ z.object({
376
+ configured: z.literal(false)
377
+ }).strict(),
378
+ contentProfileResultDataSchema.extend({ configured: z.literal(true) }).strict()
379
+ ]),
380
+ ok: z.literal(true)
381
+ }).strict();
382
+ var contentProfileSessionIdSchema = z.uuid();
383
+ var CONTENT_PROFILE_FIELDS = [
384
+ "all",
385
+ "confirmation-policy",
386
+ "content-value-promise",
387
+ "core-values",
388
+ "creator-role",
389
+ "display-name",
390
+ "pen-name",
391
+ "point-of-view",
392
+ "primary-domains",
393
+ "publishing-cadence",
394
+ "red-lines",
395
+ "target-audience",
396
+ "title-preferences",
397
+ "visual-preferences",
398
+ "writing-voice"
399
+ ];
400
+ var contentProfileFieldSchema = z.enum(CONTENT_PROFILE_FIELDS);
401
+ var contentProfileQuestionSchema = z.object({
402
+ choices: z.array(
403
+ z.object({
404
+ choiceId: z.string().regex(/^profile_[a-z0-9.-]+$/u),
405
+ label: z.string().trim().min(1).max(120)
406
+ }).strict()
407
+ ).max(12),
408
+ inputType: z.enum(["multi-choice", "single-choice", "text"]),
409
+ field: contentProfileFieldSchema.exclude(["all"]),
410
+ prompt: z.string().trim().min(1).max(500),
411
+ questionId: z.string().regex(/^[a-z][a-z0-9.-]{1,63}$/u)
412
+ }).strict();
413
+ var contentProfileSessionResultSchema = z.object({
414
+ command: z.enum(["profile.answer", "profile.begin"]),
415
+ data: z.discriminatedUnion("status", [
416
+ z.object({
417
+ profileSessionId: contentProfileSessionIdSchema,
418
+ question: contentProfileQuestionSchema,
419
+ status: z.literal("question")
420
+ }).strict(),
421
+ z.object({
422
+ profile: contentProfileViewSchema,
423
+ status: z.literal("completed")
424
+ }).strict()
425
+ ]),
426
+ ok: z.literal(true)
427
+ }).strict();
428
+ var contentProfileCommandSchema = z.enum([
429
+ "profile.answer",
430
+ "profile.begin",
431
+ "profile.status"
432
+ ]);
433
+ var contentProfileErrorResultSchema = z.object({
434
+ command: contentProfileCommandSchema,
435
+ error: z.object({
436
+ actual: z.string().trim().min(1).optional(),
437
+ candidates: z.array(z.string().trim().min(1)).max(32).optional(),
438
+ code: z.enum([
439
+ "DXC_COMMAND_FAILED",
440
+ "DXC_PROFILE_BUSY",
441
+ "DXC_PROFILE_INPUT_INVALID",
442
+ "DXC_PROFILE_INVALID",
443
+ "DXC_PROFILE_IO_FAILED",
444
+ "DXC_PROFILE_SESSION_EXPIRED"
445
+ ]),
446
+ expected: z.string().trim().min(1).optional(),
447
+ field: z.string().trim().min(1).optional(),
448
+ message: z.string().trim().min(1),
449
+ recovery: z.string().trim().min(1),
450
+ retryable: z.boolean()
451
+ }).strict(),
452
+ ok: z.literal(false)
453
+ }).strict();
454
+ var CONTENT_MEMORY_KINDS = [
455
+ "audience-change",
456
+ "brand-context",
457
+ "business-context",
458
+ "temporary-campaign",
459
+ "writing-preference"
460
+ ];
461
+ var contentMemoryKindSchema = z.enum(CONTENT_MEMORY_KINDS);
462
+ var contentMemoryScopeSchema = z.enum(["global", "project"]);
463
+ var contentMemoryFieldsSchema = z.object({
464
+ content: z.string().trim().min(1).max(500),
465
+ expiresAt: z.iso.datetime().optional(),
466
+ kind: contentMemoryKindSchema
467
+ }).strict();
468
+ var contentMemoryInputSchema = contentMemoryFieldsSchema.extend({ scope: z.literal("global").default("global") }).strict().refine((input) => input.kind !== "temporary-campaign" || input.expiresAt !== void 0, {
469
+ message: "temporary campaign memory requires an expiry time"
470
+ });
471
+ var storedContentMemoryInputSchema = contentMemoryFieldsSchema.extend({
472
+ scope: contentMemoryScopeSchema
473
+ });
474
+ var contentMemoryRecordSchema = storedContentMemoryInputSchema.and(
475
+ z.object({
476
+ createdAt: z.iso.datetime(),
477
+ id: z.uuid(),
478
+ source: z.literal("user-stated"),
479
+ status: z.enum(["active", "archived", "expired"]),
480
+ updatedAt: z.iso.datetime()
481
+ }).strict()
482
+ );
483
+ var contentMemoryStoreSchema = z.object({ memories: z.array(contentMemoryRecordSchema).max(100), schemaVersion: z.literal("1") }).strict();
484
+ var contentMemoryViewSchema = contentMemoryFieldsSchema.extend({ id: z.uuid() }).strict();
485
+ var contentMemoryResultDataSchema = z.object({
486
+ memories: z.array(contentMemoryViewSchema)
487
+ }).strict();
488
+ var contentMemoryAddResultSchema = z.object({
489
+ command: z.literal("memory.add"),
490
+ data: contentMemoryResultDataSchema.extend({ memory: contentMemoryViewSchema }),
491
+ ok: z.literal(true)
492
+ }).strict();
493
+ var contentMemoryArchiveResultSchema = z.object({
494
+ command: z.literal("memory.archive"),
495
+ data: contentMemoryResultDataSchema.extend({ memory: contentMemoryViewSchema }),
496
+ ok: z.literal(true)
497
+ }).strict();
498
+ var contentMemoryCorrectResultSchema = z.object({
499
+ command: z.literal("memory.correct"),
500
+ data: contentMemoryResultDataSchema.extend({
501
+ archivedMemory: contentMemoryViewSchema,
502
+ memory: contentMemoryViewSchema
503
+ }),
504
+ ok: z.literal(true)
505
+ }).strict();
506
+ var contentMemoryListResultSchema = z.object({
507
+ command: z.literal("memory.list"),
508
+ data: contentMemoryResultDataSchema,
509
+ ok: z.literal(true)
510
+ }).strict();
511
+ var contentMemoryCommandSchema = z.enum([
512
+ "memory.add",
513
+ "memory.archive",
514
+ "memory.correct",
515
+ "memory.list"
516
+ ]);
517
+ var contentMemoryErrorResultSchema = z.object({
518
+ command: contentMemoryCommandSchema,
519
+ error: z.object({
520
+ code: z.enum([
521
+ "DXC_COMMAND_FAILED",
522
+ "DXC_MEMORY_BUSY",
523
+ "DXC_MEMORY_INPUT_INVALID",
524
+ "DXC_MEMORY_INVALID",
525
+ "DXC_MEMORY_IO_FAILED",
526
+ "DXC_MEMORY_NOT_FOUND"
527
+ ]),
528
+ actual: z.string().trim().min(1).optional(),
529
+ candidates: z.array(z.string().trim().min(1)).max(32).optional(),
530
+ expected: z.string().trim().min(1).optional(),
531
+ field: z.string().trim().min(1).optional(),
532
+ message: z.string().trim().min(1),
533
+ recovery: z.string().trim().min(1),
534
+ retryable: z.boolean()
535
+ }).strict(),
536
+ ok: z.literal(false)
537
+ }).strict();
538
+ var contentProjectListItemSchema = z.object({
539
+ availability: z.discriminatedUnion("available", [
540
+ z.object({ available: z.literal(true) }).strict(),
541
+ z.object({
542
+ available: z.literal(false),
543
+ reason: z.enum(["project-directory-missing", "project-invalid", "project-unreadable"]),
544
+ recovery: z.literal("\u8BF7\u7528\u6237\u786E\u8BA4\u9879\u76EE\u7684\u65B0\u4F4D\u7F6E\u540E\u91CD\u65B0\u8FDB\u5165\u8BE5\u9879\u76EE\u3002")
545
+ }).strict()
546
+ ]),
547
+ done: z.boolean(),
548
+ projectId: z.uuid(),
549
+ step: contentArtifactKindSchema.nullable(),
550
+ title: z.string().trim().min(1).max(160),
551
+ updatedAt: z.iso.datetime()
552
+ }).strict();
553
+ var contentProjectListResultSchema = z.object({
554
+ command: z.literal("project.list"),
555
+ data: z.object({ projects: z.array(contentProjectListItemSchema).max(1e3) }).strict(),
556
+ ok: z.literal(true)
557
+ }).strict();
558
+ var contentProjectRelinkResultSchema = z.object({
559
+ command: z.literal("project.relink"),
560
+ data: z.object({
561
+ projectId: z.uuid(),
562
+ title: z.string().trim().min(1).max(160),
563
+ updatedAt: z.iso.datetime()
564
+ }).strict(),
565
+ ok: z.literal(true)
566
+ }).strict();
567
+ var contentProjectCommandSchema = z.enum(["project.list", "project.relink"]);
568
+ var contentProjectErrorResultSchema = z.object({
569
+ command: contentProjectCommandSchema,
570
+ error: z.object({
571
+ actual: z.string().trim().min(1).optional(),
572
+ candidates: z.array(z.string().trim().min(1)).max(32).optional(),
573
+ code: z.enum([
574
+ "DXC_COMMAND_FAILED",
575
+ "DXC_PROJECT_BUSY",
576
+ "DXC_PROJECT_EXISTS",
577
+ "DXC_PROJECT_INVALID",
578
+ "DXC_PROJECT_IO_FAILED",
579
+ "DXC_PROJECT_NOT_FOUND"
580
+ ]),
581
+ expected: z.string().trim().min(1).optional(),
582
+ field: z.string().trim().min(1).optional(),
583
+ message: z.string().trim().min(1),
584
+ recovery: z.string().trim().min(1),
585
+ retryable: z.boolean()
586
+ }).strict(),
587
+ ok: z.literal(false)
588
+ }).strict();
589
+ var contentWorkflowCommandSchema = z.enum([
590
+ "workflow.complete",
591
+ "workflow.deliver",
592
+ "workflow.next",
593
+ "workflow.preview",
594
+ "workflow.repair-knowledge",
595
+ "workflow.start"
596
+ ]);
597
+ var CONTENT_WORKFLOW_LOCAL_ERROR_CODES = [
598
+ "DXC_API_BASE_URL_INVALID",
599
+ "DXC_API_REQUEST_FAILED",
600
+ "DXC_API_RESPONSE_INVALID",
601
+ "DXC_COMMAND_FAILED",
602
+ "DXC_DEVICE_IDENTITY_INVALID",
603
+ "DXC_DEVICE_IDENTITY_MISSING",
604
+ "DXC_DEVICE_IDENTITY_READ_FAILED",
605
+ "DXC_DEVICE_REFRESH_CONTEXT_MISSING",
606
+ "DXC_DEVICE_SESSION_TOKEN_MISSING",
607
+ "DXC_DRAFT_CONFIRMATION_REQUIRED",
608
+ "DXC_DRAFT_RETRY_NOT_SAFE",
609
+ "DXC_PUBLISHING_ACCOUNT_UNAVAILABLE",
610
+ "DXC_PUBLISHING_ARTICLE_INVALID",
611
+ "DXC_PUBLISHING_ASSETS_DIRECTORY_INVALID",
612
+ "DXC_PUBLISHING_AUTHOR_TOO_LONG",
613
+ "DXC_PUBLISHING_CLOUD_PREFLIGHT_FAILED",
614
+ "DXC_PUBLISHING_COVER_REQUIRED",
615
+ "DXC_PUBLISHING_COVER_TOO_LARGE",
616
+ "DXC_PUBLISHING_DIGEST_TOO_LONG",
617
+ "DXC_PUBLISHING_INLINE_ASSETS_MISMATCH",
618
+ "DXC_PUBLISHING_INLINE_IMAGE_TOO_LARGE",
619
+ "DXC_PUBLISHING_INPUT_INVALID",
620
+ "DXC_PUBLISHING_INPUT_TYPE_UNSUPPORTED",
621
+ "DXC_PUBLISHING_LOCAL_PREVIEW_ASSET_MISMATCH",
622
+ "DXC_PUBLISHING_LOCAL_PREVIEW_OUTPUT_CONFLICT",
623
+ "DXC_PUBLISHING_LOCAL_PREVIEW_TOO_LARGE",
624
+ "DXC_PUBLISHING_LOCAL_PREVIEW_WRITE_FAILED",
625
+ "DXC_PUBLISHING_PREFLIGHT_FAILED",
626
+ "DXC_PUBLISHING_TEMPLATE_HINT_MISMATCH",
627
+ "DXC_PUBLISHING_TITLE_TOO_LONG",
628
+ "DXC_PUBLISHING_TOO_MANY_INLINE_IMAGES",
629
+ "DXC_PUBLISHING_UPLOAD_URL_INVALID",
630
+ "DXC_PUBLISHING_VISUAL_ANCHOR_INVALID",
631
+ "DXC_PUBLISHING_VISUAL_PLAN_INVALID",
632
+ "DXC_PUBLISHING_VISUAL_PLAN_YAML_INVALID",
633
+ "DXC_WECHAT_NOT_CONNECTED",
634
+ "DXC_WECHAT_SESSION_INVALID",
635
+ "DXC_WECHAT_SESSION_SERVER_MISMATCH",
636
+ "DXC_WORKFLOW_ARTICLE_FIELD_INVALID",
637
+ "DXC_WORKFLOW_ARTICLE_FRONTMATTER_INVALID",
638
+ "DXC_WORKFLOW_ARTIFACT_INVALID",
639
+ "DXC_WORKFLOW_ARTIFACT_MISSING",
640
+ "DXC_WORKFLOW_BUSY",
641
+ "DXC_WORKFLOW_CONFIRMATION_REQUIRED",
642
+ "DXC_WORKFLOW_DELIVERY_REQUIRED",
643
+ "DXC_WORKFLOW_DELIVERY_STATE_INVALID",
644
+ "DXC_WORKFLOW_INPUT_MISSING",
645
+ "DXC_WORKFLOW_PREVIEW_REQUIRED",
646
+ "DXC_WORKFLOW_PROJECT_REFERENCE_INVALID",
647
+ "DXC_WORKFLOW_QUOTE_USAGE_INVALID",
648
+ "DXC_WORKFLOW_STATE_INVALID",
649
+ "DXC_WORKFLOW_STEP_INVALID",
650
+ "DXC_WORKFLOW_TITLE_FIELD_INVALID",
651
+ "DXC_WORKFLOW_TITLE_REQUIRED",
652
+ "DXC_WORK_ITEM_INVALID"
653
+ ];
654
+ var contentWorkflowFailureBaseSchema = z.object({
655
+ actual: z.string().trim().min(1).optional(),
656
+ candidates: z.array(z.string().trim().min(1)).max(100).optional(),
657
+ details: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()])).optional(),
658
+ expected: z.string().trim().min(1).optional(),
659
+ field: z.string().trim().min(1).optional(),
660
+ fields: z.record(z.string(), z.union([z.boolean(), z.number(), z.string()])).optional(),
661
+ message: z.string().trim().min(1),
662
+ recovery: z.string().trim().min(1),
663
+ retryable: z.boolean()
664
+ });
665
+ var contentWorkflowServerErrorCodeSchema = z.string().regex(
666
+ /^(?:ASSET|COVER|DEVICE|IDEMPOTENCY|INLINE|PUBLISHING|SNAPSHOT|WECHAT|WORKER)_[A-Z0-9_]+$/u
667
+ );
668
+ var contentWorkflowFailureSchema = z.union([
669
+ contentWorkflowFailureBaseSchema.extend({
670
+ code: z.literal("DXC_WORK_ITEM_STALE"),
671
+ expected: contentWorkflowWorkItemIdSchema,
672
+ field: z.literal("workItemId"),
673
+ retryable: z.literal(false)
674
+ }).strict(),
675
+ contentWorkflowFailureBaseSchema.extend({
676
+ code: z.union([
677
+ z.enum(CONTENT_WORKFLOW_LOCAL_ERROR_CODES),
678
+ contentWorkflowServerErrorCodeSchema
679
+ ])
680
+ }).strict()
681
+ ]);
682
+ var contentWorkflowErrorResultSchema = z.object({
683
+ command: contentWorkflowCommandSchema,
684
+ error: contentWorkflowFailureSchema,
685
+ ok: z.literal(false)
686
+ }).strict();
687
+
688
+ // packages/contracts/src/content-knowledge.ts
689
+ import { z as z2 } from "zod";
690
+ var CONTENT_KNOWLEDGE_SCHEMA_VERSION = "2";
691
+ var CONTENT_KNOWLEDGE_EMBEDDING_MODEL = "Xenova/bge-small-zh-v1.5";
692
+ var CONTENT_KNOWLEDGE_EMBEDDING_REVISION = "75c43b069aac4d136ba6bc1122f995fedcfd2781";
693
+ var CONTENT_KNOWLEDGE_EMBEDDING_DIMENSIONS = 512;
694
+ var CONTENT_KNOWLEDGE_EMBEDDING_QUANTIZATION = "q8";
695
+ var CONTENT_KNOWLEDGE_CHUNKER_VERSION = "dxc-markdown-chunker@3";
696
+ var contentKnowledgeSearchModeSchema = z2.enum(["hybrid", "lexical", "semantic"]);
697
+ var contentKnowledgeSourceFilterSchema = z2.enum(["all", "history", "quotes"]);
698
+ var contentKnowledgeRefSchema = z2.string().regex(/^kr1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u);
699
+ var contentKnowledgeQuoteStatusSchema = z2.enum(["active", "archived"]);
700
+ var contentKnowledgeQuoteOriginSchema = z2.enum(["original", "third-party"]);
701
+ var contentKnowledgeQuoteVerbatimUseSchema = z2.enum([
702
+ "original",
703
+ "needs-verification",
704
+ "permitted",
705
+ "do-not-use-verbatim"
706
+ ]);
707
+ var contentKnowledgeModelSchema = z2.object({
708
+ dimensions: z2.literal(CONTENT_KNOWLEDGE_EMBEDDING_DIMENSIONS),
709
+ id: z2.literal(CONTENT_KNOWLEDGE_EMBEDDING_MODEL),
710
+ quantization: z2.literal(CONTENT_KNOWLEDGE_EMBEDDING_QUANTIZATION),
711
+ revision: z2.literal(CONTENT_KNOWLEDGE_EMBEDDING_REVISION)
712
+ }).strict();
713
+ var contentKnowledgeArticleSummarySchema = z2.object({
714
+ articleId: z2.uuid(),
715
+ chunkCount: z2.number().int().positive(),
716
+ importedAt: z2.iso.datetime(),
717
+ sourceLabel: z2.string().trim().min(1).max(255),
718
+ title: z2.string().trim().min(1).max(300),
719
+ updatedAt: z2.iso.datetime()
720
+ }).strict();
721
+ var contentKnowledgeImportItemSchema = z2.object({
722
+ article: contentKnowledgeArticleSummarySchema,
723
+ semanticIndexed: z2.boolean(),
724
+ status: z2.enum(["created", "updated", "unchanged"])
725
+ }).strict();
726
+ var contentKnowledgeImportSkippedItemSchema = z2.object({
727
+ code: z2.enum(["DXC_KNOWLEDGE_ARTICLE_INVALID", "DXC_KNOWLEDGE_FILE_TOO_LARGE"]),
728
+ message: z2.string().trim().min(1),
729
+ sourceLabel: z2.string().trim().min(1).max(255)
730
+ }).strict();
731
+ var contentKnowledgeImportResultSchema = z2.object({
732
+ command: z2.literal("knowledge.import"),
733
+ data: z2.object({
734
+ imported: z2.array(contentKnowledgeImportItemSchema),
735
+ skipped: z2.array(contentKnowledgeImportSkippedItemSchema)
736
+ }).strict(),
737
+ ok: z2.literal(true)
738
+ }).strict();
739
+ var contentKnowledgeMatchLaneSchema = z2.enum(["lexical", "semantic"]);
740
+ var contentKnowledgeSearchItemBaseSchema = z2.object({
741
+ lanes: z2.array(contentKnowledgeMatchLaneSchema).min(1).max(2),
742
+ rank: z2.number().int().positive().max(20),
743
+ snippet: z2.string().trim().min(1).max(420)
744
+ }).strict();
745
+ var contentKnowledgeHistorySearchItemSchema = contentKnowledgeSearchItemBaseSchema.extend({
746
+ heading: z2.string().trim().min(1).max(300).nullable(),
747
+ knowledgeRef: contentKnowledgeRefSchema,
748
+ sourceType: z2.literal("history-article"),
749
+ sourceLabel: z2.string().trim().min(1).max(255),
750
+ title: z2.string().trim().min(1).max(300)
751
+ });
752
+ var contentKnowledgeQuoteSearchItemSchema = contentKnowledgeSearchItemBaseSchema.extend({
753
+ attribution: z2.string().trim().min(1).max(300).nullable(),
754
+ knowledgeRef: contentKnowledgeRefSchema,
755
+ origin: contentKnowledgeQuoteOriginSchema,
756
+ sourceLabel: z2.string().trim().min(1).max(300).nullable(),
757
+ sourceType: z2.literal("quote"),
758
+ tags: z2.array(z2.string().trim().min(1).max(80)).max(20),
759
+ verbatimUse: contentKnowledgeQuoteVerbatimUseSchema
760
+ });
761
+ var contentKnowledgeSearchItemSchema = z2.discriminatedUnion("sourceType", [
762
+ contentKnowledgeHistorySearchItemSchema,
763
+ contentKnowledgeQuoteSearchItemSchema
764
+ ]);
765
+ var contentKnowledgeQuoteSummarySchema = z2.object({
766
+ activeCount: z2.number().int().nonnegative(),
767
+ archivedCount: z2.number().int().nonnegative(),
768
+ sourceInitialized: z2.boolean()
769
+ }).strict();
770
+ var contentKnowledgeQuoteRecordSchema = z2.object({
771
+ attribution: z2.string().trim().min(1).max(300).nullable(),
772
+ origin: contentKnowledgeQuoteOriginSchema,
773
+ quoteId: z2.uuid(),
774
+ source: z2.string().trim().min(1).max(300).nullable(),
775
+ status: contentKnowledgeQuoteStatusSchema,
776
+ tags: z2.array(z2.string().trim().min(1).max(80)).max(20),
777
+ text: z2.string().trim().min(1).max(2e3),
778
+ verbatimUse: contentKnowledgeQuoteVerbatimUseSchema
779
+ }).strict();
780
+ var contentKnowledgeQuoteListResultSchema = z2.object({
781
+ command: z2.literal("knowledge.quotes.list"),
782
+ data: z2.object({ quotes: z2.array(contentKnowledgeQuoteRecordSchema).max(5e3) }).strict(),
783
+ ok: z2.literal(true)
784
+ }).strict();
785
+ var contentKnowledgeQuoteMutationResultSchema = z2.object({
786
+ command: z2.enum([
787
+ "knowledge.quotes.add",
788
+ "knowledge.quotes.update",
789
+ "knowledge.quotes.archive"
790
+ ]),
791
+ data: z2.object({ quote: contentKnowledgeQuoteRecordSchema, synced: z2.literal(true) }).strict(),
792
+ ok: z2.literal(true)
793
+ }).strict();
794
+ var contentKnowledgeQuoteStatusResultSchema = z2.object({
795
+ command: z2.literal("knowledge.quotes.status"),
796
+ data: contentKnowledgeQuoteSummarySchema,
797
+ ok: z2.literal(true)
798
+ }).strict();
799
+ var contentKnowledgeSearchItemLegacySchema = z2.object({
800
+ articleId: z2.uuid(),
801
+ chunkId: z2.uuid(),
802
+ chunkSha256: z2.string().regex(/^[a-f0-9]{64}$/u),
803
+ heading: z2.string().trim().min(1).max(300).nullable(),
804
+ lanes: z2.array(contentKnowledgeMatchLaneSchema).min(1).max(2),
805
+ ordinal: z2.number().int().nonnegative(),
806
+ rank: z2.number().int().positive().max(20),
807
+ snippet: z2.string().trim().min(1).max(420),
808
+ sourceLabel: z2.string().trim().min(1).max(255),
809
+ title: z2.string().trim().min(1).max(300)
810
+ }).strict();
811
+ var contentKnowledgeSearchResultSchema = z2.object({
812
+ command: z2.literal("knowledge.search"),
813
+ data: z2.object({
814
+ mode: contentKnowledgeSearchModeSchema,
815
+ query: z2.string().trim().min(1).max(500),
816
+ results: z2.array(contentKnowledgeSearchItemSchema).max(20),
817
+ sourceFilter: contentKnowledgeSourceFilterSchema
818
+ }).strict(),
819
+ ok: z2.literal(true)
820
+ }).strict();
821
+ var contentKnowledgeStatusResultSchema = z2.object({
822
+ command: z2.literal("knowledge.status"),
823
+ data: z2.object({
824
+ articleCount: z2.number().int().nonnegative(),
825
+ chunkCount: z2.number().int().nonnegative(),
826
+ modelCached: z2.boolean(),
827
+ semanticIndexedChunkCount: z2.number().int().nonnegative(),
828
+ quotes: contentKnowledgeQuoteSummarySchema
829
+ }).strict(),
830
+ ok: z2.literal(true)
831
+ }).strict();
832
+ var contentKnowledgeRemoveResultSchema = z2.object({
833
+ command: z2.literal("knowledge.remove"),
834
+ data: z2.object({
835
+ knowledgeRef: contentKnowledgeRefSchema,
836
+ removed: z2.boolean()
837
+ }).strict(),
838
+ ok: z2.literal(true)
839
+ }).strict();
840
+ var contentKnowledgeAdoptResultSchema = z2.object({
841
+ command: z2.literal("knowledge.adopt"),
842
+ data: z2.object({
843
+ adopted: z2.discriminatedUnion("sourceType", [
844
+ z2.object({
845
+ heading: z2.string().trim().min(1).max(300).nullable(),
846
+ knowledgeRef: contentKnowledgeRefSchema,
847
+ label: z2.string().trim().min(1).max(300),
848
+ snippet: z2.string().trim().min(1).max(420),
849
+ sourceType: z2.literal("history-article")
850
+ }).strict(),
851
+ z2.object({
852
+ attribution: z2.string().trim().min(1).max(300).nullable(),
853
+ knowledgeRef: contentKnowledgeRefSchema,
854
+ label: z2.string().trim().min(1).max(300),
855
+ snippet: z2.string().trim().min(1).max(420),
856
+ sourceType: z2.literal("quote"),
857
+ verbatimUse: contentKnowledgeQuoteVerbatimUseSchema
858
+ }).strict()
859
+ ]),
860
+ projectId: z2.uuid()
861
+ }).strict(),
862
+ ok: z2.literal(true)
863
+ }).strict();
864
+ var contentKnowledgeCommandSchema = z2.enum([
865
+ "knowledge.adopt",
866
+ "knowledge.import",
867
+ "knowledge.remove",
868
+ "knowledge.search",
869
+ "knowledge.status",
870
+ "knowledge.quotes.add",
871
+ "knowledge.quotes.archive",
872
+ "knowledge.quotes.list",
873
+ "knowledge.quotes.status",
874
+ "knowledge.quotes.update"
875
+ ]);
876
+ var contentKnowledgeErrorResultSchema = z2.object({
877
+ command: contentKnowledgeCommandSchema,
878
+ error: z2.object({
879
+ code: z2.enum([
880
+ "DXC_COMMAND_FAILED",
881
+ "DXC_KNOWLEDGE_ARTICLE_INVALID",
882
+ "DXC_KNOWLEDGE_BUSY",
883
+ "DXC_KNOWLEDGE_DIRECTORY_INVALID",
884
+ "DXC_KNOWLEDGE_DIRECTORY_TOO_LARGE",
885
+ "DXC_KNOWLEDGE_FILE_TOO_LARGE",
886
+ "DXC_KNOWLEDGE_INPUT_NOT_FOUND",
887
+ "DXC_KNOWLEDGE_IO_FAILED",
888
+ "DXC_KNOWLEDGE_MODEL_FAILED",
889
+ "DXC_KNOWLEDGE_QUERY_INVALID",
890
+ "DXC_KNOWLEDGE_REFERENCE_INVALID",
891
+ "DXC_KNOWLEDGE_REFERENCE_STALE",
892
+ "DXC_KNOWLEDGE_QUOTE_INVALID",
893
+ "DXC_KNOWLEDGE_QUOTE_SOURCE_NOT_INITIALIZED",
894
+ "DXC_KNOWLEDGE_SCHEMA_UNSUPPORTED",
895
+ "DXC_KNOWLEDGE_SEMANTIC_NOT_READY",
896
+ "DXC_KNOWLEDGE_STATE_INVALID"
897
+ ]),
898
+ actual: z2.string().trim().min(1).optional(),
899
+ candidates: z2.array(z2.string().trim().min(1)).max(32).optional(),
900
+ details: z2.object({
901
+ nextAction: z2.object({
902
+ choices: z2.array(
903
+ z2.object({
904
+ choiceId: z2.string().regex(/^knowledge-choice1_[A-Za-z0-9_-]+\.[a-f0-9]{32}$/u),
905
+ label: z2.string().trim().min(1).max(120)
906
+ }).strict()
907
+ ).length(2),
908
+ purpose: z2.literal("knowledge-model-unavailable"),
909
+ type: z2.literal("select-choice")
910
+ }).strict()
911
+ }).strict().optional(),
912
+ expected: z2.string().trim().min(1).optional(),
913
+ field: z2.string().trim().min(1).optional(),
914
+ message: z2.string().trim().min(1),
915
+ recovery: z2.string().trim().min(1),
916
+ retryable: z2.boolean()
917
+ }).strict(),
918
+ ok: z2.literal(false)
919
+ }).strict();
920
+
921
+ // packages/contracts/src/index.ts
922
+ import { z as z6 } from "zod";
923
+
924
+ // packages/contracts/src/publishing.ts
925
+ import { z as z3 } from "zod";
926
+ var sha256Schema = z3.string().regex(/^[a-f0-9]{64}$/u);
927
+ var wechatTemplateIdSchema = z3.enum([
928
+ "wechat-minimal@1",
929
+ "wechat-academic-paper@1",
930
+ "wechat-aurora-glass@1",
931
+ "wechat-bauhaus@1",
932
+ "wechat-cyberpunk-neon@1",
933
+ "wechat-knowledge-base@1",
934
+ "wechat-luxury-gold@1",
935
+ "wechat-morandi-forest@1",
936
+ "wechat-neo-brutalism@1",
937
+ "wechat-receipt@1",
938
+ "wechat-sunset-film@1"
939
+ ]);
940
+ var publishingUploadKindSchema = z3.enum(["article-source", "cover-image", "inline-image"]);
941
+ var publishingUploadMediaTypeSchema = z3.enum([
942
+ "text/markdown",
943
+ "text/plain",
944
+ "image/jpeg",
945
+ "image/png"
946
+ ]);
947
+ var createPublishingUploadRequestSchema = z3.object({
948
+ fileName: z3.string().trim().min(1).max(160),
949
+ kind: publishingUploadKindSchema,
950
+ mediaType: publishingUploadMediaTypeSchema,
951
+ sha256: sha256Schema,
952
+ size: z3.number().int().positive().max(5 * 1024 * 1024)
953
+ }).strict().superRefine((value, context) => {
954
+ if (value.kind === "article-source" && value.mediaType !== "text/markdown" && value.mediaType !== "text/plain") {
955
+ context.addIssue({
956
+ code: "custom",
957
+ message: "article source requires a text media type",
958
+ path: ["mediaType"]
959
+ });
960
+ }
961
+ if ((value.kind === "cover-image" || value.kind === "inline-image") && value.mediaType !== "image/jpeg" && value.mediaType !== "image/png") {
962
+ context.addIssue({
963
+ code: "custom",
964
+ message: "image upload requires a supported image media type",
965
+ path: ["mediaType"]
966
+ });
967
+ }
968
+ if (value.kind === "article-source" && value.size > 512 * 1024) {
969
+ context.addIssue({
970
+ code: "custom",
971
+ message: "article source exceeds the maximum size",
972
+ path: ["size"]
973
+ });
974
+ }
975
+ if (value.kind === "inline-image" && value.size >= 1024 * 1024) {
976
+ context.addIssue({
977
+ code: "custom",
978
+ message: "inline image must be smaller than 1 MiB",
979
+ path: ["size"]
980
+ });
981
+ }
982
+ });
983
+ var publishingUploadSessionSchema = z3.object({
984
+ expiresAt: z3.iso.datetime(),
985
+ id: z3.uuid(),
986
+ kind: publishingUploadKindSchema,
987
+ uploadUrl: z3.url()
988
+ }).strict();
989
+ var publishingUploadReceiptSchema = z3.object({
990
+ id: z3.uuid(),
991
+ sha256: sha256Schema,
992
+ size: z3.number().int().positive().max(5 * 1024 * 1024),
993
+ status: z3.literal("UPLOADED")
994
+ }).strict();
995
+ var createPublishingArticleRequestSchema = z3.object({
996
+ coverUploadId: z3.uuid(),
997
+ inlineAssets: z3.array(
998
+ z3.object({
999
+ logicalPath: z3.string().trim().min(1).max(240),
1000
+ uploadId: z3.uuid()
1001
+ }).strict()
1002
+ ).max(20).optional(),
1003
+ sourceUploadId: z3.uuid()
1004
+ }).strict().superRefine((value, context) => {
1005
+ const inlineAssets = value.inlineAssets ?? [];
1006
+ const logicalPaths = inlineAssets.map((asset) => asset.logicalPath);
1007
+ const uploadIds = inlineAssets.map((asset) => asset.uploadId);
1008
+ if (new Set(logicalPaths).size !== logicalPaths.length) {
1009
+ context.addIssue({
1010
+ code: "custom",
1011
+ message: "inline asset logical paths must be unique",
1012
+ path: ["inlineAssets"]
1013
+ });
1014
+ }
1015
+ if (new Set(uploadIds).size !== uploadIds.length) {
1016
+ context.addIssue({
1017
+ code: "custom",
1018
+ message: "inline asset uploads must be unique",
1019
+ path: ["inlineAssets"]
1020
+ });
1021
+ }
1022
+ });
1023
+ var publishingInlineAssetSchema = z3.object({
1024
+ logicalPath: z3.string().trim().min(1).max(240),
1025
+ mediaType: z3.enum(["image/jpeg", "image/png"]),
1026
+ sha256: sha256Schema
1027
+ }).strict();
1028
+ var publishingArticleSchema = z3.object({
1029
+ cover: z3.object({
1030
+ height: z3.number().int().positive().max(12e3),
1031
+ mediaType: z3.enum(["image/jpeg", "image/png"]),
1032
+ width: z3.number().int().positive().max(12e3)
1033
+ }).strict(),
1034
+ coverHash: sha256Schema,
1035
+ createdAt: z3.iso.datetime(),
1036
+ id: z3.uuid(),
1037
+ inlineAssets: z3.array(publishingInlineAssetSchema).max(20).default([]),
1038
+ sourceHash: sha256Schema
1039
+ }).strict();
1040
+ var createPublishingRenderSnapshotRequestSchema = z3.object({
1041
+ title: z3.string().trim().min(1).max(64).optional()
1042
+ }).strict();
1043
+ var publishingPreflightIssueSchema = z3.object({
1044
+ code: z3.string().trim().min(1),
1045
+ message: z3.string().trim().min(1),
1046
+ path: z3.string().trim().min(1).optional()
1047
+ }).strict();
1048
+ var publishingPreflightSchema = z3.object({
1049
+ errors: z3.array(publishingPreflightIssueSchema),
1050
+ metrics: z3.object({
1051
+ digestCharacters: z3.number().int().nonnegative(),
1052
+ externalLinkCount: z3.number().int().nonnegative(),
1053
+ htmlCharacters: z3.number().int().nonnegative(),
1054
+ imageCount: z3.number().int().nonnegative(),
1055
+ tableCount: z3.number().int().nonnegative()
1056
+ }).strict(),
1057
+ ok: z3.boolean(),
1058
+ warnings: z3.array(publishingPreflightIssueSchema)
1059
+ }).strict();
1060
+ var publishingRenderSnapshotSchema = z3.object({
1061
+ articleId: z3.uuid(),
1062
+ assetManifestHash: sha256Schema,
1063
+ author: z3.string().trim().min(1).max(16),
1064
+ commentsEnabled: z3.boolean(),
1065
+ coverHash: sha256Schema,
1066
+ createdAt: z3.iso.datetime(),
1067
+ digest: z3.string().trim().min(1).max(120),
1068
+ htmlHash: sha256Schema,
1069
+ id: z3.uuid(),
1070
+ inlineAssets: z3.array(publishingInlineAssetSchema).max(20).default([]),
1071
+ preflight: publishingPreflightSchema,
1072
+ rendererVersion: z3.string().trim().min(1),
1073
+ snapshotHash: sha256Schema,
1074
+ sourceHash: sha256Schema,
1075
+ templateId: wechatTemplateIdSchema,
1076
+ title: z3.string().trim().min(1).max(32)
1077
+ }).strict();
1078
+ var createPublishingPreviewLinkRequestSchema = z3.object({
1079
+ snapshotHash: sha256Schema
1080
+ }).strict();
1081
+ var publishingPreviewLinkSchema = z3.object({
1082
+ createdAt: z3.iso.datetime().optional(),
1083
+ expiresAt: z3.iso.datetime(),
1084
+ expiresInSeconds: z3.number().int().positive().max(24 * 60 * 60).optional(),
1085
+ snapshotHash: sha256Schema,
1086
+ url: z3.url()
1087
+ }).strict();
1088
+ var publishingPreviewSelectionStateSchema = z3.object({
1089
+ rootSnapshotHash: sha256Schema,
1090
+ rootSnapshotId: z3.uuid(),
1091
+ selectedSnapshotHash: sha256Schema,
1092
+ selectedSnapshotId: z3.uuid(),
1093
+ selectionRevision: z3.number().int().nonnegative(),
1094
+ templateId: wechatTemplateIdSchema,
1095
+ updatedAt: z3.iso.datetime(),
1096
+ viewed: z3.boolean(),
1097
+ viewedAt: z3.iso.datetime().nullable()
1098
+ }).strict();
1099
+ var createPublishingApprovalRequestSchema = z3.object({
1100
+ accountId: z3.uuid(),
1101
+ confirmed: z3.literal(true),
1102
+ snapshotHash: sha256Schema
1103
+ }).strict();
1104
+ var publishingApprovalSchema = z3.object({
1105
+ accountId: z3.uuid(),
1106
+ confirmedAt: z3.iso.datetime(),
1107
+ id: z3.uuid(),
1108
+ rootSnapshotHash: sha256Schema,
1109
+ rootSnapshotId: z3.uuid(),
1110
+ selectedSnapshotHash: sha256Schema,
1111
+ selectedSnapshotId: z3.uuid(),
1112
+ templateId: wechatTemplateIdSchema
1113
+ }).strict();
1114
+ var createPublishingDraftIntentRequestSchema = z3.object({
1115
+ approvalId: z3.uuid(),
1116
+ previousIntentId: z3.uuid().optional()
1117
+ }).strict();
1118
+ var publishingDraftStatusSchema = z3.enum([
1119
+ "QUEUED",
1120
+ "PREPARING",
1121
+ "UPLOADING_ASSETS",
1122
+ "ASSET_UPLOAD_UNVERIFIED",
1123
+ "CREATING_DRAFT",
1124
+ "VERIFYING",
1125
+ "SUCCEEDED",
1126
+ "CREATED_UNVERIFIED",
1127
+ "FAILED"
1128
+ ]);
1129
+ var publishingDraftIntentSchema = z3.object({
1130
+ accountId: z3.uuid(),
1131
+ approvalId: z3.uuid(),
1132
+ createdAt: z3.iso.datetime(),
1133
+ errorCode: z3.string().trim().min(1).optional(),
1134
+ id: z3.uuid(),
1135
+ mediaId: z3.string().trim().min(1).max(128).optional(),
1136
+ progress: z3.object({
1137
+ label: z3.string().trim().min(1).max(40),
1138
+ message: z3.string().trim().min(1).max(300),
1139
+ nextAction: z3.string().trim().min(1).max(300),
1140
+ pollAfterSeconds: z3.number().int().positive().max(60).nullable(),
1141
+ terminal: z3.boolean()
1142
+ }).strict(),
1143
+ snapshotHash: sha256Schema,
1144
+ status: publishingDraftStatusSchema,
1145
+ updatedAt: z3.iso.datetime(),
1146
+ verification: z3.object({
1147
+ authorMatched: z3.boolean(),
1148
+ contentMatched: z3.boolean(),
1149
+ digestMatched: z3.boolean(),
1150
+ titleMatched: z3.boolean()
1151
+ }).strict().optional()
1152
+ }).strict();
1153
+ var publishingDraftIntentResponseSchema = z3.object({
1154
+ intent: publishingDraftIntentSchema
1155
+ }).strict();
1156
+ var publishingDraftAttentionDiagnosticsSchema = z3.object({
1157
+ errorCode: z3.string().trim().min(1).optional(),
1158
+ intentId: z3.uuid(),
1159
+ reason: z3.object({
1160
+ message: z3.string().trim().min(1).max(500),
1161
+ nextAction: z3.string().trim().min(1).max(500),
1162
+ phase: z3.enum([
1163
+ "preparation",
1164
+ "asset-upload",
1165
+ "draft-create",
1166
+ "draft-readback",
1167
+ "verification",
1168
+ "unknown"
1169
+ ]),
1170
+ retryAllowed: z3.boolean()
1171
+ }).strict(),
1172
+ status: publishingDraftStatusSchema,
1173
+ verification: z3.object({
1174
+ authorMatched: z3.boolean(),
1175
+ coverMatched: z3.boolean().nullable(),
1176
+ contentMatched: z3.boolean(),
1177
+ digestMatched: z3.boolean(),
1178
+ firstDifference: z3.enum(["image-count", "image-identity", "image-order", "text"]).nullable().optional(),
1179
+ imageMismatches: z3.array(
1180
+ z3.object({
1181
+ actualIndex: z3.number().int().nonnegative().optional(),
1182
+ expectedIndex: z3.number().int().nonnegative().optional(),
1183
+ kind: z3.enum(["identity", "missing", "order", "unexpected"]),
1184
+ logicalPath: z3.string().trim().min(1).max(240).optional(),
1185
+ role: z3.enum(["cover", "inline-image"])
1186
+ }).strict()
1187
+ ).max(41),
1188
+ titleMatched: z3.boolean()
1189
+ }).strict().optional()
1190
+ }).strict();
1191
+
1192
+ // packages/contracts/src/content-monitor.ts
1193
+ import { z as z5 } from "zod";
1194
+
1195
+ // packages/contracts/src/content-source.ts
1196
+ import { z as z4 } from "zod";
1197
+ var sourceFetchKindSchema = z4.enum(["rss", "api", "html"]);
1198
+ var sourceExecutionLocationSchema = z4.literal("local-device");
1199
+ var sourceDataTransitSchema = z4.literal("local-only");
1200
+ var sourceCaptureMetadataSchema = z4.object({
1201
+ capturedAt: z4.iso.datetime(),
1202
+ contentHash: z4.string().regex(/^[a-f0-9]{64}$/u),
1203
+ dataTransit: sourceDataTransitSchema,
1204
+ executionLocation: sourceExecutionLocationSchema,
1205
+ extractor: z4.string().trim().min(1).max(120),
1206
+ finalUrl: z4.url(),
1207
+ mediaType: z4.string().trim().min(1).max(160),
1208
+ sourceUrl: z4.url()
1209
+ }).strict();
1210
+ var sourceFeedItemSchema = z4.object({
1211
+ id: z4.string().trim().min(1).max(256),
1212
+ publishedAt: z4.iso.datetime().optional(),
1213
+ summary: z4.string().trim().min(1).max(2e3).optional(),
1214
+ title: z4.string().trim().min(1).max(500),
1215
+ url: z4.url().optional()
1216
+ }).strict();
1217
+ var sourceHtmlDocumentSchema = z4.object({
1218
+ canonicalUrl: z4.url().optional(),
1219
+ excerpt: z4.string().trim().min(1).max(12e3),
1220
+ title: z4.string().trim().min(1).max(500)
1221
+ }).strict();
1222
+ var sourceFetchDataSchema = z4.discriminatedUnion("kind", [
1223
+ z4.object({
1224
+ capture: sourceCaptureMetadataSchema,
1225
+ items: z4.array(sourceFeedItemSchema).max(100),
1226
+ kind: z4.literal("rss")
1227
+ }).strict(),
1228
+ z4.object({
1229
+ capture: sourceCaptureMetadataSchema,
1230
+ kind: z4.literal("api"),
1231
+ payload: z4.unknown()
1232
+ }).strict(),
1233
+ z4.object({
1234
+ capture: sourceCaptureMetadataSchema,
1235
+ document: sourceHtmlDocumentSchema,
1236
+ kind: z4.literal("html")
1237
+ }).strict()
1238
+ ]);
1239
+ var sourceFetchResultSchema = z4.object({
1240
+ command: z4.literal("source.fetch"),
1241
+ data: sourceFetchDataSchema,
1242
+ ok: z4.literal(true)
1243
+ }).strict();
1244
+ var sourceFetchErrorResultSchema = z4.object({
1245
+ command: z4.literal("source.fetch"),
1246
+ error: z4.object({
1247
+ code: z4.enum([
1248
+ "DXC_SOURCE_AUTH_MISSING",
1249
+ "DXC_SOURCE_CONTENT_INVALID",
1250
+ "DXC_SOURCE_FETCH_FAILED",
1251
+ "DXC_SOURCE_REDIRECT_LIMIT",
1252
+ "DXC_SOURCE_RESPONSE_TOO_LARGE",
1253
+ "DXC_SOURCE_URL_BLOCKED",
1254
+ "DXC_SOURCE_URL_INVALID"
1255
+ ]).or(z4.literal("DXC_SOURCE_FAILED")),
1256
+ message: z4.string().trim().min(1).max(500),
1257
+ recovery: z4.string().trim().min(1).max(800).optional()
1258
+ }).strict(),
1259
+ ok: z4.literal(false)
1260
+ }).strict();
1261
+
1262
+ // packages/contracts/src/content-monitor.ts
1263
+ var contentMonitorSourceSchema = z5.object({
1264
+ bearerEnvironment: z5.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u).nullable(),
1265
+ createdAt: z5.iso.datetime(),
1266
+ enabled: z5.boolean(),
1267
+ headerEnvironments: z5.array(
1268
+ z5.object({
1269
+ environment: z5.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
1270
+ header: z5.string().regex(/^[A-Za-z0-9-]+$/u)
1271
+ }).strict()
1272
+ ).max(12),
1273
+ id: z5.uuid(),
1274
+ kind: sourceFetchKindSchema,
1275
+ name: z5.string().trim().min(1).max(120),
1276
+ rssLimit: z5.number().int().min(1).max(100).nullable(),
1277
+ url: z5.url()
1278
+ }).strict();
1279
+ var contentMonitorSourceSummarySchema = contentMonitorSourceSchema.extend({
1280
+ lastRunAt: z5.iso.datetime().nullable(),
1281
+ lastRunSummary: z5.string().trim().min(1).max(200).nullable(),
1282
+ latestItemAt: z5.iso.datetime().nullable(),
1283
+ observedItemCount: z5.number().int().nonnegative()
1284
+ });
1285
+ var contentMonitorRunSourceResultSchema = z5.object({
1286
+ failureMessage: z5.string().trim().min(1).max(500).nullable(),
1287
+ monitoredItemCount: z5.number().int().nonnegative(),
1288
+ newItemCount: z5.number().int().nonnegative(),
1289
+ sourceId: z5.uuid(),
1290
+ sourceName: z5.string().trim().min(1).max(120),
1291
+ summary: z5.string().trim().min(1).max(200),
1292
+ unchangedItemCount: z5.number().int().nonnegative(),
1293
+ updatedItemCount: z5.number().int().nonnegative()
1294
+ }).strict();
1295
+ var contentMonitorAddResultSchema = z5.object({
1296
+ command: z5.literal("monitor.add"),
1297
+ data: z5.object({
1298
+ source: contentMonitorSourceSchema,
1299
+ summary: z5.string().trim().min(1).max(200)
1300
+ }).strict(),
1301
+ ok: z5.literal(true)
1302
+ }).strict();
1303
+ var contentMonitorListResultSchema = z5.object({
1304
+ command: z5.literal("monitor.list"),
1305
+ data: z5.object({
1306
+ sources: z5.array(contentMonitorSourceSummarySchema),
1307
+ summary: z5.string().trim().min(1).max(200)
1308
+ }).strict(),
1309
+ ok: z5.literal(true)
1310
+ }).strict();
1311
+ var contentMonitorRunResultSchema = z5.object({
1312
+ command: z5.literal("monitor.run"),
1313
+ data: z5.object({
1314
+ failedSourceCount: z5.number().int().nonnegative(),
1315
+ finishedAt: z5.iso.datetime(),
1316
+ results: z5.array(contentMonitorRunSourceResultSchema),
1317
+ startedAt: z5.iso.datetime(),
1318
+ summary: z5.string().trim().min(1).max(200)
1319
+ }).strict(),
1320
+ ok: z5.literal(true)
1321
+ }).strict();
1322
+ var contentMonitorStatusResultSchema = z5.object({
1323
+ command: z5.literal("monitor.status"),
1324
+ data: z5.object({
1325
+ databasePath: z5.literal("~/.dxc/source-monitor.sqlite"),
1326
+ enabledSourceCount: z5.number().int().nonnegative(),
1327
+ latestRunAt: z5.iso.datetime().nullable(),
1328
+ latestRunSummary: z5.string().trim().min(1).max(200).nullable(),
1329
+ sourceCount: z5.number().int().nonnegative(),
1330
+ summary: z5.string().trim().min(1).max(200)
1331
+ }).strict(),
1332
+ ok: z5.literal(true)
1333
+ }).strict();
1334
+ var contentMonitorRemoveResultSchema = z5.object({
1335
+ command: z5.literal("monitor.remove"),
1336
+ data: z5.object({
1337
+ removed: z5.boolean(),
1338
+ sourceId: z5.uuid(),
1339
+ summary: z5.string().trim().min(1).max(200)
1340
+ }).strict(),
1341
+ ok: z5.literal(true)
1342
+ }).strict();
1343
+ var contentMonitorCommandSchema = z5.enum([
1344
+ "monitor.add",
1345
+ "monitor.list",
1346
+ "monitor.remove",
1347
+ "monitor.run",
1348
+ "monitor.status"
1349
+ ]);
1350
+ var contentMonitorErrorResultSchema = z5.object({
1351
+ command: contentMonitorCommandSchema,
1352
+ error: z5.object({
1353
+ code: z5.enum([
1354
+ "DXC_MONITOR_IO_FAILED",
1355
+ "DXC_MONITOR_SCHEMA_UNSUPPORTED",
1356
+ "DXC_MONITOR_SOURCE_INVALID",
1357
+ "DXC_MONITOR_SOURCE_NOT_FOUND",
1358
+ "DXC_MONITOR_STATE_INVALID"
1359
+ ]),
1360
+ message: z5.string().trim().min(1).max(500)
1361
+ }).strict(),
1362
+ ok: z5.literal(false)
1363
+ }).strict();
1364
+
1365
+ // packages/contracts/src/index.ts
1366
+ var liveHealthResponseSchema = z6.object({
1367
+ status: z6.literal("ok")
1368
+ }).strict();
1369
+ var readyHealthResponseSchema = z6.object({
1370
+ status: z6.literal("ready"),
1371
+ checks: z6.object({
1372
+ configuration: z6.literal("ok")
1373
+ }).strict()
1374
+ }).strict();
1375
+ var versionResultSchema = z6.object({
1376
+ ok: z6.literal(true),
1377
+ command: z6.literal("version"),
1378
+ data: z6.object({
1379
+ cliVersion: z6.string().min(1),
1380
+ nodeVersion: z6.string().min(1)
1381
+ }).strict()
1382
+ }).strict();
1383
+ var doctorCheckSchema = z6.object({
1384
+ name: z6.enum(["node-runtime", "working-directory"]),
1385
+ status: z6.enum(["ok", "error"]),
1386
+ message: z6.string().min(1)
1387
+ }).strict();
1388
+ var doctorResultSchema = z6.object({
1389
+ ok: z6.boolean(),
1390
+ command: z6.literal("doctor"),
1391
+ data: z6.object({
1392
+ status: z6.enum(["ok", "error"]),
1393
+ checks: z6.array(doctorCheckSchema)
1394
+ }).strict()
1395
+ }).strict();
1396
+ var articleAssetSchema = z6.object({
1397
+ logicalPath: z6.string().trim().min(1),
1398
+ role: z6.enum(["cover", "inline"])
1399
+ }).strict();
1400
+ var articleBundleSchema = z6.object({
1401
+ schemaVersion: z6.literal("1"),
1402
+ title: z6.string().trim().min(1),
1403
+ author: z6.string().trim().min(1),
1404
+ digest: z6.string().trim().min(1),
1405
+ templateHint: wechatTemplateIdSchema.optional(),
1406
+ coverImage: z6.string().trim().min(1).optional(),
1407
+ commentsEnabled: z6.boolean(),
1408
+ tags: z6.array(z6.string().trim().min(1)),
1409
+ markdown: z6.string().trim().min(1),
1410
+ assets: z6.array(articleAssetSchema)
1411
+ }).strict();
1412
+ var preflightIssueSchema = z6.object({
1413
+ code: z6.string().trim().min(1),
1414
+ path: z6.string().trim().min(1).optional(),
1415
+ message: z6.string().trim().min(1)
1416
+ }).strict();
1417
+ var preflightResultSchema = z6.object({
1418
+ ok: z6.boolean(),
1419
+ errors: z6.array(preflightIssueSchema),
1420
+ warnings: z6.array(preflightIssueSchema),
1421
+ metrics: z6.object({
1422
+ digestCharacters: z6.number().int().nonnegative(),
1423
+ htmlCharacters: z6.number().int().nonnegative(),
1424
+ imageCount: z6.number().int().nonnegative(),
1425
+ externalLinkCount: z6.number().int().nonnegative(),
1426
+ tableCount: z6.number().int().nonnegative()
1427
+ }).strict()
1428
+ }).strict();
1429
+ var wechatRenderResultSchema = z6.object({
1430
+ templateId: wechatTemplateIdSchema,
1431
+ rendererVersion: z6.string().trim().min(1),
1432
+ sourceHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1433
+ htmlHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1434
+ html: z6.string().min(1),
1435
+ preflight: preflightResultSchema
1436
+ }).strict();
1437
+ var wechatPermissionIdSchema = z6.union([z6.literal(3), z6.literal(11)]);
1438
+ var deviceBindingSessionStatusSchema = z6.enum([
1439
+ "CREATED",
1440
+ "PROVED",
1441
+ "AUTHORIZATION_PENDING",
1442
+ "BOUND",
1443
+ "EXPIRED",
1444
+ "FAILED"
1445
+ ]);
1446
+ var createDeviceBindingSessionRequestSchema = z6.object({
1447
+ deviceName: z6.string().trim().min(1).max(80),
1448
+ installationId: z6.uuid(),
1449
+ publicKeyPem: z6.string().min(80).max(2048)
1450
+ }).strict();
1451
+ var createDeviceBindingSessionResponseSchema = z6.object({
1452
+ challenge: z6.string().regex(/^[A-Za-z0-9_-]{43,128}$/u),
1453
+ expiresAt: z6.iso.datetime(),
1454
+ id: z6.uuid()
1455
+ }).strict();
1456
+ var proveDeviceBindingSessionRequestSchema = z6.object({
1457
+ challenge: z6.string().regex(/^[A-Za-z0-9_-]{43,128}$/u),
1458
+ deviceRefreshTokenHash: z6.string().regex(/^[a-f0-9]{64}$/u).optional(),
1459
+ deviceSessionTokenHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1460
+ signature: z6.string().regex(/^[A-Za-z0-9_-]{64,256}$/u)
1461
+ }).strict();
1462
+ var proveDeviceBindingSessionResponseSchema = z6.object({
1463
+ bindingToken: z6.string().min(32).max(256),
1464
+ expiresAt: z6.iso.datetime(),
1465
+ id: z6.uuid(),
1466
+ status: z6.literal("PROVED")
1467
+ }).strict();
1468
+ var deviceSessionIdentitySchema = z6.object({
1469
+ deviceId: z6.uuid(),
1470
+ deviceName: z6.string().trim().min(1).max(80),
1471
+ expiresAt: z6.iso.datetime(),
1472
+ tenantId: z6.uuid(),
1473
+ userId: z6.uuid()
1474
+ }).strict();
1475
+ var deviceSessionStatusResponseSchema = z6.object({
1476
+ identity: deviceSessionIdentitySchema
1477
+ }).strict();
1478
+ var deviceSessionCredentialEnrollmentRequestSchema = z6.object({
1479
+ refreshTokenHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1480
+ signature: z6.string().regex(/^[A-Za-z0-9_-]{64,256}$/u)
1481
+ }).strict();
1482
+ var deviceSessionRefreshRequestSchema = z6.object({
1483
+ nextDeviceSessionTokenHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1484
+ nextRefreshTokenHash: z6.string().regex(/^[a-f0-9]{64}$/u),
1485
+ refreshToken: z6.string().regex(/^[A-Za-z0-9_-]{43,256}$/u),
1486
+ rotationId: z6.uuid(),
1487
+ signature: z6.string().regex(/^[A-Za-z0-9_-]{64,256}$/u)
1488
+ }).strict();
1489
+ var wechatLoginSessionPurposeSchema = z6.enum(["link", "login", "start"]);
1490
+ var wechatLoginSessionStatusSchema = z6.enum([
1491
+ "URL_READY",
1492
+ "EXCHANGING",
1493
+ "IDENTIFIED",
1494
+ "SUCCEEDED",
1495
+ "EXPIRED",
1496
+ "FAILED"
1497
+ ]);
1498
+ var wechatLoginFailureCodeSchema = z6.enum([
1499
+ "WECHAT_LOGIN_DEVICE_UNAUTHORIZED",
1500
+ "WECHAT_LOGIN_IDENTITY_CONFLICT",
1501
+ "WECHAT_LOGIN_IDENTITY_NOT_LINKED",
1502
+ "WECHAT_LOGIN_PROVIDER_FAILED",
1503
+ "WECHAT_LOGIN_SESSION_INVALID"
1504
+ ]);
1505
+ var createWechatLoginSessionRequestSchema = z6.object({
1506
+ purpose: wechatLoginSessionPurposeSchema
1507
+ }).strict();
1508
+ var createWechatLoginSessionResponseSchema = z6.object({
1509
+ authorizationUrl: z6.url(),
1510
+ expiresAt: z6.iso.datetime(),
1511
+ id: z6.uuid(),
1512
+ pollToken: z6.string().min(32).max(256),
1513
+ purpose: wechatLoginSessionPurposeSchema
1514
+ }).strict();
1515
+ var wechatLoginSessionResponseSchema = z6.object({
1516
+ expiresAt: z6.iso.datetime(),
1517
+ failureCode: wechatLoginFailureCodeSchema.optional(),
1518
+ id: z6.uuid(),
1519
+ identity: deviceSessionIdentitySchema.optional(),
1520
+ purpose: wechatLoginSessionPurposeSchema,
1521
+ status: wechatLoginSessionStatusSchema
1522
+ }).strict().superRefine((session, context) => {
1523
+ if (session.status === "SUCCEEDED" && session.identity === void 0) {
1524
+ context.addIssue({
1525
+ code: "custom",
1526
+ message: "successful login session requires an identity"
1527
+ });
1528
+ }
1529
+ if (session.status === "FAILED" && session.failureCode === void 0) {
1530
+ context.addIssue({
1531
+ code: "custom",
1532
+ message: "failed login session requires a failure code"
1533
+ });
1534
+ }
1535
+ if (session.status !== "FAILED" && session.failureCode !== void 0) {
1536
+ context.addIssue({
1537
+ code: "custom",
1538
+ message: "only failed login session may expose a failure code"
1539
+ });
1540
+ }
1541
+ });
1542
+ var wechatAccountSchema = z6.object({
1543
+ id: z6.uuid(),
1544
+ displayName: z6.string().trim().min(1),
1545
+ accountType: z6.string().trim().min(1),
1546
+ status: z6.enum(["ACTIVE", "PERMISSION_CHANGED", "REVOKED"]),
1547
+ permissions: z6.array(wechatPermissionIdSchema),
1548
+ draftCapability: z6.enum(["available", "missing", "revoked"])
1549
+ }).strict();
1550
+ var createWechatAuthorizationSessionResponseSchema = z6.object({
1551
+ id: z6.uuid(),
1552
+ authorizationUrl: z6.url(),
1553
+ pollToken: z6.string().min(32).max(256),
1554
+ expiresAt: z6.iso.datetime()
1555
+ }).strict();
1556
+ var wechatAuthorizationSessionResponseSchema = z6.object({
1557
+ id: z6.uuid(),
1558
+ status: z6.enum(["URL_READY", "EXCHANGING", "AUTHORIZED", "BOUND", "EXPIRED", "FAILED"]),
1559
+ expiresAt: z6.iso.datetime(),
1560
+ account: wechatAccountSchema.optional()
1561
+ }).strict();
1562
+ var wechatAccountsResponseSchema = z6.object({
1563
+ accounts: z6.array(wechatAccountSchema)
1564
+ }).strict();
1565
+ var apiErrorResponseSchema = z6.object({
1566
+ error: z6.object({
1567
+ code: z6.string().trim().min(1),
1568
+ message: z6.string().trim().min(1),
1569
+ retryable: z6.boolean()
1570
+ }).strict()
1571
+ }).strict();
1572
+
1573
+ // apps/cli/src/local-state.ts
1574
+ import { randomUUID } from "node:crypto";
1575
+ import { constants as fileConstants } from "node:fs";
1576
+ import { chmod, lstat, mkdir, open, rename, unlink } from "node:fs/promises";
1577
+ import path from "node:path";
1578
+ import { setTimeout as delay } from "node:timers/promises";
1579
+ var LocalStateError = class extends Error {
1580
+ constructor(failure) {
1581
+ super(failure);
1582
+ this.failure = failure;
1583
+ this.name = "LocalStateError";
1584
+ }
1585
+ failure;
1586
+ };
1587
+ function errorCode(error) {
1588
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
1589
+ }
1590
+ function ownedByCurrentUser(userId, ownerId) {
1591
+ return userId === void 0 || userId === ownerId;
1592
+ }
1593
+ async function ensurePrivateDirectory(directory) {
1594
+ try {
1595
+ await mkdir(directory, { mode: 448, recursive: true });
1596
+ const metadata = await lstat(directory);
1597
+ const userId = typeof process.getuid === "function" ? process.getuid() : void 0;
1598
+ if (!metadata.isDirectory() || metadata.isSymbolicLink() || !ownedByCurrentUser(userId, metadata.uid)) {
1599
+ throw new LocalStateError("invalid");
1600
+ }
1601
+ await chmod(directory, 448);
1602
+ } catch (error) {
1603
+ if (error instanceof LocalStateError) {
1604
+ throw error;
1605
+ }
1606
+ if (errorCode(error) === "ELOOP") {
1607
+ throw new LocalStateError("invalid");
1608
+ }
1609
+ throw new LocalStateError("io");
1610
+ }
1611
+ }
1612
+ async function ensurePrivateRegularFile(target) {
1613
+ await ensurePrivateDirectory(path.dirname(target));
1614
+ let handle;
1615
+ try {
1616
+ handle = await open(
1617
+ target,
1618
+ fileConstants.O_CREAT | fileConstants.O_RDWR | fileConstants.O_NOFOLLOW,
1619
+ 384
1620
+ );
1621
+ const metadata = await handle.stat();
1622
+ const userId = typeof process.getuid === "function" ? process.getuid() : void 0;
1623
+ if (!metadata.isFile() || !ownedByCurrentUser(userId, metadata.uid)) {
1624
+ throw new LocalStateError("invalid");
1625
+ }
1626
+ await handle.chmod(384);
1627
+ } catch (error) {
1628
+ if (error instanceof LocalStateError) {
1629
+ throw error;
1630
+ }
1631
+ if (errorCode(error) === "ELOOP") {
1632
+ throw new LocalStateError("invalid");
1633
+ }
1634
+ throw new LocalStateError("io");
1635
+ } finally {
1636
+ await handle?.close();
1637
+ }
1638
+ }
1639
+ async function readPrivateFile(target, maximumBytes) {
1640
+ const contents = await readPrivateBuffer(target, maximumBytes);
1641
+ return contents.toString("utf8");
1642
+ }
1643
+ async function readPrivateBuffer(target, maximumBytes) {
1644
+ let handle;
1645
+ try {
1646
+ handle = await open(target, fileConstants.O_RDONLY | fileConstants.O_NOFOLLOW);
1647
+ } catch (error) {
1648
+ if (errorCode(error) === "ENOENT") {
1649
+ throw new LocalStateError("missing");
1650
+ }
1651
+ if (errorCode(error) === "ELOOP") {
1652
+ throw new LocalStateError("invalid");
1653
+ }
1654
+ throw new LocalStateError("io");
1655
+ }
1656
+ try {
1657
+ const metadata = await handle.stat();
1658
+ const userId = typeof process.getuid === "function" ? process.getuid() : void 0;
1659
+ if (!metadata.isFile() || !ownedByCurrentUser(userId, metadata.uid) || metadata.size > maximumBytes || process.platform !== "win32" && (metadata.mode & 63) !== 0) {
1660
+ throw new LocalStateError("invalid");
1661
+ }
1662
+ return await handle.readFile();
1663
+ } catch (error) {
1664
+ if (error instanceof LocalStateError) {
1665
+ throw error;
1666
+ }
1667
+ throw new LocalStateError("io");
1668
+ } finally {
1669
+ await handle.close();
1670
+ }
1671
+ }
1672
+ async function writePrivateJson(target, value) {
1673
+ await writePrivateBuffer(target, Buffer.from(`${JSON.stringify(value, void 0, 2)}
1674
+ `, "utf8"));
1675
+ }
1676
+ async function writePrivateBuffer(target, value) {
1677
+ const directory = path.dirname(target);
1678
+ await ensurePrivateDirectory(directory);
1679
+ const temporary = path.join(directory, `.${path.basename(target)}.${randomUUID()}.tmp`);
1680
+ let handle;
1681
+ try {
1682
+ handle = await open(
1683
+ temporary,
1684
+ fileConstants.O_CREAT | fileConstants.O_EXCL | fileConstants.O_WRONLY | fileConstants.O_NOFOLLOW,
1685
+ 384
1686
+ );
1687
+ await handle.writeFile(value);
1688
+ await handle.sync();
1689
+ await handle.close();
1690
+ handle = void 0;
1691
+ await rename(temporary, target);
1692
+ await chmod(target, 384);
1693
+ } catch (error) {
1694
+ throw error instanceof LocalStateError ? error : new LocalStateError("io");
1695
+ } finally {
1696
+ await handle?.close();
1697
+ await unlink(temporary).catch(() => void 0);
1698
+ }
1699
+ }
1700
+ var LOCK_WAIT_MILLISECONDS = 3e3;
1701
+ var LOCK_RETRY_MILLISECONDS = 10;
1702
+ var LOCK_STALE_MILLISECONDS = 5 * 6e4;
1703
+ async function readLockOwner(lockPath) {
1704
+ let handle;
1705
+ try {
1706
+ handle = await open(lockPath, fileConstants.O_RDONLY | fileConstants.O_NOFOLLOW);
1707
+ const metadata = await handle.stat();
1708
+ if (!metadata.isFile() || metadata.size < 1 || metadata.size > 256) {
1709
+ throw new LocalStateError("invalid");
1710
+ }
1711
+ const value = JSON.parse(await handle.readFile("utf8"));
1712
+ if (typeof value !== "object" || value === null || !("pid" in value) || !Number.isSafeInteger(value.pid) || Number(value.pid) <= 0 || !("token" in value) || typeof value.token !== "string" || value.token.length < 1) {
1713
+ throw new LocalStateError("invalid");
1714
+ }
1715
+ return { pid: Number(value.pid), token: value.token };
1716
+ } catch (error) {
1717
+ if (error instanceof LocalStateError) {
1718
+ throw error;
1719
+ }
1720
+ if (errorCode(error) === "ELOOP") {
1721
+ throw new LocalStateError("invalid");
1722
+ }
1723
+ throw error;
1724
+ } finally {
1725
+ await handle?.close();
1726
+ }
1727
+ }
1728
+ function processIsAlive(pid) {
1729
+ try {
1730
+ process.kill(pid, 0);
1731
+ return true;
1732
+ } catch (error) {
1733
+ return errorCode(error) !== "ESRCH";
1734
+ }
1735
+ }
1736
+ async function acquireReclaimGuard(lockPath, identity) {
1737
+ const owner = { pid: process.pid, token: randomUUID() };
1738
+ const basePath = `${lockPath}.reclaim-${String(identity.dev)}-${String(identity.ino)}`;
1739
+ let guardPath = basePath;
1740
+ for (let generation = 0; generation < 32; generation += 1) {
1741
+ let handle;
1742
+ try {
1743
+ handle = await open(
1744
+ guardPath,
1745
+ fileConstants.O_CREAT | fileConstants.O_EXCL | fileConstants.O_WRONLY | fileConstants.O_NOFOLLOW,
1746
+ 384
1747
+ );
1748
+ await handle.writeFile(`${JSON.stringify(owner)}
1749
+ `);
1750
+ await handle.sync();
1751
+ await handle.close();
1752
+ handle = void 0;
1753
+ return async () => {
1754
+ try {
1755
+ const current = await readLockOwner(guardPath);
1756
+ if (current.token === owner.token) {
1757
+ await unlink(guardPath);
1758
+ }
1759
+ } catch (error) {
1760
+ if (errorCode(error) !== "ENOENT") {
1761
+ throw error instanceof LocalStateError ? error : new LocalStateError("io");
1762
+ }
1763
+ }
1764
+ };
1765
+ } catch (error) {
1766
+ await handle?.close();
1767
+ if (errorCode(error) === "ELOOP") {
1768
+ throw new LocalStateError("invalid");
1769
+ }
1770
+ if (errorCode(error) !== "EEXIST") {
1771
+ throw error instanceof LocalStateError ? error : new LocalStateError("io");
1772
+ }
1773
+ const metadata = await lstat(guardPath);
1774
+ let previous;
1775
+ try {
1776
+ previous = await readLockOwner(guardPath);
1777
+ } catch (ownerError) {
1778
+ if (!(ownerError instanceof LocalStateError && ownerError.failure === "invalid")) {
1779
+ throw ownerError;
1780
+ }
1781
+ }
1782
+ if (previous !== void 0 && processIsAlive(previous.pid)) {
1783
+ return void 0;
1784
+ }
1785
+ if (previous === void 0 && Date.now() - metadata.mtimeMs <= LOCK_STALE_MILLISECONDS) {
1786
+ return void 0;
1787
+ }
1788
+ const predecessor = previous?.token ?? `${metadata.ino}-${Math.trunc(metadata.mtimeMs)}`;
1789
+ guardPath = `${basePath}.next-${predecessor}`;
1790
+ }
1791
+ }
1792
+ throw new LocalStateError("invalid");
1793
+ }
1794
+ async function acquirePrivateFileLock(target, hooks) {
1795
+ const directory = path.dirname(target);
1796
+ await ensurePrivateDirectory(directory);
1797
+ const lockPath = path.join(directory, `.${path.basename(target)}.lock`);
1798
+ const startedAt = Date.now();
1799
+ const owner = { pid: process.pid, token: randomUUID() };
1800
+ while (Date.now() - startedAt <= LOCK_WAIT_MILLISECONDS) {
1801
+ let handle;
1802
+ try {
1803
+ handle = await open(
1804
+ lockPath,
1805
+ fileConstants.O_CREAT | fileConstants.O_EXCL | fileConstants.O_WRONLY | fileConstants.O_NOFOLLOW,
1806
+ 384
1807
+ );
1808
+ await handle.writeFile(`${JSON.stringify(owner)}
1809
+ `);
1810
+ await handle.sync();
1811
+ await handle.close();
1812
+ handle = void 0;
1813
+ return async () => {
1814
+ let current;
1815
+ try {
1816
+ current = await readLockOwner(lockPath);
1817
+ } catch (error) {
1818
+ if (errorCode(error) === "ENOENT") {
1819
+ return;
1820
+ }
1821
+ throw error instanceof LocalStateError ? error : new LocalStateError("io");
1822
+ }
1823
+ if (current.token !== owner.token) {
1824
+ return;
1825
+ }
1826
+ await unlink(lockPath).catch((error) => {
1827
+ if (errorCode(error) !== "ENOENT") {
1828
+ throw new LocalStateError("io");
1829
+ }
1830
+ });
1831
+ };
1832
+ } catch (error) {
1833
+ await handle?.close();
1834
+ if (errorCode(error) !== "EEXIST") {
1835
+ if (errorCode(error) === "ELOOP") {
1836
+ throw new LocalStateError("invalid");
1837
+ }
1838
+ throw error instanceof LocalStateError ? error : new LocalStateError("io");
1839
+ }
1840
+ try {
1841
+ const metadata = await lstat(lockPath);
1842
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
1843
+ throw new LocalStateError("invalid");
1844
+ }
1845
+ if (Date.now() - metadata.mtimeMs > LOCK_STALE_MILLISECONDS) {
1846
+ await hooks?.afterStaleMetadataRead?.(lockPath);
1847
+ const releaseGuard = await acquireReclaimGuard(lockPath, metadata);
1848
+ if (releaseGuard === void 0) {
1849
+ await hooks?.afterReclaimGuardDenied?.(lockPath);
1850
+ await delay(LOCK_RETRY_MILLISECONDS);
1851
+ continue;
1852
+ }
1853
+ try {
1854
+ const currentMetadata = await lstat(lockPath);
1855
+ if (currentMetadata.dev !== metadata.dev || currentMetadata.ino !== metadata.ino || Date.now() - currentMetadata.mtimeMs <= LOCK_STALE_MILLISECONDS) {
1856
+ continue;
1857
+ }
1858
+ let staleOwner;
1859
+ try {
1860
+ staleOwner = await readLockOwner(lockPath);
1861
+ } catch (ownerError) {
1862
+ if (!(ownerError instanceof LocalStateError && ownerError.failure === "invalid")) {
1863
+ throw ownerError;
1864
+ }
1865
+ }
1866
+ if (staleOwner !== void 0 && processIsAlive(staleOwner.pid)) {
1867
+ await delay(LOCK_RETRY_MILLISECONDS);
1868
+ continue;
1869
+ }
1870
+ const stalePath = `${lockPath}.stale-${randomUUID()}`;
1871
+ await rename(lockPath, stalePath);
1872
+ await hooks?.afterStaleRename?.(lockPath);
1873
+ const movedMetadata = await lstat(stalePath);
1874
+ if (movedMetadata.dev !== metadata.dev || movedMetadata.ino !== metadata.ino) {
1875
+ throw new LocalStateError("invalid");
1876
+ }
1877
+ await unlink(stalePath);
1878
+ } finally {
1879
+ await releaseGuard();
1880
+ }
1881
+ continue;
1882
+ }
1883
+ } catch (metadataError) {
1884
+ if (metadataError instanceof LocalStateError) {
1885
+ throw metadataError;
1886
+ }
1887
+ if (errorCode(metadataError) !== "ENOENT") {
1888
+ throw new LocalStateError("io");
1889
+ }
1890
+ }
1891
+ await delay(LOCK_RETRY_MILLISECONDS);
1892
+ }
1893
+ }
1894
+ throw new LocalStateError("busy");
1895
+ }
1896
+ async function withPrivateFileLocks(targets, action, hooks) {
1897
+ const releases = [];
1898
+ try {
1899
+ for (const target of [...new Set(targets)].sort()) {
1900
+ releases.push(await acquirePrivateFileLock(target, hooks));
1901
+ }
1902
+ return await action();
1903
+ } finally {
1904
+ for (const release of releases.reverse()) {
1905
+ await release();
1906
+ }
1907
+ }
1908
+ }
1909
+
1910
+ // apps/cli/src/user-path.ts
1911
+ import path2 from "node:path";
1912
+ function expandHome(input, homeDirectory, pathApi) {
1913
+ if (input === "~") {
1914
+ return homeDirectory;
1915
+ }
1916
+ if (input.startsWith("~/") || input.startsWith("~\\")) {
1917
+ return pathApi.join(homeDirectory, input.slice(2));
1918
+ }
1919
+ return input;
1920
+ }
1921
+ function windowsShellPath(input) {
1922
+ const msys = /^\/([a-z])(?:\/(.*))?$/iu.exec(input);
1923
+ if (msys !== null) {
1924
+ return `${msys[1]?.toUpperCase()}:\\${(msys[2] ?? "").replaceAll("/", "\\")}`;
1925
+ }
1926
+ const mounted = /^\/(?:cygdrive|mnt)\/([a-z])(?:\/(.*))?$/iu.exec(input);
1927
+ if (mounted !== null) {
1928
+ return `${mounted[1]?.toUpperCase()}:\\${(mounted[2] ?? "").replaceAll("/", "\\")}`;
1929
+ }
1930
+ return input;
1931
+ }
1932
+ function resolveUserPath(options) {
1933
+ const platform = options.platform ?? process.platform;
1934
+ const pathApi = platform === "win32" ? path2.win32 : path2.posix;
1935
+ const expanded = expandHome(options.input, options.homeDirectory, pathApi);
1936
+ if (platform === "win32") {
1937
+ return pathApi.resolve(options.currentDirectory, windowsShellPath(expanded));
1938
+ }
1939
+ return pathApi.resolve(options.currentDirectory, expanded);
1940
+ }
1941
+
1942
+ // apps/cli/src/project.ts
1943
+ import { randomUUID as randomUUID2 } from "node:crypto";
1944
+ import { lstat as lstat2, mkdir as mkdir2, unlink as unlink2 } from "node:fs/promises";
1945
+ import path3 from "node:path";
1946
+ var MANIFEST_NAME = "dxc.project.json";
1947
+ var MANIFEST_MAXIMUM_BYTES = 32 * 1024;
1948
+ var PROJECT_INDEX_MAXIMUM_BYTES = 512 * 1024;
1949
+ var PROJECT_INDEX_RELATIVE_PATH = ".dxc/content-projects.json";
1950
+ var DEFAULT_PROJECTS_RELATIVE_PATH = ".dxc/projects";
1951
+ var DEFAULT_ARTIFACT_PATHS = {
1952
+ article: "artifacts/04-article.md",
1953
+ brief: "artifacts/02-brief.md",
1954
+ delivery: "artifacts/08-delivery.md",
1955
+ outline: "artifacts/03-outline.md",
1956
+ "quality-review": "artifacts/07-quality-review.md",
1957
+ research: "artifacts/01-research.md",
1958
+ titles: "artifacts/05-titles.md",
1959
+ "visual-plan": "artifacts/06-visual-plan.md"
1960
+ };
1961
+ var ProjectCliError = class extends Error {
1962
+ constructor(code, message, fields = { recovery: "\u8BF7\u6309\u5F53\u524D\u9879\u76EE Skill \u7684\u6062\u590D\u52A8\u4F5C\u91CD\u8BD5\u3002" }) {
1963
+ super(message);
1964
+ this.code = code;
1965
+ this.fields = fields;
1966
+ this.name = "ProjectCliError";
1967
+ }
1968
+ code;
1969
+ fields;
1970
+ };
1971
+ function errorCode2(error) {
1972
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
1973
+ }
1974
+ function indexPath(homeDirectory) {
1975
+ return path3.join(homeDirectory, PROJECT_INDEX_RELATIVE_PATH);
1976
+ }
1977
+ async function readManifest(directory) {
1978
+ try {
1979
+ const source = await readPrivateFile(
1980
+ path3.join(directory, MANIFEST_NAME),
1981
+ MANIFEST_MAXIMUM_BYTES
1982
+ );
1983
+ const parsed = contentProjectManifestSchema.safeParse(JSON.parse(source));
1984
+ if (!parsed.success) {
1985
+ throw new ProjectCliError("DXC_PROJECT_INVALID", "\u9879\u76EE\u6587\u4EF6 dxc.project.json \u5DF2\u635F\u574F\u3002");
1986
+ }
1987
+ return parsed.data;
1988
+ } catch (error) {
1989
+ if (error instanceof ProjectCliError) {
1990
+ throw error;
1991
+ }
1992
+ if (error instanceof LocalStateError && error.failure === "missing") {
1993
+ throw new ProjectCliError("DXC_PROJECT_NOT_FOUND", "\u6CA1\u6709\u627E\u5230\u5185\u5BB9\u9879\u76EE\u3002");
1994
+ }
1995
+ throw new ProjectCliError("DXC_PROJECT_IO_FAILED", "\u65E0\u6CD5\u8BFB\u53D6\u5185\u5BB9\u9879\u76EE\u3002");
1996
+ }
1997
+ }
1998
+ async function readIndex(homeDirectory) {
1999
+ try {
2000
+ const source = await readPrivateFile(indexPath(homeDirectory), PROJECT_INDEX_MAXIMUM_BYTES);
2001
+ const parsed = contentProjectIndexSchema.safeParse(JSON.parse(source));
2002
+ if (!parsed.success) {
2003
+ throw new ProjectCliError("DXC_PROJECT_INVALID", "\u672C\u5730\u9879\u76EE\u5217\u8868\u5DF2\u635F\u574F\u3002");
2004
+ }
2005
+ return parsed.data;
2006
+ } catch (error) {
2007
+ if (error instanceof LocalStateError && error.failure === "missing") {
2008
+ return { projects: [], schemaVersion: "1" };
2009
+ }
2010
+ if (error instanceof ProjectCliError) {
2011
+ throw error;
2012
+ }
2013
+ throw new ProjectCliError("DXC_PROJECT_IO_FAILED", "\u65E0\u6CD5\u8BFB\u53D6\u672C\u5730\u9879\u76EE\u5217\u8868\u3002");
2014
+ }
2015
+ }
2016
+ var ProjectCli = class {
2017
+ #currentDirectory;
2018
+ #homeDirectory;
2019
+ #now;
2020
+ #randomUUID;
2021
+ constructor(dependencies) {
2022
+ this.#currentDirectory = dependencies.currentDirectory;
2023
+ this.#homeDirectory = dependencies.homeDirectory;
2024
+ this.#now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
2025
+ this.#randomUUID = dependencies.randomUUID ?? randomUUID2;
2026
+ }
2027
+ async #rememberLocked(directory, manifest) {
2028
+ const target = indexPath(this.#homeDirectory);
2029
+ const index = await readIndex(this.#homeDirectory);
2030
+ const entry = {
2031
+ directory,
2032
+ projectId: manifest.projectId,
2033
+ title: manifest.title,
2034
+ updatedAt: this.#now().toISOString()
2035
+ };
2036
+ const projects = [
2037
+ entry,
2038
+ ...index.projects.filter(
2039
+ (project) => project.projectId !== entry.projectId && project.directory !== entry.directory
2040
+ )
2041
+ ].slice(0, 1e3);
2042
+ await writePrivateJson(target, { projects, schemaVersion: "1" });
2043
+ }
2044
+ async initialize(directoryInput, title) {
2045
+ const projectId = this.#randomUUID();
2046
+ const directory = directoryInput === void 0 ? path3.join(this.#homeDirectory, DEFAULT_PROJECTS_RELATIVE_PATH, projectId) : resolveUserPath({
2047
+ currentDirectory: this.#currentDirectory,
2048
+ homeDirectory: this.#homeDirectory,
2049
+ input: directoryInput
2050
+ });
2051
+ const manifestTarget = path3.join(directory, MANIFEST_NAME);
2052
+ const parsed = contentProjectManifestSchema.safeParse({
2053
+ artifacts: DEFAULT_ARTIFACT_PATHS,
2054
+ assetsDirectory: "assets",
2055
+ createdAt: this.#now().toISOString(),
2056
+ projectId,
2057
+ schemaVersion: "1",
2058
+ title,
2059
+ workflowId: CONTENT_WORKFLOW_ID
2060
+ });
2061
+ if (!parsed.success) {
2062
+ throw new ProjectCliError("DXC_PROJECT_INVALID", "\u9879\u76EE\u6807\u9898\u6216\u76EE\u5F55\u4E0D\u5408\u6CD5\u3002");
2063
+ }
2064
+ const target = indexPath(this.#homeDirectory);
2065
+ await withPrivateFileLocks([target], async () => {
2066
+ try {
2067
+ await lstat2(manifestTarget);
2068
+ throw new ProjectCliError("DXC_PROJECT_EXISTS", "\u8BE5\u76EE\u5F55\u5DF2\u7ECF\u662F DxC \u5185\u5BB9\u9879\u76EE\u3002");
2069
+ } catch (error) {
2070
+ if (error instanceof ProjectCliError) {
2071
+ throw error;
2072
+ }
2073
+ if (errorCode2(error) !== "ENOENT") {
2074
+ throw new ProjectCliError("DXC_PROJECT_IO_FAILED", "\u65E0\u6CD5\u68C0\u67E5\u9879\u76EE\u76EE\u5F55\u3002");
2075
+ }
2076
+ }
2077
+ let manifestWritten = false;
2078
+ try {
2079
+ if (directoryInput === void 0) {
2080
+ await ensurePrivateDirectory(directory);
2081
+ await ensurePrivateDirectory(path3.join(directory, "artifacts"));
2082
+ await ensurePrivateDirectory(path3.join(directory, parsed.data.assetsDirectory));
2083
+ } else {
2084
+ await mkdir2(path3.join(directory, "artifacts"), { recursive: true });
2085
+ await mkdir2(path3.join(directory, parsed.data.assetsDirectory), { recursive: true });
2086
+ }
2087
+ await writePrivateJson(manifestTarget, parsed.data);
2088
+ manifestWritten = true;
2089
+ await this.#rememberLocked(directory, parsed.data);
2090
+ } catch (error) {
2091
+ if (manifestWritten) {
2092
+ await unlink2(manifestTarget).catch(() => void 0);
2093
+ }
2094
+ if (error instanceof ProjectCliError) {
2095
+ throw error;
2096
+ }
2097
+ throw new ProjectCliError("DXC_PROJECT_IO_FAILED", "\u65E0\u6CD5\u521B\u5EFA\u5185\u5BB9\u9879\u76EE\u3002", {
2098
+ recovery: "\u9879\u76EE\u6E05\u5355\u5DF2\u5B89\u5168\u56DE\u6EDA\uFF1B\u8BF7\u4FDD\u7559\u4E3B\u9898\u548C\u76EE\u5F55\u540E\u91CD\u8BD5\u540C\u4E00\u521B\u5EFA\u52A8\u4F5C\u3002",
2099
+ retryable: true
2100
+ });
2101
+ }
2102
+ }).catch((error) => {
2103
+ if (error instanceof LocalStateError && error.failure === "busy") {
2104
+ throw new ProjectCliError("DXC_PROJECT_BUSY", "\u672C\u5730\u9879\u76EE\u7D22\u5F15\u6B63\u5728\u66F4\u65B0\u3002", {
2105
+ recovery: "\u9879\u76EE\u5C1A\u672A\u521B\u5EFA\uFF1B\u8BF7\u7B49\u5F85\u5F53\u524D\u9879\u76EE\u52A8\u4F5C\u5B8C\u6210\u540E\u91CD\u8BD5\u540C\u4E00\u64CD\u4F5C\u3002",
2106
+ retryable: true
2107
+ });
2108
+ }
2109
+ throw error;
2110
+ });
2111
+ return { data: { directory, manifest: parsed.data } };
2112
+ }
2113
+ async locateByProjectId(projectIdInput) {
2114
+ const projectId = projectIdInput.trim().toLocaleLowerCase("en-US");
2115
+ const index = await readIndex(this.#homeDirectory);
2116
+ const entry = index.projects.find(
2117
+ (candidate) => candidate.projectId.toLocaleLowerCase("en-US") === projectId
2118
+ );
2119
+ if (entry === void 0) {
2120
+ throw new ProjectCliError("DXC_PROJECT_NOT_FOUND", "\u6CA1\u6709\u627E\u5230\u6307\u5B9A\u7684\u5185\u5BB9\u9879\u76EE\u3002");
2121
+ }
2122
+ const manifest = await readManifest(entry.directory);
2123
+ if (manifest.projectId !== entry.projectId) {
2124
+ throw new ProjectCliError("DXC_PROJECT_INVALID", "\u672C\u5730\u9879\u76EE\u767B\u8BB0\u4E0E\u9879\u76EE\u6587\u4EF6\u4E0D\u4E00\u81F4\u3002");
2125
+ }
2126
+ return { directory: entry.directory, manifest };
2127
+ }
2128
+ async locate(directoryInput) {
2129
+ if (directoryInput !== void 0) {
2130
+ const directory2 = resolveUserPath({
2131
+ currentDirectory: this.#currentDirectory,
2132
+ homeDirectory: this.#homeDirectory,
2133
+ input: directoryInput
2134
+ });
2135
+ return { directory: directory2, manifest: await readManifest(directory2) };
2136
+ }
2137
+ let directory = path3.resolve(this.#currentDirectory);
2138
+ while (true) {
2139
+ try {
2140
+ return { directory, manifest: await readManifest(directory) };
2141
+ } catch (error) {
2142
+ if (!(error instanceof ProjectCliError) || error.code !== "DXC_PROJECT_NOT_FOUND") {
2143
+ throw error;
2144
+ }
2145
+ }
2146
+ const parent = path3.dirname(directory);
2147
+ if (parent === directory) {
2148
+ throw new ProjectCliError("DXC_PROJECT_NOT_FOUND", "\u5F53\u524D\u76EE\u5F55\u4E2D\u6CA1\u6709 DxC \u5185\u5BB9\u9879\u76EE\u3002");
2149
+ }
2150
+ directory = parent;
2151
+ }
2152
+ }
2153
+ async relink(projectIdInput, directoryInput) {
2154
+ const projectId = projectIdInput.trim().toLocaleLowerCase("en-US");
2155
+ const directory = resolveUserPath({
2156
+ currentDirectory: this.#currentDirectory,
2157
+ homeDirectory: this.#homeDirectory,
2158
+ input: directoryInput
2159
+ });
2160
+ const manifest = await readManifest(directory);
2161
+ if (manifest.projectId.toLocaleLowerCase("en-US") !== projectId) {
2162
+ throw new ProjectCliError("DXC_PROJECT_INVALID", "\u6240\u9009\u4F4D\u7F6E\u4E0D\u5C5E\u4E8E\u8BE5\u9879\u76EE ID\u3002", {
2163
+ actual: manifest.projectId,
2164
+ expected: projectId,
2165
+ field: "project",
2166
+ recovery: "\u8BF7\u8BA9\u7528\u6237\u91CD\u65B0\u9009\u62E9\u4E0E\u8BE5\u9879\u76EE ID \u5BF9\u5E94\u7684\u9879\u76EE\u4F4D\u7F6E\u3002"
2167
+ });
2168
+ }
2169
+ const target = indexPath(this.#homeDirectory);
2170
+ return withPrivateFileLocks([target], async () => {
2171
+ const index = await readIndex(this.#homeDirectory);
2172
+ const existing = index.projects.find(
2173
+ (entry) => entry.projectId.toLocaleLowerCase("en-US") === projectId
2174
+ );
2175
+ if (existing === void 0) {
2176
+ throw new ProjectCliError("DXC_PROJECT_NOT_FOUND", "\u672C\u5730\u9879\u76EE\u5217\u8868\u4E2D\u6CA1\u6709\u8BE5\u9879\u76EE ID\u3002", {
2177
+ actual: projectId,
2178
+ field: "project",
2179
+ recovery: "\u8BF7\u91CD\u65B0\u5217\u51FA\u9879\u76EE\u5E76\u4F7F\u7528\u5F53\u524D\u8FD4\u56DE\u7684\u9879\u76EE ID\u3002"
2180
+ });
2181
+ }
2182
+ const updatedAt = this.#now().toISOString();
2183
+ await writePrivateJson(target, {
2184
+ projects: index.projects.map(
2185
+ (entry) => entry.projectId === existing.projectId ? { directory, projectId: manifest.projectId, title: manifest.title, updatedAt } : entry
2186
+ ),
2187
+ schemaVersion: "1"
2188
+ });
2189
+ return contentProjectRelinkResultSchema.parse({
2190
+ command: "project.relink",
2191
+ data: { projectId: manifest.projectId, title: manifest.title, updatedAt },
2192
+ ok: true
2193
+ });
2194
+ }).catch((error) => {
2195
+ if (error instanceof LocalStateError && error.failure === "busy") {
2196
+ throw new ProjectCliError("DXC_PROJECT_BUSY", "\u672C\u5730\u9879\u76EE\u7D22\u5F15\u6B63\u5728\u66F4\u65B0\u3002", {
2197
+ recovery: "\u8BF7\u7B49\u5F85\u5F53\u524D\u9879\u76EE\u52A8\u4F5C\u5B8C\u6210\u540E\u91CD\u8BD5\u540C\u4E00\u64CD\u4F5C\u3002",
2198
+ retryable: true
2199
+ });
2200
+ }
2201
+ throw error;
2202
+ });
2203
+ }
2204
+ async find(query, directoryInput) {
2205
+ if (directoryInput !== void 0) {
2206
+ return [await this.locate(directoryInput)];
2207
+ }
2208
+ if (query === void 0 || query.trim().length === 0) {
2209
+ try {
2210
+ return [await this.locate()];
2211
+ } catch (error) {
2212
+ if (!(error instanceof ProjectCliError) || error.code !== "DXC_PROJECT_NOT_FOUND") {
2213
+ throw error;
2214
+ }
2215
+ }
2216
+ }
2217
+ const normalized = query?.trim().toLocaleLowerCase("zh-CN");
2218
+ const index = await readIndex(this.#homeDirectory);
2219
+ const candidates = index.projects.filter(
2220
+ (project) => normalized === void 0 || project.projectId.toLocaleLowerCase("zh-CN").includes(normalized) || project.title.toLocaleLowerCase("zh-CN").includes(normalized)
2221
+ );
2222
+ const locations = [];
2223
+ for (const candidate of candidates) {
2224
+ try {
2225
+ const manifest = await readManifest(candidate.directory);
2226
+ if (manifest.projectId === candidate.projectId) {
2227
+ locations.push({ directory: candidate.directory, manifest });
2228
+ }
2229
+ } catch (error) {
2230
+ if (!(error instanceof ProjectCliError)) {
2231
+ throw error;
2232
+ }
2233
+ }
2234
+ }
2235
+ return locations;
2236
+ }
2237
+ async list() {
2238
+ const index = await readIndex(this.#homeDirectory);
2239
+ const projects = [];
2240
+ for (const entry of index.projects) {
2241
+ try {
2242
+ const manifest = await readManifest(entry.directory);
2243
+ projects.push({
2244
+ entry,
2245
+ ...manifest.projectId === entry.projectId ? { location: { directory: entry.directory, manifest } } : {}
2246
+ });
2247
+ } catch (error) {
2248
+ if (!(error instanceof ProjectCliError)) {
2249
+ throw error;
2250
+ }
2251
+ projects.push({
2252
+ entry,
2253
+ unavailableReason: error.code === "DXC_PROJECT_NOT_FOUND" ? "project-directory-missing" : error.code === "DXC_PROJECT_INVALID" ? "project-invalid" : "project-unreadable"
2254
+ });
2255
+ }
2256
+ }
2257
+ return projects;
2258
+ }
2259
+ };
2260
+
2261
+ export {
2262
+ __require,
2263
+ __esm,
2264
+ __commonJS,
2265
+ __export,
2266
+ __toESM,
2267
+ __toCommonJS,
2268
+ publishingUploadSessionSchema,
2269
+ publishingUploadReceiptSchema,
2270
+ publishingArticleSchema,
2271
+ publishingRenderSnapshotSchema,
2272
+ publishingPreviewLinkSchema,
2273
+ publishingPreviewSelectionStateSchema,
2274
+ createPublishingApprovalRequestSchema,
2275
+ publishingApprovalSchema,
2276
+ publishingDraftIntentResponseSchema,
2277
+ publishingDraftAttentionDiagnosticsSchema,
2278
+ CONTENT_ARTIFACT_KINDS,
2279
+ CONTENT_STAGE_DEFINITIONS,
2280
+ contentWorkflowAdoptedKnowledgeSchema,
2281
+ contentWorkflowContextSchema,
2282
+ portableRelativePathSchema,
2283
+ contentProfileInputSchema,
2284
+ contentProfileSchema,
2285
+ contentProfileViewSchema,
2286
+ contentProfileStatusResultSchema,
2287
+ contentProfileFieldSchema,
2288
+ contentProfileSessionResultSchema,
2289
+ contentProfileErrorResultSchema,
2290
+ CONTENT_MEMORY_KINDS,
2291
+ contentMemoryInputSchema,
2292
+ contentMemoryStoreSchema,
2293
+ contentMemoryViewSchema,
2294
+ contentMemoryAddResultSchema,
2295
+ contentMemoryArchiveResultSchema,
2296
+ contentMemoryCorrectResultSchema,
2297
+ contentMemoryListResultSchema,
2298
+ contentMemoryErrorResultSchema,
2299
+ contentProjectListResultSchema,
2300
+ contentProjectErrorResultSchema,
2301
+ contentWorkflowErrorResultSchema,
2302
+ CONTENT_KNOWLEDGE_SCHEMA_VERSION,
2303
+ CONTENT_KNOWLEDGE_EMBEDDING_MODEL,
2304
+ CONTENT_KNOWLEDGE_EMBEDDING_REVISION,
2305
+ CONTENT_KNOWLEDGE_EMBEDDING_DIMENSIONS,
2306
+ CONTENT_KNOWLEDGE_EMBEDDING_QUANTIZATION,
2307
+ CONTENT_KNOWLEDGE_CHUNKER_VERSION,
2308
+ contentKnowledgeSearchModeSchema,
2309
+ contentKnowledgeSourceFilterSchema,
2310
+ contentKnowledgeRefSchema,
2311
+ contentKnowledgeModelSchema,
2312
+ contentKnowledgeImportResultSchema,
2313
+ contentKnowledgeQuoteListResultSchema,
2314
+ contentKnowledgeQuoteMutationResultSchema,
2315
+ contentKnowledgeQuoteStatusResultSchema,
2316
+ contentKnowledgeSearchResultSchema,
2317
+ contentKnowledgeStatusResultSchema,
2318
+ contentKnowledgeRemoveResultSchema,
2319
+ contentKnowledgeAdoptResultSchema,
2320
+ contentKnowledgeErrorResultSchema,
2321
+ doctorResultSchema,
2322
+ articleBundleSchema,
2323
+ preflightResultSchema,
2324
+ wechatRenderResultSchema,
2325
+ createDeviceBindingSessionResponseSchema,
2326
+ proveDeviceBindingSessionResponseSchema,
2327
+ deviceSessionStatusResponseSchema,
2328
+ createWechatLoginSessionResponseSchema,
2329
+ wechatLoginSessionResponseSchema,
2330
+ createWechatAuthorizationSessionResponseSchema,
2331
+ wechatAuthorizationSessionResponseSchema,
2332
+ wechatAccountsResponseSchema,
2333
+ apiErrorResponseSchema,
2334
+ LocalStateError,
2335
+ ensurePrivateDirectory,
2336
+ ensurePrivateRegularFile,
2337
+ readPrivateFile,
2338
+ readPrivateBuffer,
2339
+ writePrivateJson,
2340
+ writePrivateBuffer,
2341
+ withPrivateFileLocks,
2342
+ resolveUserPath,
2343
+ ProjectCliError,
2344
+ ProjectCli
2345
+ };