@everfir/az8-cli 0.3.0-preview.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -2387,7 +2387,7 @@ var require_websocket = __commonJS({
2387
2387
  var http = __require("http");
2388
2388
  var net2 = __require("net");
2389
2389
  var tls = __require("tls");
2390
- var { randomBytes, createHash: createHash4 } = __require("crypto");
2390
+ var { randomBytes, createHash: createHash5 } = __require("crypto");
2391
2391
  var { Duplex, Readable } = __require("stream");
2392
2392
  var { URL: URL2 } = __require("url");
2393
2393
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -3047,7 +3047,7 @@ var require_websocket = __commonJS({
3047
3047
  abortHandshake(websocket, socket, "Invalid Upgrade header");
3048
3048
  return;
3049
3049
  }
3050
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
3050
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
3051
3051
  if (res.headers["sec-websocket-accept"] !== digest) {
3052
3052
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3053
3053
  return;
@@ -3414,7 +3414,7 @@ var require_websocket_server = __commonJS({
3414
3414
  var EventEmitter3 = __require("events");
3415
3415
  var http = __require("http");
3416
3416
  var { Duplex } = __require("stream");
3417
- var { createHash: createHash4 } = __require("crypto");
3417
+ var { createHash: createHash5 } = __require("crypto");
3418
3418
  var extension2 = require_extension();
3419
3419
  var PerMessageDeflate2 = require_permessage_deflate();
3420
3420
  var subprotocol2 = require_subprotocol();
@@ -3715,7 +3715,7 @@ var require_websocket_server = __commonJS({
3715
3715
  );
3716
3716
  }
3717
3717
  if (this._state > RUNNING) return abortHandshake(socket, 503);
3718
- const digest = createHash4("sha1").update(key + GUID).digest("base64");
3718
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
3719
3719
  const headers = [
3720
3720
  "HTTP/1.1 101 Switching Protocols",
3721
3721
  "Upgrade: websocket",
@@ -4822,6 +4822,58 @@ function normalize(value) {
4822
4822
  return (value ?? "").trim().toLowerCase().replaceAll(/[\s_]+/g, "-");
4823
4823
  }
4824
4824
 
4825
+ // ../../packages/project-canvas-runtime/dist/generation/workflow-access.js
4826
+ function resolveWorkflowDefinitionAccess(definition, accessTier) {
4827
+ if (accessTier === "paid") {
4828
+ return { accessReason: "paid-account", availableForAccount: true };
4829
+ }
4830
+ if (normalize2(getInternalTag(definition, "available")) === "free") {
4831
+ return { accessReason: "free-tier-eligible", availableForAccount: true };
4832
+ }
4833
+ return { accessReason: "requires-paid-account", availableForAccount: false };
4834
+ }
4835
+ function isWorkflowDefinitionAvailable(definition, accessTier) {
4836
+ return resolveWorkflowDefinitionAccess(definition, accessTier).availableForAccount;
4837
+ }
4838
+ function normalize2(value) {
4839
+ return (value ?? "").trim().toLowerCase().replaceAll(/[\s_]+/g, "-");
4840
+ }
4841
+
4842
+ // ../../packages/project-canvas-runtime/dist/generation/workflow-default.js
4843
+ function selectDefaultWorkflowDefinition(input) {
4844
+ const compatible = input.definitions.filter((definition) => isDefaultCompatible(definition, input.contentType));
4845
+ const preferred = input.preference && compatible.find((definition) => definition.id === input.preference?.definitionId);
4846
+ if (preferred) {
4847
+ return { definition: preferred, preference: input.preference, source: "preference" };
4848
+ }
4849
+ const fallback = compatible[0] ?? null;
4850
+ return {
4851
+ definition: fallback,
4852
+ preference: null,
4853
+ source: fallback ? "fallback" : "none"
4854
+ };
4855
+ }
4856
+ function isDefaultCompatible(definition, contentType) {
4857
+ const metadata = resolveWorkflowDefinitionMetadata(definition);
4858
+ if (metadata.target !== contentType)
4859
+ return false;
4860
+ if (!definition.outputSchema.some((output) => output.dataType === contentType))
4861
+ return false;
4862
+ if (getInternalTag(definition, "function") && !getInternalTag(definition, "capability")) {
4863
+ return false;
4864
+ }
4865
+ return definition.inputSchema.some((slot) => !isConfigSlot(slot));
4866
+ }
4867
+
4868
+ // ../../packages/project-canvas-runtime/dist/generation/workflow-target.js
4869
+ function resolveWorkflowTargetFromSnapshot(snapshot, workflowRunId) {
4870
+ const targetIds = new Set(snapshot.viewNodes.flatMap((viewNode) => readGenerationHistory(viewNode.history).some((entry) => entry.runtime.instanceIds.includes(workflowRunId)) ? [viewNode.id] : []));
4871
+ if (targetIds.size === 1) {
4872
+ return { status: "resolved", viewNodeId: [...targetIds][0] };
4873
+ }
4874
+ return { status: targetIds.size > 1 ? "ambiguous" : "unresolved" };
4875
+ }
4876
+
4825
4877
  // ../../node_modules/.pnpm/lib0@0.2.117/node_modules/lib0/math.js
4826
4878
  var floor = Math.floor;
4827
4879
  var abs = Math.abs;
@@ -8238,10 +8290,10 @@ var YEvent = class {
8238
8290
  }
8239
8291
  };
8240
8292
  var getPathTo = (parent, child) => {
8241
- const path9 = [];
8293
+ const path10 = [];
8242
8294
  while (child._item !== null && child !== parent) {
8243
8295
  if (child._item.parentSub !== null) {
8244
- path9.unshift(child._item.parentSub);
8296
+ path10.unshift(child._item.parentSub);
8245
8297
  } else {
8246
8298
  let i = 0;
8247
8299
  let c = (
@@ -8254,12 +8306,12 @@ var getPathTo = (parent, child) => {
8254
8306
  }
8255
8307
  c = c.right;
8256
8308
  }
8257
- path9.unshift(i);
8309
+ path10.unshift(i);
8258
8310
  }
8259
8311
  child = /** @type {AbstractType<any>} */
8260
8312
  child._item.parent;
8261
8313
  }
8262
- return path9;
8314
+ return path10;
8263
8315
  };
8264
8316
  var warnPrematureAccess = () => {
8265
8317
  warn("Invalid access: Add Yjs type to a document before reading data.");
@@ -14095,7 +14147,7 @@ var CANVAS_OPERATION_REGISTRY = [
14095
14147
  },
14096
14148
  required: ["contentType"]
14097
14149
  }),
14098
- write2("createGenerationTarget", "Create a blank audio, image, text, or video target", "undoable", {
14150
+ write2("createGenerationTarget", "Create an audio, image, text, or video target with an eligible default Draft when available", "undoable", {
14099
14151
  properties: {
14100
14152
  contentType: { enum: ["audio", "image", "text", "video"], type: "string" },
14101
14153
  name: stringSchema(),
@@ -14159,7 +14211,7 @@ var CANVAS_OPERATION_REGISTRY = [
14159
14211
  },
14160
14212
  required: ["idempotencyKey", "source"]
14161
14213
  }),
14162
- write2("editGenerationDraft", "Edit semantic prompt, config, or Workflow Definition", "silent", {
14214
+ write2("editGenerationDraft", "Edit prompt, config, or Workflow Definition, resolving an eligible default for a null Draft", "silent", {
14163
14215
  properties: {
14164
14216
  config: { additionalProperties: { type: ["boolean", "number", "string"] }, type: "object" },
14165
14217
  definitionId: stringSchema(),
@@ -15018,7 +15070,156 @@ function isConfigValueValid(value, property, normalizedEnum = normalizeConfigEnu
15018
15070
  return true;
15019
15071
  }
15020
15072
 
15073
+ // ../../packages/project-canvas-runtime/dist/generation/planning-contract.js
15074
+ function generationPlanningIssue(code, message, slotName, field) {
15075
+ return {
15076
+ code,
15077
+ message,
15078
+ severity: "error",
15079
+ ...slotName ? { slotName } : {},
15080
+ ...field ? { field } : {}
15081
+ };
15082
+ }
15083
+
15084
+ // ../../packages/project-canvas-runtime/dist/generation/planning-config.js
15085
+ function createGenerationConfigDefaults(definition, preferred) {
15086
+ const slots = generationConfigSlots(definition);
15087
+ if (slots.length === 0)
15088
+ return null;
15089
+ if (slots.length !== 1)
15090
+ return null;
15091
+ const slot = slots[0];
15092
+ const properties = slot.jsonSchema?.properties ?? {};
15093
+ const slotDefaults = readConfigDefaults(slot.defaultValue);
15094
+ return Object.fromEntries(Object.entries(properties).map(([name, property]) => {
15095
+ const preferredValue = preferred?.[name];
15096
+ if (preferredValue !== void 0 && isConfigValueValid(preferredValue, property)) {
15097
+ return [name, preferredValue];
15098
+ }
15099
+ const slotDefault = normalizeSchemaConfigValue(slotDefaults[name], property.type);
15100
+ return [
15101
+ name,
15102
+ slotDefault !== void 0 && isConfigValueValid(slotDefault, property) ? slotDefault : configFallback(property, normalizeConfigEnum(property))
15103
+ ];
15104
+ }));
15105
+ }
15106
+ async function createGenerationConfigPlan(definition, requested, runtime) {
15107
+ const slots = generationConfigSlots(definition);
15108
+ if (slots.length === 0) {
15109
+ return {
15110
+ fields: [],
15111
+ issues: requested ? [generationPlanningIssue("config-not-supported", "This Workflow Definition does not accept configuration.")] : [],
15112
+ values: null
15113
+ };
15114
+ }
15115
+ if (slots.length !== 1) {
15116
+ return {
15117
+ fields: [],
15118
+ issues: [
15119
+ generationPlanningIssue("multiple-config-slots-unsupported", "Generation Planning currently requires exactly one configuration slot.")
15120
+ ],
15121
+ values: null
15122
+ };
15123
+ }
15124
+ const slot = slots[0];
15125
+ const properties = slot.jsonSchema?.properties ?? {};
15126
+ const slotDefaults = readConfigDefaults(slot.defaultValue);
15127
+ const values = {};
15128
+ const issues = [];
15129
+ for (const name of Object.keys(requested ?? {})) {
15130
+ if (!properties[name]) {
15131
+ issues.push(generationPlanningIssue("config-field-unknown", `Unknown configuration field: ${name}.`, slot.name, name));
15132
+ }
15133
+ }
15134
+ const fields = await Promise.all(Object.entries(properties).map(async ([name, property]) => {
15135
+ const normalizedEnum = normalizeConfigEnum(property);
15136
+ if (normalizedEnum?.invalidValues.length) {
15137
+ issues.push(generationPlanningIssue("config-enum-invalid", `Configuration ${name} contains enum values that do not match ${property.type}.`, slot.name, name));
15138
+ }
15139
+ const requestedValue = Object.hasOwn(requested ?? {}, name) ? requested?.[name] : normalizeSchemaConfigValue(slotDefaults[name], property.type);
15140
+ const fallback = configFallback(property, normalizedEnum);
15141
+ if (requestedValue !== void 0 && !isConfigValueValid(requestedValue, property)) {
15142
+ issues.push(generationPlanningIssue("config-value-invalid", `Configuration ${name} is outside its allowed values.`, slot.name, name));
15143
+ }
15144
+ const value = requestedValue !== void 0 && isConfigValueValid(requestedValue, property) ? requestedValue : fallback;
15145
+ values[name] = value;
15146
+ const dynamicOptions = await readDynamicOptions(runtime, name, property, value, issues, slot.name);
15147
+ return {
15148
+ description: property.description ?? "",
15149
+ name,
15150
+ required: slot.jsonSchema?.required?.includes(name) ?? false,
15151
+ type: property.type,
15152
+ value,
15153
+ ...property.maximum === void 0 ? {} : { maximum: property.maximum },
15154
+ ...property.minimum === void 0 ? {} : { minimum: property.minimum },
15155
+ ...dynamicOptions ?? normalizedEnum?.options ? { options: dynamicOptions ?? normalizedEnum?.options } : {}
15156
+ };
15157
+ }));
15158
+ for (const name of slot.jsonSchema?.required ?? []) {
15159
+ if (values[name] === "") {
15160
+ issues.push(generationPlanningIssue("config-field-required", `Configuration ${name} requires a value.`, slot.name, name));
15161
+ }
15162
+ }
15163
+ return { fields, issues, values };
15164
+ }
15165
+ function readConfigDefaults(value) {
15166
+ if (!value || typeof value !== "object" || Array.isArray(value))
15167
+ return {};
15168
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "boolean" || typeof entry[1] === "string" || typeof entry[1] === "number" && Number.isFinite(entry[1])));
15169
+ }
15170
+ async function readDynamicOptions(runtime, name, property, current, issues, slotName) {
15171
+ const source = property.dynamicEnum;
15172
+ if (property.type !== "string" || !source?.modelKey || !runtime.getDynamicEnumValues)
15173
+ return null;
15174
+ try {
15175
+ const remote = await runtime.getDynamicEnumValues({
15176
+ modelKey: source.modelKey,
15177
+ paramName: name,
15178
+ provider: source.provider
15179
+ });
15180
+ const values = typeof current === "string" && current.trim() ? [current] : [];
15181
+ for (const item of remote)
15182
+ if (!values.includes(item))
15183
+ values.push(item);
15184
+ return values;
15185
+ } catch {
15186
+ issues.push({
15187
+ code: "dynamic-options-unavailable",
15188
+ field: name,
15189
+ message: `Dynamic options for configuration ${name} are temporarily unavailable.`,
15190
+ severity: "warning",
15191
+ slotName
15192
+ });
15193
+ return null;
15194
+ }
15195
+ }
15196
+ function configFallback(property, normalizedEnum) {
15197
+ const normalizedDefault = normalizeSchemaConfigValue(property.default, property.type);
15198
+ if (normalizedDefault !== void 0 && isConfigValueValid(normalizedDefault, property)) {
15199
+ return normalizedDefault;
15200
+ }
15201
+ const first = normalizedEnum?.options[0];
15202
+ if (first !== void 0)
15203
+ return first;
15204
+ if (property.type === "boolean")
15205
+ return false;
15206
+ if (property.type === "number") {
15207
+ return property.minimum ?? (property.maximum && property.maximum < 0 ? property.maximum : 0);
15208
+ }
15209
+ return "";
15210
+ }
15211
+ function generationConfigSlots(definition) {
15212
+ return definition.inputSchema.filter((slot) => slot.dataType === "json" && (slot.required || isConfigSlot(slot)));
15213
+ }
15214
+
15021
15215
  // ../../packages/project-canvas-runtime/dist/generation/draft-edit.js
15216
+ function createInitialGenerationDraft(definition, preferredConfig, now) {
15217
+ const config2 = createGenerationConfigDefaults(definition, preferredConfig);
15218
+ return editGenerationDraft(null, definition, {
15219
+ definitionId: definition.id,
15220
+ ...config2 ? { config: config2 } : {}
15221
+ }, now);
15222
+ }
15022
15223
  function editGenerationDraft(current, definition, input, now) {
15023
15224
  const changedDefinition = current?.definitionId !== definition.id;
15024
15225
  const draft = !current || changedDefinition ? {
@@ -15202,7 +15403,20 @@ function removeReferenceTokenFromContent(content, referenceId) {
15202
15403
  return next;
15203
15404
  }
15204
15405
  function createDefaultSlots(definition) {
15406
+ const promptSlot = findPromptSlot(definition);
15407
+ const config2 = createGenerationConfigDefaults(definition);
15408
+ const configSlots = definition.inputSchema.filter((slot) => slot.dataType === "json");
15409
+ const configSlot = configSlots.length === 1 ? configSlots[0] : void 0;
15205
15410
  return Object.fromEntries(definition.inputSchema.map((slot) => {
15411
+ if (slot === promptSlot) {
15412
+ return [slot.name, [literal({ id: definition.id }, slot.name, "text", "")]];
15413
+ }
15414
+ if (slot === configSlot && config2) {
15415
+ return [
15416
+ slot.name,
15417
+ [literal({ id: definition.id }, slot.name, "json", JSON.stringify(config2))]
15418
+ ];
15419
+ }
15206
15420
  if (slot.defaultValue === void 0)
15207
15421
  return [slot.name, []];
15208
15422
  const content = slot.dataType === "json" ? JSON.stringify(slot.defaultValue) : String(slot.defaultValue);
@@ -15229,11 +15443,14 @@ function requireSingleSlot(definition, dataType, purpose) {
15229
15443
  return slots[0];
15230
15444
  }
15231
15445
  function requirePromptSlot(definition) {
15232
- const slot = definition.inputSchema.find((candidate) => candidate.name === "prompt" && candidate.dataType === "text") ?? definition.inputSchema.find((candidate) => candidate.required && candidate.dataType === "text") ?? definition.inputSchema.find((candidate) => candidate.dataType === "text");
15446
+ const slot = findPromptSlot(definition);
15233
15447
  if (!slot)
15234
15448
  throw new Error("Workflow Definition must expose a prompt slot.");
15235
15449
  return slot;
15236
15450
  }
15451
+ function findPromptSlot(definition) {
15452
+ return definition.inputSchema.find((candidate) => candidate.name === "prompt" && candidate.dataType === "text") ?? definition.inputSchema.find((candidate) => candidate.required && candidate.dataType === "text") ?? definition.inputSchema.find((candidate) => candidate.dataType === "text");
15453
+ }
15237
15454
  function validateConfig(slot, config2) {
15238
15455
  const schema = slot.jsonSchema;
15239
15456
  if (!schema)
@@ -15305,124 +15522,6 @@ function requirePrimaryOutput(definition, contentType) {
15305
15522
  return output;
15306
15523
  }
15307
15524
 
15308
- // ../../packages/project-canvas-runtime/dist/generation/planning-contract.js
15309
- function generationPlanningIssue(code, message, slotName, field) {
15310
- return {
15311
- code,
15312
- message,
15313
- severity: "error",
15314
- ...slotName ? { slotName } : {},
15315
- ...field ? { field } : {}
15316
- };
15317
- }
15318
-
15319
- // ../../packages/project-canvas-runtime/dist/generation/planning-config.js
15320
- async function createGenerationConfigPlan(definition, requested, runtime) {
15321
- const slots = definition.inputSchema.filter((slot2) => slot2.dataType === "json" && (slot2.required || isConfigSlot(slot2)));
15322
- if (slots.length === 0) {
15323
- return {
15324
- fields: [],
15325
- issues: requested ? [generationPlanningIssue("config-not-supported", "This Workflow Definition does not accept configuration.")] : [],
15326
- values: null
15327
- };
15328
- }
15329
- if (slots.length !== 1) {
15330
- return {
15331
- fields: [],
15332
- issues: [
15333
- generationPlanningIssue("multiple-config-slots-unsupported", "Generation Planning currently requires exactly one configuration slot.")
15334
- ],
15335
- values: null
15336
- };
15337
- }
15338
- const slot = slots[0];
15339
- const properties = slot.jsonSchema?.properties ?? {};
15340
- const slotDefaults = readConfigDefaults(slot.defaultValue);
15341
- const values = {};
15342
- const issues = [];
15343
- for (const name of Object.keys(requested ?? {})) {
15344
- if (!properties[name]) {
15345
- issues.push(generationPlanningIssue("config-field-unknown", `Unknown configuration field: ${name}.`, slot.name, name));
15346
- }
15347
- }
15348
- const fields = await Promise.all(Object.entries(properties).map(async ([name, property]) => {
15349
- const normalizedEnum = normalizeConfigEnum(property);
15350
- if (normalizedEnum?.invalidValues.length) {
15351
- issues.push(generationPlanningIssue("config-enum-invalid", `Configuration ${name} contains enum values that do not match ${property.type}.`, slot.name, name));
15352
- }
15353
- const requestedValue = Object.hasOwn(requested ?? {}, name) ? requested?.[name] : normalizeSchemaConfigValue(slotDefaults[name], property.type);
15354
- const fallback = configFallback(property, normalizedEnum);
15355
- if (requestedValue !== void 0 && !isConfigValueValid(requestedValue, property)) {
15356
- issues.push(generationPlanningIssue("config-value-invalid", `Configuration ${name} is outside its allowed values.`, slot.name, name));
15357
- }
15358
- const value = requestedValue !== void 0 && isConfigValueValid(requestedValue, property) ? requestedValue : fallback;
15359
- values[name] = value;
15360
- const dynamicOptions = await readDynamicOptions(runtime, name, property, value, issues, slot.name);
15361
- return {
15362
- description: property.description ?? "",
15363
- name,
15364
- required: slot.jsonSchema?.required?.includes(name) ?? false,
15365
- type: property.type,
15366
- value,
15367
- ...property.maximum === void 0 ? {} : { maximum: property.maximum },
15368
- ...property.minimum === void 0 ? {} : { minimum: property.minimum },
15369
- ...dynamicOptions ?? normalizedEnum?.options ? { options: dynamicOptions ?? normalizedEnum?.options } : {}
15370
- };
15371
- }));
15372
- for (const name of slot.jsonSchema?.required ?? []) {
15373
- if (values[name] === "") {
15374
- issues.push(generationPlanningIssue("config-field-required", `Configuration ${name} requires a value.`, slot.name, name));
15375
- }
15376
- }
15377
- return { fields, issues, values };
15378
- }
15379
- function readConfigDefaults(value) {
15380
- if (!value || typeof value !== "object" || Array.isArray(value))
15381
- return {};
15382
- return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "boolean" || typeof entry[1] === "string" || typeof entry[1] === "number" && Number.isFinite(entry[1])));
15383
- }
15384
- async function readDynamicOptions(runtime, name, property, current, issues, slotName) {
15385
- const source = property.dynamicEnum;
15386
- if (property.type !== "string" || !source?.modelKey || !runtime.getDynamicEnumValues)
15387
- return null;
15388
- try {
15389
- const remote = await runtime.getDynamicEnumValues({
15390
- modelKey: source.modelKey,
15391
- paramName: name,
15392
- provider: source.provider
15393
- });
15394
- const values = typeof current === "string" && current.trim() ? [current] : [];
15395
- for (const item of remote)
15396
- if (!values.includes(item))
15397
- values.push(item);
15398
- return values;
15399
- } catch {
15400
- issues.push({
15401
- code: "dynamic-options-unavailable",
15402
- field: name,
15403
- message: `Dynamic options for configuration ${name} are temporarily unavailable.`,
15404
- severity: "warning",
15405
- slotName
15406
- });
15407
- return null;
15408
- }
15409
- }
15410
- function configFallback(property, normalizedEnum) {
15411
- const normalizedDefault = normalizeSchemaConfigValue(property.default, property.type);
15412
- if (normalizedDefault !== void 0 && isConfigValueValid(normalizedDefault, property)) {
15413
- return normalizedDefault;
15414
- }
15415
- const first = normalizedEnum?.options[0];
15416
- if (first !== void 0)
15417
- return first;
15418
- if (property.type === "boolean")
15419
- return false;
15420
- if (property.type === "number") {
15421
- return property.minimum ?? (property.maximum && property.maximum < 0 ? property.maximum : 0);
15422
- }
15423
- return "";
15424
- }
15425
-
15426
15525
  // ../../packages/project-canvas-runtime/dist/generation/planning-execution.js
15427
15526
  function createGenerationExecutionOperations(input) {
15428
15527
  const operations = [];
@@ -15431,10 +15530,10 @@ function createGenerationExecutionOperations(input) {
15431
15530
  definitionId: input.definition.id,
15432
15531
  viewNodeId: input.targetViewNodeId
15433
15532
  };
15434
- if (resolvePromptSlot(input.definition) && input.prompt !== readGenerationDraftPrompt(input.currentDraft)) {
15533
+ if (resolvePromptSlot(input.definition) && (definitionChanges || input.prompt !== readGenerationDraftPrompt(input.currentDraft))) {
15435
15534
  editInput.prompt = input.prompt;
15436
15535
  }
15437
- if (!sameConfig(input.config, readGenerationDraftConfig(input.currentDraft)) && input.config) {
15536
+ if (input.config && (definitionChanges || !sameConfig(input.config, readGenerationDraftConfig(input.currentDraft)))) {
15438
15537
  editInput.config = input.config;
15439
15538
  }
15440
15539
  if (definitionChanges || Object.keys(editInput).length > 2) {
@@ -16113,9 +16212,12 @@ var CoreNodeCreativeLoop = class {
16113
16212
  if (name === "createGenerationTarget")
16114
16213
  return this.createGenerationTarget(input, timeoutMs);
16115
16214
  if (name === "planGeneration") {
16215
+ if (input.definitionId !== void 0) {
16216
+ await this.requireSelectableDefinition(requireString3(input.definitionId, "definitionId"));
16217
+ }
16116
16218
  return {
16117
16219
  result: await planGeneration(input, {
16118
- definitions: [...this.definitions.values()],
16220
+ definitions: this.selectableDefinitions(),
16119
16221
  foundationData: this.systems.foundationData,
16120
16222
  getSnapshot: () => this.context.getSnapshot(),
16121
16223
  projectContentProjection: this.projection,
@@ -16143,15 +16245,23 @@ var CoreNodeCreativeLoop = class {
16143
16245
  throw new Error(`Operation ${name} is outside the Core Node creative loop.`);
16144
16246
  }
16145
16247
  getDefinitions(detail, definitionId) {
16146
- const definitions = [...this.definitions.values()].filter((definition) => !definitionId || definition.id === definitionId);
16248
+ const definitions = [...this.definitions.values()].filter((definition) => {
16249
+ if (definitionId)
16250
+ return definition.id === definitionId;
16251
+ return isWorkflowDefinitionAvailable(definition, this.systems.workflowAccessTier);
16252
+ });
16147
16253
  return {
16148
- definitions: definitions.map((definition) => detail ? structuredClone(definition) : {
16149
- description: definition.description,
16150
- id: definition.id,
16151
- name: definition.name,
16152
- outputs: definition.outputSchema.map((output) => output.dataType),
16153
- tags: definition.tags,
16154
- version: definition.version
16254
+ definitions: definitions.map((definition) => {
16255
+ const access = resolveWorkflowDefinitionAccess(definition, this.systems.workflowAccessTier);
16256
+ return detail ? { ...structuredClone(definition), ...access } : {
16257
+ ...access,
16258
+ description: definition.description,
16259
+ id: definition.id,
16260
+ name: definition.name,
16261
+ outputs: definition.outputSchema.map((output) => output.dataType),
16262
+ tags: definition.tags,
16263
+ version: definition.version
16264
+ };
16155
16265
  })
16156
16266
  };
16157
16267
  }
@@ -16272,10 +16382,14 @@ var CoreNodeCreativeLoop = class {
16272
16382
  assertOnlyKeys3(input, ["contentType", "name", "position"]);
16273
16383
  const contentType = requireString3(input.contentType, "contentType");
16274
16384
  requireSupportedContentType(contentType);
16385
+ const targetContentType = contentType;
16386
+ const selection = await this.resolveDefaultDefinition(targetContentType);
16387
+ const draft = selection.definition ? createInitialGenerationDraft(selection.definition, selection.preference?.config, this.context.now()) : null;
16275
16388
  const viewNode = this.createResourceViewNode(contentType, input.position, optionalString2(input.name), {
16276
16389
  creationIntent: "blank",
16277
16390
  ...contentType === "text" ? { mode: "content" } : {}
16278
16391
  }, "generated");
16392
+ viewNode.draft = draft ? toDocumentJson(draft) : null;
16279
16393
  await this.context.commit({
16280
16394
  after: [viewNode],
16281
16395
  before: [],
@@ -16283,24 +16397,39 @@ var CoreNodeCreativeLoop = class {
16283
16397
  label: "Create generation target",
16284
16398
  timeoutMs
16285
16399
  });
16286
- return attention(viewNode.id, { viewNodeId: viewNode.id });
16400
+ if (draft)
16401
+ await this.rememberWorkflowPreference(targetContentType, draft);
16402
+ return attention(viewNode.id, {
16403
+ ...draft ? { definitionId: draft.definitionId, draftId: draft.id } : {},
16404
+ draftInitialized: Boolean(draft),
16405
+ selectionSource: selection.source,
16406
+ viewNodeId: viewNode.id
16407
+ });
16287
16408
  }
16288
16409
  async editDraft(input, timeoutMs) {
16289
16410
  assertOnlyKeys3(input, ["config", "definitionId", "prompt", "viewNodeId"]);
16290
16411
  const current = this.requireTarget(requireString3(input.viewNodeId, "viewNodeId"));
16291
16412
  const existing = readGenerationDraft(current.draft);
16292
- const definitionId = optionalString2(input.definitionId) ?? existing?.definitionId;
16293
- if (!definitionId)
16294
- throw new Error("definitionId is required when creating a Draft.");
16295
- const definition = await this.requireDefinition(definitionId);
16413
+ const contentType = current.contentType;
16414
+ const explicitDefinitionId = optionalString2(input.definitionId);
16415
+ const resolved = existing ? {
16416
+ definition: await this.requireSelectableDefinition(explicitDefinitionId ?? existing.definitionId),
16417
+ preference: null,
16418
+ source: explicitDefinitionId ? "explicit" : "existing"
16419
+ } : explicitDefinitionId ? await this.resolveExplicitDefinition(contentType, explicitDefinitionId) : await this.resolveDefaultDefinition(contentType);
16420
+ const definition = resolved.definition;
16421
+ if (!definition) {
16422
+ throw Object.assign(new Error(`No compatible Workflow Definition is available for ${contentType}.`), { code: "no-compatible-workflow" });
16423
+ }
16296
16424
  requirePrimaryOutput(definition, current.contentType);
16297
16425
  if (input.prompt === void 0 && input.config === void 0 && input.definitionId === void 0) {
16298
16426
  throw new Error("Draft edit requires definitionId, prompt, or config.");
16299
16427
  }
16300
16428
  const config2 = input.config === void 0 ? void 0 : parseConfig2(input.config);
16301
- const nextDraft = editGenerationDraft(existing, definition, {
16429
+ const baseDraft = existing ?? createInitialGenerationDraft(definition, resolved.preference?.config, this.context.now());
16430
+ const nextDraft = editGenerationDraft(baseDraft, definition, {
16302
16431
  ...config2 ? { config: config2 } : {},
16303
- ...input.definitionId === void 0 ? {} : { definitionId },
16432
+ ...input.definitionId === void 0 ? {} : { definitionId: definition.id },
16304
16433
  ...input.prompt === void 0 ? {} : { prompt: requirePlainString2(input.prompt, "prompt") }
16305
16434
  }, this.context.now());
16306
16435
  const after = {
@@ -16315,13 +16444,19 @@ var CoreNodeCreativeLoop = class {
16315
16444
  label: "Edit generation Draft",
16316
16445
  timeoutMs
16317
16446
  });
16318
- return attention(current.id, { draftId: nextDraft.id, viewNodeId: current.id });
16447
+ await this.rememberWorkflowPreference(contentType, nextDraft);
16448
+ return attention(current.id, {
16449
+ definitionId: nextDraft.definitionId,
16450
+ draftId: nextDraft.id,
16451
+ selectionSource: resolved.source,
16452
+ viewNodeId: current.id
16453
+ });
16319
16454
  }
16320
16455
  async addVisualReference(input, timeoutMs) {
16321
16456
  assertOnlyKeys3(input, ["referenceViewNodeId", "viewNodeId"]);
16322
16457
  const target = this.requireTarget(requireString3(input.viewNodeId, "viewNodeId"));
16323
16458
  const draft = requireDraft(target);
16324
- const definition = await this.requireDefinition(draft.definitionId);
16459
+ const definition = await this.requireSelectableDefinition(draft.definitionId);
16325
16460
  const referenceViewNodeId = requireString3(input.referenceViewNodeId, "referenceViewNodeId");
16326
16461
  const sourceDataType = await this.resolveReferenceDataType(referenceViewNodeId);
16327
16462
  const referenceId = `input_ref_${crypto.randomUUID().replaceAll("-", "")}`;
@@ -16333,7 +16468,7 @@ var CoreNodeCreativeLoop = class {
16333
16468
  assertOnlyKeys3(input, ["placement", "referenceViewNodeId", "viewNodeId"]);
16334
16469
  const target = this.requireTarget(requireString3(input.viewNodeId, "viewNodeId"));
16335
16470
  const draft = requireDraft(target);
16336
- const definition = await this.requireDefinition(draft.definitionId);
16471
+ const definition = await this.requireSelectableDefinition(draft.definitionId);
16337
16472
  const referenceViewNodeId = requireString3(input.referenceViewNodeId, "referenceViewNodeId");
16338
16473
  const sourceDataType = await this.resolveReferenceDataType(referenceViewNodeId);
16339
16474
  const existing = Object.values(draft.inputs.slots).flat().find((reference) => reference.kind === "view-node" && reference.viewNodeId === referenceViewNodeId);
@@ -16359,7 +16494,7 @@ var CoreNodeCreativeLoop = class {
16359
16494
  assertOnlyKeys3(input, ["viewNodeId"]);
16360
16495
  const target = this.requireTarget(requireString3(input.viewNodeId, "viewNodeId"));
16361
16496
  const draft = requireDraft(target);
16362
- const definition = await this.requireDefinition(draft.definitionId);
16497
+ const definition = await this.requireSelectableDefinition(draft.definitionId);
16363
16498
  const output = requirePrimaryOutput(definition, target.contentType);
16364
16499
  const prepared = await prepareGenerationInput({
16365
16500
  definition,
@@ -16775,6 +16910,40 @@ var CoreNodeCreativeLoop = class {
16775
16910
  this.coreNodes.set(id2, node);
16776
16911
  return structuredClone(node);
16777
16912
  }
16913
+ async resolveDefaultDefinition(contentType) {
16914
+ const preference = await this.readWorkflowPreference(contentType);
16915
+ return selectDefaultWorkflowDefinition({
16916
+ contentType,
16917
+ definitions: this.selectableDefinitions(),
16918
+ preference
16919
+ });
16920
+ }
16921
+ async resolveExplicitDefinition(contentType, definitionId) {
16922
+ const definition = await this.requireSelectableDefinition(definitionId);
16923
+ requirePrimaryOutput(definition, contentType);
16924
+ const preference = await this.readWorkflowPreference(contentType);
16925
+ return {
16926
+ definition,
16927
+ preference: preference?.definitionId === definition.id ? preference : null,
16928
+ source: "explicit"
16929
+ };
16930
+ }
16931
+ async readWorkflowPreference(contentType) {
16932
+ try {
16933
+ return await this.systems.workflowPreferences?.read(contentType) ?? null;
16934
+ } catch {
16935
+ return null;
16936
+ }
16937
+ }
16938
+ async rememberWorkflowPreference(contentType, draft) {
16939
+ try {
16940
+ await this.systems.workflowPreferences?.write(contentType, {
16941
+ config: readGenerationDraftConfig(draft) ?? {},
16942
+ definitionId: draft.definitionId
16943
+ });
16944
+ } catch {
16945
+ }
16946
+ }
16778
16947
  async requireDefinition(id2) {
16779
16948
  const cached2 = this.definitions.get(id2);
16780
16949
  if (cached2)
@@ -16785,6 +16954,16 @@ var CoreNodeCreativeLoop = class {
16785
16954
  this.definitions.set(id2, definition);
16786
16955
  return definition;
16787
16956
  }
16957
+ async requireSelectableDefinition(id2) {
16958
+ const definition = await this.requireDefinition(id2);
16959
+ if (!isWorkflowDefinitionAvailable(definition, this.systems.workflowAccessTier)) {
16960
+ throw Object.assign(new Error(`Workflow Definition ${id2} is not available to the authenticated account.`), { code: "workflow-not-available-for-account" });
16961
+ }
16962
+ return definition;
16963
+ }
16964
+ selectableDefinitions() {
16965
+ return [...this.definitions.values()].filter((definition) => isWorkflowDefinitionAvailable(definition, this.systems.workflowAccessTier));
16966
+ }
16788
16967
  async resolveReferenceDataType(referenceViewNodeId) {
16789
16968
  const referenceViewNode = this.requireViewNode(referenceViewNodeId);
16790
16969
  if (referenceViewNode.type !== "resource") {
@@ -17377,8 +17556,8 @@ function parsePosition3(value) {
17377
17556
  return { x: position.x, y: position.y };
17378
17557
  }
17379
17558
  function deriveName(url2, contentType) {
17380
- const path9 = new URL(url2).pathname;
17381
- const filename = decodeURIComponent(path9.split("/").filter(Boolean).at(-1) ?? "");
17559
+ const path10 = new URL(url2).pathname;
17560
+ const filename = decodeURIComponent(path10.split("/").filter(Boolean).at(-1) ?? "");
17382
17561
  const withoutExtension = filename.replace(/\.[a-z0-9]+$/i, "").trim();
17383
17562
  return withoutExtension || `Imported ${contentType}`;
17384
17563
  }
@@ -18883,6 +19062,8 @@ function createCreativeLoop(options, projectContentProjection, context) {
18883
19062
  foundationData: options.foundationData,
18884
19063
  projectContent: options.projectContent,
18885
19064
  projectContentProjection,
19065
+ workflowAccessTier: options.workflowAccessTier ?? "paid",
19066
+ workflowPreferences: options.workflowPreferences,
18886
19067
  workflowRuntime: options.workflowRuntime
18887
19068
  };
18888
19069
  return new CoreNodeCreativeLoop(context, systems);
@@ -18962,6 +19143,114 @@ function normalizeCreationProvenanceSuffix(value) {
18962
19143
  return normalized;
18963
19144
  }
18964
19145
 
19146
+ // src/cli/workflow-preference-store.ts
19147
+ import { createHash, randomUUID } from "node:crypto";
19148
+ import { chmod, lstat, mkdir, readFile, rename, writeFile } from "node:fs/promises";
19149
+ import { homedir } from "node:os";
19150
+ import path from "node:path";
19151
+ var FORMAT = "az8.workflow-preference.v1";
19152
+ function createNodeWorkflowPreferenceStore(options) {
19153
+ const accountId = options.accountId.trim();
19154
+ if (!accountId) throw new Error("Workflow preference scope requires an account id.");
19155
+ const env = options.env ?? process.env;
19156
+ const stateRoot = path.resolve(
19157
+ options.stateRoot ?? env.AZ8_CLI_STATE_DIR ?? path.join(env.XDG_STATE_HOME ?? path.join(homedir(), ".local", "state"), "az8-cli")
19158
+ );
19159
+ const directory = path.join(stateRoot, "workflow-preferences");
19160
+ return {
19161
+ async read(contentType) {
19162
+ await ensurePrivateDirectory(directory);
19163
+ const filePath = preferencePath(directory, options.environment, accountId, contentType);
19164
+ try {
19165
+ await assertPrivateRegularFile(filePath);
19166
+ return parseStoredPreference(
19167
+ JSON.parse(await readFile(filePath, "utf8")),
19168
+ options.environment,
19169
+ accountId,
19170
+ contentType
19171
+ );
19172
+ } catch (error51) {
19173
+ if (error51.code === "ENOENT") return null;
19174
+ return null;
19175
+ }
19176
+ },
19177
+ async write(contentType, preference) {
19178
+ const normalized = normalizePreference(preference);
19179
+ await ensurePrivateDirectory(directory);
19180
+ const value = {
19181
+ accountId,
19182
+ contentType,
19183
+ environment: options.environment,
19184
+ format: FORMAT,
19185
+ preference: normalized
19186
+ };
19187
+ await writeJsonAtomic(
19188
+ preferencePath(directory, options.environment, accountId, contentType),
19189
+ value
19190
+ );
19191
+ }
19192
+ };
19193
+ }
19194
+ function parseStoredPreference(value, environment, accountId, contentType) {
19195
+ if (!isRecord2(value) || value.format !== FORMAT || value.environment !== environment || value.accountId !== accountId || value.contentType !== contentType) {
19196
+ return null;
19197
+ }
19198
+ try {
19199
+ return normalizePreference(value.preference);
19200
+ } catch {
19201
+ return null;
19202
+ }
19203
+ }
19204
+ function normalizePreference(value) {
19205
+ if (!isRecord2(value) || typeof value.definitionId !== "string" || !value.definitionId.trim()) {
19206
+ throw new Error("Workflow preference requires a Definition id.");
19207
+ }
19208
+ if (!isRecord2(value.config)) throw new Error("Workflow preference config must be an object.");
19209
+ const config2 = Object.fromEntries(
19210
+ Object.entries(value.config).filter(
19211
+ (entry) => typeof entry[1] === "boolean" || typeof entry[1] === "string" || typeof entry[1] === "number" && Number.isFinite(entry[1])
19212
+ )
19213
+ );
19214
+ return { config: config2, definitionId: value.definitionId.trim() };
19215
+ }
19216
+ function preferencePath(directory, environment, accountId, contentType) {
19217
+ const digest = createHash("sha256").update(`${environment}\0${accountId}\0${contentType}`).digest("hex");
19218
+ return path.join(directory, `${digest}.json`);
19219
+ }
19220
+ async function ensurePrivateDirectory(directory) {
19221
+ await mkdir(directory, { mode: 448, recursive: true });
19222
+ const metadata = await lstat(directory);
19223
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
19224
+ throw new Error("Workflow preference state path is not a private directory.");
19225
+ }
19226
+ if (typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
19227
+ throw new Error("Workflow preference state directory has a different owner.");
19228
+ }
19229
+ await chmod(directory, 448);
19230
+ }
19231
+ async function assertPrivateRegularFile(filePath) {
19232
+ const metadata = await lstat(filePath);
19233
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
19234
+ throw new Error("Workflow preference state is not a regular file.");
19235
+ }
19236
+ if (typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
19237
+ throw new Error("Workflow preference state has a different owner.");
19238
+ }
19239
+ if ((metadata.mode & 63) !== 0) {
19240
+ throw new Error("Workflow preference state is not owner-private.");
19241
+ }
19242
+ }
19243
+ async function writeJsonAtomic(filePath, value) {
19244
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
19245
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}
19246
+ `, { mode: 384 });
19247
+ await rename(temporary, filePath);
19248
+ await chmod(filePath, 384);
19249
+ }
19250
+ function isRecord2(value) {
19251
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19252
+ }
19253
+
18965
19254
  // src/integrations/backend.ts
18966
19255
  var BackendRequestError = class extends Error {
18967
19256
  code;
@@ -18990,7 +19279,7 @@ var Az8BackendClient = class {
18990
19279
  this.config = config2;
18991
19280
  }
18992
19281
  config;
18993
- async request(path9, options = {}) {
19282
+ async request(path10, options = {}) {
18994
19283
  const method = options.method ?? "GET";
18995
19284
  const token = await this.config.credentials.getToken();
18996
19285
  const attempts = options.write ? 1 : 2;
@@ -18998,7 +19287,7 @@ var Az8BackendClient = class {
18998
19287
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
18999
19288
  let response;
19000
19289
  try {
19001
- response = await this.fetchWithDeadline(path9, token, method, options);
19290
+ response = await this.fetchWithDeadline(path10, token, method, options);
19002
19291
  } catch (error51) {
19003
19292
  if (options.write) throw new IndeterminateBackendWriteError(error51);
19004
19293
  lastError = error51;
@@ -19010,11 +19299,11 @@ var Az8BackendClient = class {
19010
19299
  }
19011
19300
  throw lastError;
19012
19301
  }
19013
- async fetchWithDeadline(path9, token, method, options) {
19302
+ async fetchWithDeadline(path10, token, method, options) {
19014
19303
  const abortController2 = new AbortController();
19015
19304
  const timeout = setTimeout(() => abortController2.abort(), options.timeoutMs ?? 15e3);
19016
19305
  try {
19017
- return await this.config.fetch(`${this.config.backendUrl}/${path9.replace(/^\/+/, "")}`, {
19306
+ return await this.config.fetch(`${this.config.backendUrl}/${path10.replace(/^\/+/, "")}`, {
19018
19307
  method,
19019
19308
  headers: {
19020
19309
  Cookie: `token=${token}`,
@@ -19059,15 +19348,22 @@ function toAuthenticatedAccount(profile) {
19059
19348
  const accountId = profile.accountId.trim();
19060
19349
  if (!accountId)
19061
19350
  throw new Error("Authenticated account profile is missing account id.");
19351
+ const accessTier = isFreeAccount(profile) ? "free" : "paid";
19062
19352
  const nickname = profile.nickname?.trim();
19063
19353
  if (nickname)
19064
- return { accountId, displayName: nickname };
19354
+ return { accessTier, accountId, displayName: nickname };
19065
19355
  const emailName = profile.email.split("@")[0]?.trim();
19066
19356
  return {
19357
+ accessTier,
19067
19358
  accountId,
19068
19359
  displayName: emailName || `User ${accountId}`
19069
19360
  };
19070
19361
  }
19362
+ function isFreeAccount(profile) {
19363
+ if (profile.identities)
19364
+ return !profile.identities.includes("valid_user");
19365
+ return (profile.subscriptionType?.trim().toLowerCase() || "free") === "free";
19366
+ }
19071
19367
 
19072
19368
  // src/integrations/account-profile.ts
19073
19369
  function createAz8AccountProfileClient(config2) {
@@ -19102,7 +19398,13 @@ function createAz8AccountProfileRepository(config2) {
19102
19398
  return {
19103
19399
  accountId: String(payload.data.account_id),
19104
19400
  email: payload.data.email,
19105
- ...payload.data.nickname === void 0 ? {} : { nickname: payload.data.nickname }
19401
+ ...Array.isArray(payload.data.identities) ? {
19402
+ identities: payload.data.identities.filter(
19403
+ (value) => typeof value === "string"
19404
+ )
19405
+ } : {},
19406
+ ...payload.data.nickname === void 0 ? {} : { nickname: payload.data.nickname },
19407
+ ...payload.data.subscription_type === void 0 ? {} : { subscriptionType: payload.data.subscription_type }
19106
19408
  };
19107
19409
  }
19108
19410
  };
@@ -19752,10 +20054,10 @@ async function parseStatusEvent(event, onStatus) {
19752
20054
  }
19753
20055
 
19754
20056
  // src/media/upload.ts
19755
- import { createHash } from "node:crypto";
20057
+ import { createHash as createHash2 } from "node:crypto";
19756
20058
  import { constants } from "node:fs";
19757
- import { lstat, open } from "node:fs/promises";
19758
- import path from "node:path";
20059
+ import { lstat as lstat2, open } from "node:fs/promises";
20060
+ import path2 from "node:path";
19759
20061
  import { Transform } from "node:stream";
19760
20062
 
19761
20063
  // ../../node_modules/.pnpm/strtok3@10.3.5/node_modules/strtok3/lib/stream/Errors.js
@@ -23643,10 +23945,10 @@ function createNodeCanvasMediaUploadSystem(config2, cwd = process.cwd()) {
23643
23945
  }
23644
23946
  async function openUploadSource(sourceReference, cwd) {
23645
23947
  if (!sourceReference.trim()) throw new Error("Media upload source must not be blank.");
23646
- const absolutePath = path.resolve(cwd, sourceReference);
23948
+ const absolutePath = path2.resolve(cwd, sourceReference);
23647
23949
  let sourceStat;
23648
23950
  try {
23649
- sourceStat = await lstat(absolutePath);
23951
+ sourceStat = await lstat2(absolutePath);
23650
23952
  } catch {
23651
23953
  throw new Error("Media upload source does not exist or cannot be inspected.");
23652
23954
  }
@@ -23671,7 +23973,7 @@ async function inspectUploadSource(handle, absolutePath, report) {
23671
23973
  if (!Number.isSafeInteger(before.size) || before.size < 1) {
23672
23974
  throw new Error("Media upload source must contain at least one byte.");
23673
23975
  }
23674
- const hash2 = createHash("sha256");
23976
+ const hash2 = createHash2("sha256");
23675
23977
  const header = Buffer.allocUnsafe(Math.min(FILE_TYPE_HEADER_BYTES, before.size));
23676
23978
  const buffer = Buffer.allocUnsafe(Math.min(HASH_BUFFER_BYTES, before.size));
23677
23979
  let bytes = 0;
@@ -23699,7 +24001,7 @@ async function inspectUploadSource(handle, absolutePath, report) {
23699
24001
  return {
23700
24002
  bytes,
23701
24003
  extension: detected.ext,
23702
- fileName: path.basename(absolutePath),
24004
+ fileName: path2.basename(absolutePath),
23703
24005
  lastModified: Math.max(0, Math.round(after.mtimeMs)),
23704
24006
  mediaType,
23705
24007
  mimeType: detected.mime,
@@ -23766,7 +24068,7 @@ async function putPreparedFile(config2, handle, absolutePath, descriptor2, uploa
23766
24068
  () => controller.abort(new Error("Media upload timed out.")),
23767
24069
  timeoutMs ?? 3e5
23768
24070
  );
23769
- const hash2 = createHash("sha256");
24071
+ const hash2 = createHash2("sha256");
23770
24072
  let bytes = 0;
23771
24073
  await report(uploadProgress("uploading", 0, descriptor2.bytes));
23772
24074
  const meter = new Transform({
@@ -23995,7 +24297,7 @@ function matches(interest, fact) {
23995
24297
  return !filter.states || filter.states.includes(fact.state);
23996
24298
  }
23997
24299
  function patchFilter(current, patch) {
23998
- if (!isRecord2(patch)) {
24300
+ if (!isRecord3(patch)) {
23999
24301
  throw interestError("interest-filter-invalid", "Interest filter patch must be an object.");
24000
24302
  }
24001
24303
  const next = structuredClone(current);
@@ -24010,7 +24312,7 @@ function validateFilter(kind, filter) {
24010
24312
  validateFilterEntries(kind, Object.entries(filter));
24011
24313
  }
24012
24314
  function validateFilterPatch(kind, filter) {
24013
- if (!isRecord2(filter)) {
24315
+ if (!isRecord3(filter)) {
24014
24316
  throw interestError("interest-filter-invalid", "Interest filter patch must be an object.");
24015
24317
  }
24016
24318
  validateFilterEntries(kind, Object.entries(filter));
@@ -24104,7 +24406,7 @@ function assertAllowed(values, allowed, label) {
24104
24406
  function isInterestKind(value) {
24105
24407
  return value === "canvas" || value === "session" || value === "workflow";
24106
24408
  }
24107
- function isRecord2(value) {
24409
+ function isRecord3(value) {
24108
24410
  return typeof value === "object" && value !== null && !Array.isArray(value);
24109
24411
  }
24110
24412
  function interestError(code, message) {
@@ -24112,11 +24414,11 @@ function interestError(code, message) {
24112
24414
  }
24113
24415
 
24114
24416
  // src/canvas/watch/project-observation.ts
24115
- function projectCanvasObservation(observation, observedAt) {
24417
+ function projectCanvasObservation(observation, observedAt, workflowTarget) {
24116
24418
  const viewNodeFacts = (observation.viewNodeChanges ?? []).map(
24117
24419
  (change) => projectViewNodeChange(change, observation.kind, observedAt)
24118
24420
  );
24119
- return observation.workflowRun ? [...viewNodeFacts, projectWorkflowRun(observation.workflowRun, observedAt)] : viewNodeFacts;
24421
+ return observation.workflowRun ? [...viewNodeFacts, projectWorkflowRun(observation.workflowRun, observedAt, workflowTarget)] : viewNodeFacts;
24120
24422
  }
24121
24423
  function projectSessionState(input) {
24122
24424
  return {
@@ -24151,7 +24453,7 @@ function projectViewNodeChange(change, source, observedAt) {
24151
24453
  ...typeof viewNode.type === "string" ? { viewNodeType: viewNode.type } : {}
24152
24454
  };
24153
24455
  }
24154
- function projectWorkflowRun(run, observedAt) {
24456
+ function projectWorkflowRun(run, observedAt, target) {
24155
24457
  const terminal = isTerminalWorkflowRunStatus(run.status);
24156
24458
  return {
24157
24459
  changeKind: terminal ? `workflow.${run.status}` : "workflow.progress",
@@ -24170,6 +24472,7 @@ function projectWorkflowRun(run, observedAt) {
24170
24472
  }
24171
24473
  } : {},
24172
24474
  ...run.progress === void 0 ? {} : { progress: run.progress },
24475
+ ...target?.status === "resolved" ? { viewNodeId: target.viewNodeId } : terminal ? { targetResolution: target?.status ?? "unresolved" } : {},
24173
24476
  ...run.outputs.length > 0 ? {
24174
24477
  outputs: run.outputs.map((output) => ({
24175
24478
  coreNodeId: output.coreNodeId,
@@ -24186,7 +24489,7 @@ function projectWorkflowRun(run, observedAt) {
24186
24489
  function summarizeViewNode(change) {
24187
24490
  const viewNode = change.after ?? change.before;
24188
24491
  if (!viewNode) return {};
24189
- const data = isRecord3(viewNode.data) ? viewNode.data : {};
24492
+ const data = isRecord4(viewNode.data) ? viewNode.data : {};
24190
24493
  const summary = {
24191
24494
  ...typeof viewNode.contentType === "string" ? { contentType: viewNode.contentType } : {},
24192
24495
  ...typeof data.label === "string" ? { name: data.label } : {},
@@ -24197,10 +24500,10 @@ function summarizeViewNode(change) {
24197
24500
  if (typeof data.color === "string") summary.color = data.color;
24198
24501
  if (typeof data.creator_name === "string") summary.creatorName = data.creator_name;
24199
24502
  }
24200
- if (change.changedFields.includes("position") && isRecord3(viewNode.position)) {
24503
+ if (change.changedFields.includes("position") && isRecord4(viewNode.position)) {
24201
24504
  summary.position = structuredClone(viewNode.position);
24202
24505
  }
24203
- if (change.changedFields.includes("size") && isRecord3(viewNode.size)) {
24506
+ if (change.changedFields.includes("size") && isRecord4(viewNode.size)) {
24204
24507
  summary.size = structuredClone(viewNode.size);
24205
24508
  }
24206
24509
  if (change.changedFields.includes("parent")) summary.parentId = viewNode.parentId ?? null;
@@ -24218,7 +24521,7 @@ function fieldGroup(field) {
24218
24521
  if (field === "parent" || field === "stacking") return "hierarchy";
24219
24522
  return field;
24220
24523
  }
24221
- function isRecord3(value) {
24524
+ function isRecord4(value) {
24222
24525
  return typeof value === "object" && value !== null && !Array.isArray(value);
24223
24526
  }
24224
24527
  function safeWorkflowMessage(value) {
@@ -24493,6 +24796,7 @@ var CanvasSession = class {
24493
24796
  unsubscribeRuntime = null;
24494
24797
  observationListeners = /* @__PURE__ */ new Set();
24495
24798
  knownWorkflowRunIds = /* @__PURE__ */ new Set();
24799
+ knownWorkflowTargets = /* @__PURE__ */ new Map();
24496
24800
  projectionRevision = 0;
24497
24801
  actorId = null;
24498
24802
  collaborationContext = null;
@@ -24557,12 +24861,15 @@ var CanvasSession = class {
24557
24861
  projectContents: contentSync.contents,
24558
24862
  projectId: authenticated.id,
24559
24863
  role: authenticated.role,
24864
+ workflowAccessTier: actor.accessTier,
24560
24865
  workflowDefinitions,
24866
+ workflowPreferences: this.dependencies.workflowPreferences?.(actor),
24561
24867
  workflowRuntime
24562
24868
  });
24563
24869
  this.runtime = runtime;
24564
24870
  for (const workflowRunId of runtime.getSnapshot().pendingWorkflowInstanceIds) {
24565
24871
  this.knownWorkflowRunIds.add(workflowRunId);
24872
+ this.retainWorkflowTarget(workflowRunId);
24566
24873
  }
24567
24874
  this.projectionRevision = runtime.revision;
24568
24875
  this.unsubscribeRuntime = runtime.subscribe((observation) => {
@@ -24570,7 +24877,13 @@ var CanvasSession = class {
24570
24877
  if (observation.workflowRun) {
24571
24878
  this.knownWorkflowRunIds.add(observation.workflowRun.id);
24572
24879
  }
24573
- this.watch.recordMany(projectCanvasObservation(observation, Date.now()));
24880
+ this.watch.recordMany(
24881
+ projectCanvasObservation(
24882
+ observation,
24883
+ Date.now(),
24884
+ observation.workflowRun ? this.resolveWorkflowTarget(observation.workflowRun.id) : void 0
24885
+ )
24886
+ );
24574
24887
  const legacyObservation = {
24575
24888
  ...observation.changedViewNodeIds ? { changedViewNodeIds: observation.changedViewNodeIds } : {},
24576
24889
  kind: observation.kind,
@@ -24593,9 +24906,24 @@ var CanvasSession = class {
24593
24906
  if (typeof input.workflowRunId === "string" && input.workflowRunId) {
24594
24907
  this.knownWorkflowRunIds.add(input.workflowRunId);
24595
24908
  }
24596
- const result3 = await runtime.execute(name, input, timeoutMs, options);
24909
+ let result3;
24910
+ try {
24911
+ result3 = await runtime.execute(name, input, timeoutMs, options);
24912
+ } catch (error51) {
24913
+ const indeterminate = readCanvasOperationIndeterminateResult(error51);
24914
+ if (typeof indeterminate?.workflowRunId === "string" && indeterminate.workflowRunId && typeof indeterminate.viewNodeId === "string" && indeterminate.viewNodeId) {
24915
+ this.knownWorkflowRunIds.add(indeterminate.workflowRunId);
24916
+ this.knownWorkflowTargets.set(indeterminate.workflowRunId, indeterminate.viewNodeId);
24917
+ }
24918
+ throw error51;
24919
+ }
24597
24920
  if (typeof result3.result.workflowRunId === "string" && result3.result.workflowRunId) {
24598
24921
  this.knownWorkflowRunIds.add(result3.result.workflowRunId);
24922
+ if (typeof result3.result.viewNodeId === "string" && result3.result.viewNodeId) {
24923
+ this.knownWorkflowTargets.set(result3.result.workflowRunId, result3.result.viewNodeId);
24924
+ } else {
24925
+ this.retainWorkflowTarget(result3.result.workflowRunId);
24926
+ }
24599
24927
  }
24600
24928
  this.projectionRevision = result3.revision;
24601
24929
  if (result3.attention) this.publishAttention(result3.attention);
@@ -24619,7 +24947,8 @@ var CanvasSession = class {
24619
24947
  if (!isWorkflowRun(workflowRun)) continue;
24620
24948
  for (const fact of projectCanvasObservation(
24621
24949
  { kind: "workflow", revision: result3.revision, workflowRun },
24622
- Date.now()
24950
+ Date.now(),
24951
+ this.resolveWorkflowTarget(workflowRun.id)
24623
24952
  )) {
24624
24953
  this.watch.recordAuthoritativeWorkflow(fact);
24625
24954
  }
@@ -24718,6 +25047,28 @@ var CanvasSession = class {
24718
25047
  this.document = null;
24719
25048
  this.health.connectionId = null;
24720
25049
  }
25050
+ resolveWorkflowTarget(workflowRunId) {
25051
+ const retained = this.knownWorkflowTargets.get(workflowRunId);
25052
+ if (!this.runtime) {
25053
+ return retained ? { status: "resolved", viewNodeId: retained } : { status: "unresolved" };
25054
+ }
25055
+ const current = resolveWorkflowTargetFromSnapshot(this.runtime.getSnapshot(), workflowRunId);
25056
+ if (current.status === "ambiguous") return current;
25057
+ if (current.status === "resolved") {
25058
+ if (retained && retained !== current.viewNodeId) return { status: "ambiguous" };
25059
+ this.knownWorkflowTargets.set(workflowRunId, current.viewNodeId);
25060
+ return current;
25061
+ }
25062
+ return retained ? { status: "resolved", viewNodeId: retained } : current;
25063
+ }
25064
+ retainWorkflowTarget(workflowRunId) {
25065
+ if (!this.runtime) return { status: "unresolved" };
25066
+ const resolution = resolveWorkflowTargetFromSnapshot(this.runtime.getSnapshot(), workflowRunId);
25067
+ if (resolution.status === "resolved") {
25068
+ this.knownWorkflowTargets.set(workflowRunId, resolution.viewNodeId);
25069
+ }
25070
+ return resolution;
25071
+ }
24721
25072
  transition(state, onState) {
24722
25073
  const previousState = this.health.state;
24723
25074
  this.health.state = state;
@@ -24776,7 +25127,12 @@ var CanvasClient = class {
24776
25127
  session;
24777
25128
  receipts = [];
24778
25129
  constructor(config2, projectId, session) {
24779
- this.session = session ?? new CanvasSession(config2, projectId);
25130
+ this.session = session ?? new CanvasSession(config2, projectId, void 0, {
25131
+ workflowPreferences: (actor) => createNodeWorkflowPreferenceStore({
25132
+ accountId: actor.accountId,
25133
+ environment: config2.environment
25134
+ })
25135
+ });
24780
25136
  }
24781
25137
  async connect(displayName, onState) {
24782
25138
  await this.session.connect(displayName, onState);
@@ -24937,8 +25293,8 @@ function readTimedOut(value) {
24937
25293
  }
24938
25294
 
24939
25295
  // src/cli/config.ts
24940
- import { readFile } from "node:fs/promises";
24941
- import path2 from "node:path";
25296
+ import { readFile as readFile2 } from "node:fs/promises";
25297
+ import path3 from "node:path";
24942
25298
  var DEFAULT_ENV_FILE = ".env.local";
24943
25299
  var DEFAULT_ENVIRONMENT = "production";
24944
25300
  var ENVIRONMENT_ORIGINS = {
@@ -24948,7 +25304,7 @@ var ENVIRONMENT_ORIGINS = {
24948
25304
  async function resolveCliConfig(options, dependencies) {
24949
25305
  const cwd = dependencies.cwd ?? process.cwd();
24950
25306
  const envFile = options.envFile;
24951
- const fileEnvironment = envFile ? await readEnvironmentFile(path2.resolve(cwd, envFile)) : await readDefaultEnvironmentFile(cwd);
25307
+ const fileEnvironment = envFile ? await readEnvironmentFile(path3.resolve(cwd, envFile)) : await readDefaultEnvironmentFile(cwd);
24952
25308
  const environmentVariables = {
24953
25309
  ...fileEnvironment,
24954
25310
  ...dependencies.env ?? process.env
@@ -24970,6 +25326,7 @@ async function resolveCliConfig(options, dependencies) {
24970
25326
  return token;
24971
25327
  }
24972
25328
  },
25329
+ environment,
24973
25330
  fetch: dependencies.fetch ?? globalThis.fetch,
24974
25331
  serviceUrl: normalizeUrl(
24975
25332
  options.serviceUrl ?? environmentVariables.AZ8_SERVICE_URL ?? `${origin}/api`
@@ -24983,7 +25340,7 @@ function readEnvironment(value) {
24983
25340
  }
24984
25341
  async function readEnvironmentFile(filePath) {
24985
25342
  try {
24986
- const contents = await readFile(filePath, "utf8");
25343
+ const contents = await readFile2(filePath, "utf8");
24987
25344
  return Object.fromEntries(
24988
25345
  contents.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#")).flatMap((line) => {
24989
25346
  const separator = line.indexOf("=");
@@ -24999,11 +25356,11 @@ async function readEnvironmentFile(filePath) {
24999
25356
  }
25000
25357
  }
25001
25358
  async function readDefaultEnvironmentFile(cwd) {
25002
- let directory = path2.resolve(cwd);
25359
+ let directory = path3.resolve(cwd);
25003
25360
  while (true) {
25004
- const environment = await readEnvironmentFile(path2.join(directory, DEFAULT_ENV_FILE));
25361
+ const environment = await readEnvironmentFile(path3.join(directory, DEFAULT_ENV_FILE));
25005
25362
  if (Object.keys(environment).length > 0) return environment;
25006
- const parent = path2.dirname(directory);
25363
+ const parent = path3.dirname(directory);
25007
25364
  if (parent === directory) return {};
25008
25365
  directory = parent;
25009
25366
  }
@@ -25013,7 +25370,7 @@ function normalizeUrl(value) {
25013
25370
  }
25014
25371
 
25015
25372
  // src/agent-session/rpc.ts
25016
- import { chmod, unlink } from "node:fs/promises";
25373
+ import { chmod as chmod2, unlink } from "node:fs/promises";
25017
25374
  import net from "node:net";
25018
25375
  var MAX_RPC_REQUEST_BYTES = 1024 * 1024;
25019
25376
  var MAX_RPC_RESPONSE_BYTES = 16 * 1024 * 1024;
@@ -25125,7 +25482,7 @@ async function listenAgentSessionRpc(socketPath, handler) {
25125
25482
  resolve();
25126
25483
  });
25127
25484
  });
25128
- await chmod(socketPath, 384);
25485
+ await chmod2(socketPath, 384);
25129
25486
  return {
25130
25487
  async close() {
25131
25488
  const closed = new Promise(
@@ -25170,20 +25527,20 @@ async function unlinkIfPresent(filePath) {
25170
25527
  }
25171
25528
 
25172
25529
  // src/agent-session/state-store.ts
25173
- import { createHash as createHash2, randomUUID } from "node:crypto";
25530
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
25174
25531
  import {
25175
- chmod as chmod2,
25176
- lstat as lstat2,
25177
- mkdir,
25532
+ chmod as chmod3,
25533
+ lstat as lstat3,
25534
+ mkdir as mkdir2,
25178
25535
  readdir,
25179
- readFile as readFile2,
25536
+ readFile as readFile3,
25180
25537
  realpath,
25181
- rename,
25538
+ rename as rename2,
25182
25539
  unlink as unlink2,
25183
- writeFile
25540
+ writeFile as writeFile2
25184
25541
  } from "node:fs/promises";
25185
- import { homedir } from "node:os";
25186
- import path3 from "node:path";
25542
+ import { homedir as homedir2 } from "node:os";
25543
+ import path4 from "node:path";
25187
25544
 
25188
25545
  // src/agent-session/types.ts
25189
25546
  var AGENT_SESSION_FORMAT = "az8.agent-session.v1";
@@ -25196,44 +25553,44 @@ var AgentSessionStateStore = class {
25196
25553
  stateRoot;
25197
25554
  env;
25198
25555
  constructor(options = {}) {
25199
- this.cwd = path3.resolve(options.cwd ?? process.cwd());
25556
+ this.cwd = path4.resolve(options.cwd ?? process.cwd());
25200
25557
  this.env = options.env ?? process.env;
25201
- this.stateRoot = path3.resolve(
25202
- options.stateRoot ?? this.env.AZ8_CLI_STATE_DIR ?? path3.join(this.env.XDG_STATE_HOME ?? path3.join(homedir(), ".local", "state"), "az8-cli")
25558
+ this.stateRoot = path4.resolve(
25559
+ options.stateRoot ?? this.env.AZ8_CLI_STATE_DIR ?? path4.join(this.env.XDG_STATE_HOME ?? path4.join(homedir2(), ".local", "state"), "az8-cli")
25203
25560
  );
25204
25561
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
25205
- const defaultRuntimeRoot = process.platform === "linux" && this.env.XDG_RUNTIME_DIR ? path3.join(this.env.XDG_RUNTIME_DIR, "az8-cli") : path3.join("/tmp", `az8-cli-${uid}`);
25206
- this.runtimeRoot = path3.resolve(options.runtimeRoot ?? defaultRuntimeRoot);
25562
+ const defaultRuntimeRoot = process.platform === "linux" && this.env.XDG_RUNTIME_DIR ? path4.join(this.env.XDG_RUNTIME_DIR, "az8-cli") : path4.join("/tmp", `az8-cli-${uid}`);
25563
+ this.runtimeRoot = path4.resolve(options.runtimeRoot ?? defaultRuntimeRoot);
25207
25564
  }
25208
25565
  createSessionId() {
25209
- return `session_${randomUUID()}`;
25566
+ return `session_${randomUUID2()}`;
25210
25567
  }
25211
25568
  async initialize() {
25212
25569
  await Promise.all([
25213
- ensurePrivateDirectory(this.stateRoot),
25214
- ensurePrivateDirectory(this.runtimeRoot),
25215
- ensurePrivateDirectory(this.descriptorsDirectory()),
25216
- ensurePrivateDirectory(this.contextsDirectory()),
25217
- ensurePrivateDirectory(this.launchesDirectory())
25570
+ ensurePrivateDirectory2(this.stateRoot),
25571
+ ensurePrivateDirectory2(this.runtimeRoot),
25572
+ ensurePrivateDirectory2(this.descriptorsDirectory()),
25573
+ ensurePrivateDirectory2(this.contextsDirectory()),
25574
+ ensurePrivateDirectory2(this.launchesDirectory())
25218
25575
  ]);
25219
25576
  }
25220
25577
  descriptorPath(sessionId) {
25221
- return path3.join(this.descriptorsDirectory(), `${requireSessionId(sessionId)}.json`);
25578
+ return path4.join(this.descriptorsDirectory(), `${requireSessionId(sessionId)}.json`);
25222
25579
  }
25223
25580
  socketPath(sessionId) {
25224
- const digest = createHash2("sha256").update(requireSessionId(sessionId)).digest("hex").slice(0, 24);
25225
- return path3.join(this.runtimeRoot, `${digest}.sock`);
25581
+ const digest = createHash3("sha256").update(requireSessionId(sessionId)).digest("hex").slice(0, 24);
25582
+ return path4.join(this.runtimeRoot, `${digest}.sock`);
25226
25583
  }
25227
25584
  async writeDescriptor(descriptor2) {
25228
25585
  assertDescriptor(descriptor2);
25229
25586
  await this.initialize();
25230
- await writeJsonAtomic(this.descriptorPath(descriptor2.sessionId), descriptor2);
25587
+ await writeJsonAtomic2(this.descriptorPath(descriptor2.sessionId), descriptor2);
25231
25588
  }
25232
25589
  async readDescriptor(sessionId) {
25233
25590
  await this.initialize();
25234
25591
  const filePath = this.descriptorPath(sessionId);
25235
- await assertPrivateRegularFile(filePath);
25236
- const value = JSON.parse(await readFile2(filePath, "utf8"));
25592
+ await assertPrivateRegularFile2(filePath);
25593
+ const value = JSON.parse(await readFile3(filePath, "utf8"));
25237
25594
  assertDescriptor(value);
25238
25595
  return value;
25239
25596
  }
@@ -25255,25 +25612,25 @@ var AgentSessionStateStore = class {
25255
25612
  }
25256
25613
  async writeLaunchSpec(spec) {
25257
25614
  await this.initialize();
25258
- const filePath = path3.join(this.launchesDirectory(), `${requireSessionId(spec.sessionId)}.json`);
25259
- await writeJsonAtomic(filePath, spec);
25615
+ const filePath = path4.join(this.launchesDirectory(), `${requireSessionId(spec.sessionId)}.json`);
25616
+ await writeJsonAtomic2(filePath, spec);
25260
25617
  return filePath;
25261
25618
  }
25262
25619
  async deleteLaunchSpec(sessionId) {
25263
25620
  await unlinkIfPresent2(
25264
- path3.join(this.launchesDirectory(), `${requireSessionId(sessionId)}.json`)
25621
+ path4.join(this.launchesDirectory(), `${requireSessionId(sessionId)}.json`)
25265
25622
  );
25266
25623
  }
25267
25624
  async selectCurrent(sessionId) {
25268
25625
  await this.readDescriptor(sessionId);
25269
25626
  const context = await this.contextIdentity();
25270
- await writeJsonAtomic(this.contextPath(context), { context, sessionId });
25627
+ await writeJsonAtomic2(this.contextPath(context), { context, sessionId });
25271
25628
  }
25272
25629
  async readCurrent() {
25273
25630
  await this.initialize();
25274
25631
  const context = await this.contextIdentity();
25275
25632
  try {
25276
- const value = JSON.parse(await readFile2(this.contextPath(context), "utf8"));
25633
+ const value = JSON.parse(await readFile3(this.contextPath(context), "utf8"));
25277
25634
  if (value.context !== context || typeof value.sessionId !== "string") return void 0;
25278
25635
  return requireSessionId(value.sessionId);
25279
25636
  } catch (error51) {
@@ -25297,13 +25654,13 @@ var AgentSessionStateStore = class {
25297
25654
  return requireSessionId(selected);
25298
25655
  }
25299
25656
  descriptorsDirectory() {
25300
- return path3.join(this.stateRoot, "sessions");
25657
+ return path4.join(this.stateRoot, "sessions");
25301
25658
  }
25302
25659
  contextsDirectory() {
25303
- return path3.join(this.stateRoot, "contexts");
25660
+ return path4.join(this.stateRoot, "contexts");
25304
25661
  }
25305
25662
  launchesDirectory() {
25306
- return path3.join(this.stateRoot, "launches");
25663
+ return path4.join(this.stateRoot, "launches");
25307
25664
  }
25308
25665
  async contextIdentity() {
25309
25666
  const override = this.env.AZ8_CONTEXT?.trim();
@@ -25315,16 +25672,16 @@ var AgentSessionStateStore = class {
25315
25672
  }
25316
25673
  }
25317
25674
  contextPath(context) {
25318
- const digest = createHash2("sha256").update(context).digest("hex");
25319
- return path3.join(this.contextsDirectory(), `${digest}.json`);
25675
+ const digest = createHash3("sha256").update(context).digest("hex");
25676
+ return path4.join(this.contextsDirectory(), `${digest}.json`);
25320
25677
  }
25321
25678
  };
25322
25679
  async function readAndDeleteLaunchSpec(filePath) {
25323
- if (path3.basename(path3.dirname(filePath)) !== "launches") {
25680
+ if (path4.basename(path4.dirname(filePath)) !== "launches") {
25324
25681
  throw sessionStateError("invalid-session-launch", "Session launch path is invalid.");
25325
25682
  }
25326
- await assertPrivateRegularFile(filePath);
25327
- const value = JSON.parse(await readFile2(filePath, "utf8"));
25683
+ await assertPrivateRegularFile2(filePath);
25684
+ const value = JSON.parse(await readFile3(filePath, "utf8"));
25328
25685
  assertLaunchSpec(value, filePath);
25329
25686
  await unlinkIfPresent2(filePath);
25330
25687
  return value;
@@ -25346,30 +25703,30 @@ function assertLaunchSpec(value, launchPath) {
25346
25703
  throw sessionStateError("invalid-session-launch", "Session launch descriptor is invalid.");
25347
25704
  }
25348
25705
  const sessionId = requireSessionId(value.sessionId);
25349
- const stateRoot = path3.resolve(value.stateRoot);
25350
- const expectedLaunch = path3.join(stateRoot, "launches", `${sessionId}.json`);
25351
- if (path3.resolve(launchPath) !== expectedLaunch) {
25706
+ const stateRoot = path4.resolve(value.stateRoot);
25707
+ const expectedLaunch = path4.join(stateRoot, "launches", `${sessionId}.json`);
25708
+ if (path4.resolve(launchPath) !== expectedLaunch) {
25352
25709
  throw sessionStateError(
25353
25710
  "invalid-session-launch",
25354
25711
  "Session launch identity does not match its path."
25355
25712
  );
25356
25713
  }
25357
- const expectedDescriptor = path3.join(stateRoot, "sessions", `${sessionId}.json`);
25358
- if (path3.resolve(value.descriptorPath) !== expectedDescriptor) {
25714
+ const expectedDescriptor = path4.join(stateRoot, "sessions", `${sessionId}.json`);
25715
+ if (path4.resolve(value.descriptorPath) !== expectedDescriptor) {
25359
25716
  throw sessionStateError("invalid-session-launch", "Session descriptor path is invalid.");
25360
25717
  }
25361
- const socketDigest = createHash2("sha256").update(sessionId).digest("hex").slice(0, 24);
25362
- const expectedSocket = path3.join(
25363
- path3.resolve(value.runtimeRoot),
25718
+ const socketDigest = createHash3("sha256").update(sessionId).digest("hex").slice(0, 24);
25719
+ const expectedSocket = path4.join(
25720
+ path4.resolve(value.runtimeRoot),
25364
25721
  `${socketDigest}.sock`
25365
25722
  );
25366
- if (path3.resolve(value.socketPath) !== expectedSocket) {
25723
+ if (path4.resolve(value.socketPath) !== expectedSocket) {
25367
25724
  throw sessionStateError("invalid-session-launch", "Session socket path is invalid.");
25368
25725
  }
25369
25726
  }
25370
- async function ensurePrivateDirectory(directory) {
25371
- await mkdir(directory, { mode: 448, recursive: true });
25372
- const metadata = await lstat2(directory);
25727
+ async function ensurePrivateDirectory2(directory) {
25728
+ await mkdir2(directory, { mode: 448, recursive: true });
25729
+ const metadata = await lstat3(directory);
25373
25730
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
25374
25731
  throw sessionStateError(
25375
25732
  "unsafe-session-state",
@@ -25382,10 +25739,10 @@ async function ensurePrivateDirectory(directory) {
25382
25739
  "Session state directory has a different owner."
25383
25740
  );
25384
25741
  }
25385
- await chmod2(directory, 448);
25742
+ await chmod3(directory, 448);
25386
25743
  }
25387
- async function assertPrivateRegularFile(filePath) {
25388
- const metadata = await lstat2(filePath);
25744
+ async function assertPrivateRegularFile2(filePath) {
25745
+ const metadata = await lstat3(filePath);
25389
25746
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
25390
25747
  throw sessionStateError("unsafe-session-state", "Session state file is not a regular file.");
25391
25748
  }
@@ -25396,12 +25753,12 @@ async function assertPrivateRegularFile(filePath) {
25396
25753
  throw sessionStateError("unsafe-session-state", "Session state file is not owner-private.");
25397
25754
  }
25398
25755
  }
25399
- async function writeJsonAtomic(filePath, value) {
25400
- const temporary = `${filePath}.${randomUUID()}.tmp`;
25401
- await writeFile(temporary, `${JSON.stringify(value, null, 2)}
25756
+ async function writeJsonAtomic2(filePath, value) {
25757
+ const temporary = `${filePath}.${randomUUID2()}.tmp`;
25758
+ await writeFile2(temporary, `${JSON.stringify(value, null, 2)}
25402
25759
  `, { mode: 384 });
25403
- await rename(temporary, filePath);
25404
- await chmod2(filePath, 384);
25760
+ await rename2(temporary, filePath);
25761
+ await chmod3(filePath, 384);
25405
25762
  }
25406
25763
  async function unlinkIfPresent2(filePath) {
25407
25764
  try {
@@ -25594,7 +25951,13 @@ async function createCanvasClient(spec, dependencies) {
25594
25951
  ...dependencies,
25595
25952
  cwd: spec.cwd
25596
25953
  });
25597
- const session = new CanvasSession(config2, spec.projectId);
25954
+ const session = new CanvasSession(config2, spec.projectId, void 0, {
25955
+ workflowPreferences: (actor) => createNodeWorkflowPreferenceStore({
25956
+ accountId: actor.accountId,
25957
+ environment: config2.environment,
25958
+ stateRoot: spec.stateRoot
25959
+ })
25960
+ });
25598
25961
  const client = new CanvasClient(config2, spec.projectId, session);
25599
25962
  await client.connect(spec.clientName);
25600
25963
  return {
@@ -25648,13 +26011,13 @@ function assertRequest(request) {
25648
26011
  code: "invalid-watch-timeout"
25649
26012
  });
25650
26013
  }
25651
- if (request.kind === "interests.patch" && !isRecord4(request.input)) invalidPayload();
26014
+ if (request.kind === "interests.patch" && !isRecord5(request.input)) invalidPayload();
25652
26015
  if (request.kind === "query") {
25653
- if (!isRecord4(request.input) || typeof request.input.target !== "string") invalidPayload();
26016
+ if (!isRecord5(request.input) || typeof request.input.target !== "string") invalidPayload();
25654
26017
  parseCanvasQueryTarget(request.input.target);
25655
26018
  }
25656
26019
  if (request.kind === "operation") {
25657
- if (!isRecord4(request.input) || typeof request.name !== "string" || typeof request.requestId !== "string" || request.requestId.length === 0 || request.timeoutMs !== void 0 && (!Number.isInteger(request.timeoutMs) || request.timeoutMs < 1)) {
26020
+ if (!isRecord5(request.input) || typeof request.name !== "string" || typeof request.requestId !== "string" || request.requestId.length === 0 || request.timeoutMs !== void 0 && (!Number.isInteger(request.timeoutMs) || request.timeoutMs < 1)) {
25658
26021
  invalidPayload();
25659
26022
  }
25660
26023
  }
@@ -25670,7 +26033,7 @@ function invalidPayload() {
25670
26033
  code: "invalid-session-request"
25671
26034
  });
25672
26035
  }
25673
- function isRecord4(value) {
26036
+ function isRecord5(value) {
25674
26037
  return typeof value === "object" && value !== null && !Array.isArray(value);
25675
26038
  }
25676
26039
  function readErrorCode2(error51) {
@@ -26407,7 +26770,7 @@ function humanReadableArgName(arg) {
26407
26770
  // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
26408
26771
  import { EventEmitter as EventEmitter2 } from "node:events";
26409
26772
  import childProcess from "node:child_process";
26410
- import path4 from "node:path";
26773
+ import path5 from "node:path";
26411
26774
  import fs from "node:fs";
26412
26775
  import process2 from "node:process";
26413
26776
  import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
@@ -28393,9 +28756,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
28393
28756
  args2 = args2.slice();
28394
28757
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
28395
28758
  function findFile(baseDir, baseName) {
28396
- const localBin = path4.resolve(baseDir, baseName);
28759
+ const localBin = path5.resolve(baseDir, baseName);
28397
28760
  if (fs.existsSync(localBin)) return localBin;
28398
- if (sourceExt.includes(path4.extname(baseName))) return void 0;
28761
+ if (sourceExt.includes(path5.extname(baseName))) return void 0;
28399
28762
  const foundExt = sourceExt.find(
28400
28763
  (ext) => fs.existsSync(`${localBin}${ext}`)
28401
28764
  );
@@ -28413,17 +28776,17 @@ Expecting one of '${allowedValues.join("', '")}'`);
28413
28776
  } catch {
28414
28777
  resolvedScriptPath = this._scriptPath;
28415
28778
  }
28416
- executableDir = path4.resolve(
28417
- path4.dirname(resolvedScriptPath),
28779
+ executableDir = path5.resolve(
28780
+ path5.dirname(resolvedScriptPath),
28418
28781
  executableDir
28419
28782
  );
28420
28783
  }
28421
28784
  if (executableDir) {
28422
28785
  let localFile = findFile(executableDir, executableFile);
28423
28786
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
28424
- const legacyName = path4.basename(
28787
+ const legacyName = path5.basename(
28425
28788
  this._scriptPath,
28426
- path4.extname(this._scriptPath)
28789
+ path5.extname(this._scriptPath)
28427
28790
  );
28428
28791
  if (legacyName !== this._name) {
28429
28792
  localFile = findFile(
@@ -28434,7 +28797,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
28434
28797
  }
28435
28798
  executableFile = localFile || executableFile;
28436
28799
  }
28437
- const launchWithNode = sourceExt.includes(path4.extname(executableFile));
28800
+ const launchWithNode = sourceExt.includes(path5.extname(executableFile));
28438
28801
  let proc;
28439
28802
  if (process2.platform !== "win32") {
28440
28803
  if (launchWithNode) {
@@ -29351,7 +29714,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
29351
29714
  * @return {Command}
29352
29715
  */
29353
29716
  nameFromFilename(filename) {
29354
- this._name = path4.basename(filename, path4.extname(filename));
29717
+ this._name = path5.basename(filename, path5.extname(filename));
29355
29718
  return this;
29356
29719
  }
29357
29720
  /**
@@ -29365,9 +29728,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
29365
29728
  * @param {string} [path]
29366
29729
  * @return {(string|null|Command)}
29367
29730
  */
29368
- executableDir(path9) {
29369
- if (path9 === void 0) return this._executableDir;
29370
- this._executableDir = path9;
29731
+ executableDir(path10) {
29732
+ if (path10 === void 0) return this._executableDir;
29733
+ this._executableDir = path10;
29371
29734
  return this;
29372
29735
  }
29373
29736
  /**
@@ -29623,8 +29986,8 @@ function useColor() {
29623
29986
  var program = new Command();
29624
29987
 
29625
29988
  // src/canvas/one-shot.ts
29626
- import { readFile as readFile3 } from "node:fs/promises";
29627
- import path5 from "node:path";
29989
+ import { readFile as readFile4 } from "node:fs/promises";
29990
+ import path6 from "node:path";
29628
29991
  var MAX_INPUT_BYTES = 1024 * 1024;
29629
29992
  var PROCESS_SCOPED_OPERATIONS = /* @__PURE__ */ new Set(["redo", "undo"]);
29630
29993
  var PROCESS_SCOPED_QUERIES = /* @__PURE__ */ new Set(["receipt.detail", "receipts.summary"]);
@@ -29676,9 +30039,9 @@ async function readCanvasOneShotInputOptions(options, dependencies = {}) {
29676
30039
  let source = "{}";
29677
30040
  if (inline !== void 0) source = inline;
29678
30041
  if (file2 !== void 0) {
29679
- const filePath = path5.resolve(dependencies.cwd ?? process.cwd(), file2);
30042
+ const filePath = path6.resolve(dependencies.cwd ?? process.cwd(), file2);
29680
30043
  try {
29681
- source = dependencies.readFile ? await dependencies.readFile(filePath) : await readFile3(filePath, "utf8");
30044
+ source = dependencies.readFile ? await dependencies.readFile(filePath) : await readFile4(filePath, "utf8");
29682
30045
  } catch {
29683
30046
  throw canvasClientFailure(
29684
30047
  "invalid-operation-input",
@@ -29799,9 +30162,9 @@ function formatZodError(error51) {
29799
30162
  }
29800
30163
 
29801
30164
  // src/media/download.ts
29802
- import { createHash as createHash3 } from "node:crypto";
29803
- import { link, lstat as lstat3, open as open2, rename as rename2, stat, unlink as unlink3 } from "node:fs/promises";
29804
- import path6 from "node:path";
30165
+ import { createHash as createHash4 } from "node:crypto";
30166
+ import { link, lstat as lstat4, open as open2, rename as rename3, stat, unlink as unlink3 } from "node:fs/promises";
30167
+ import path7 from "node:path";
29805
30168
 
29806
30169
  // ../../packages/foundation-data/dist/media.js
29807
30170
  var CoreNodeMediaResolutionError = class extends Error {
@@ -29855,7 +30218,7 @@ var MediaDownloadError = class extends Error {
29855
30218
  details;
29856
30219
  };
29857
30220
  async function runCanvasMediaDownload(config2, command, dependencies = {}) {
29858
- const requestedAbsolutePath = path6.resolve(dependencies.cwd ?? process.cwd(), command.outputPath);
30221
+ const requestedAbsolutePath = path7.resolve(dependencies.cwd ?? process.cwd(), command.outputPath);
29859
30222
  let outputTarget;
29860
30223
  try {
29861
30224
  outputTarget = await prepareOutputTarget(
@@ -29946,7 +30309,7 @@ function formatCanvasMediaDownloadResult(result3) {
29946
30309
  return `${JSON.stringify(result3.output, null, 2)}
29947
30310
  `;
29948
30311
  }
29949
- async function resolveMediaSource(client, command, randomUUID4) {
30312
+ async function resolveMediaSource(client, command, randomUUID5) {
29950
30313
  let coreNodeId;
29951
30314
  if (command.source.kind === "view-node") {
29952
30315
  try {
@@ -29966,7 +30329,7 @@ async function resolveMediaSource(client, command, randomUUID4) {
29966
30329
  const outcome = await client.executeOperation({
29967
30330
  input: { coreNodeId },
29968
30331
  name: "getCoreNode",
29969
- requestId: `media-download-resolve-${randomUUID4?.() ?? crypto.randomUUID()}`,
30332
+ requestId: `media-download-resolve-${randomUUID5?.() ?? crypto.randomUUID()}`,
29970
30333
  timeoutMs: command.timeoutMs ?? DEFAULT_RESOLUTION_TIMEOUT_MS
29971
30334
  });
29972
30335
  if (outcome.receipt.status !== "succeeded") {
@@ -30021,8 +30384,8 @@ async function prepareOutputTarget(requestedPath, overwrite, cwd) {
30021
30384
  { phase: "output-setup" }
30022
30385
  );
30023
30386
  }
30024
- const absolutePath = path6.resolve(cwd, requestedPath);
30025
- const parentPath = path6.dirname(absolutePath);
30387
+ const absolutePath = path7.resolve(cwd, requestedPath);
30388
+ const parentPath = path7.dirname(absolutePath);
30026
30389
  let parent;
30027
30390
  try {
30028
30391
  parent = await stat(parentPath);
@@ -30046,7 +30409,7 @@ async function prepareOutputTarget(requestedPath, overwrite, cwd) {
30046
30409
  }
30047
30410
  let existing;
30048
30411
  try {
30049
- existing = await lstat3(absolutePath);
30412
+ existing = await lstat4(absolutePath);
30050
30413
  } catch (error51) {
30051
30414
  if (readFsCode2(error51) !== "ENOENT") {
30052
30415
  throw new MediaDownloadError(
@@ -30211,9 +30574,9 @@ async function detectFileTypeFromFileHeader(filePath) {
30211
30574
  }
30212
30575
  async function openTemporaryFile(outputTarget, identity) {
30213
30576
  const safeIdentity = identity.replace(/[^a-z0-9-]/gi, "").slice(0, 64) || "download";
30214
- const basename = path6.basename(outputTarget.absolutePath);
30577
+ const basename = path7.basename(outputTarget.absolutePath);
30215
30578
  for (let attempt = 0; attempt < 3; attempt += 1) {
30216
- const temporaryPath = path6.join(
30579
+ const temporaryPath = path7.join(
30217
30580
  outputTarget.parentPath,
30218
30581
  `.${basename}.az8-${safeIdentity}-${attempt}.part`
30219
30582
  );
@@ -30248,7 +30611,7 @@ async function streamResponseToFile(response, handle, deadline, expectedBytes) {
30248
30611
  );
30249
30612
  }
30250
30613
  const reader = response.body.getReader();
30251
- const hash2 = createHash3("sha256");
30614
+ const hash2 = createHash4("sha256");
30252
30615
  let bytes = 0;
30253
30616
  try {
30254
30617
  while (true) {
@@ -30329,7 +30692,7 @@ function validateDownloadedMedia(media, contentType, detected) {
30329
30692
  async function commitTemporaryFile(temporaryPath, outputTarget, overwrite) {
30330
30693
  try {
30331
30694
  if (overwrite) {
30332
- await rename2(temporaryPath, outputTarget.absolutePath);
30695
+ await rename3(temporaryPath, outputTarget.absolutePath);
30333
30696
  return;
30334
30697
  }
30335
30698
  await link(temporaryPath, outputTarget.absolutePath);
@@ -30441,7 +30804,7 @@ function failureResult2(command, error51, absolutePath, attemptsCompleted = 1, m
30441
30804
  destinationCommitted: false,
30442
30805
  partialFileRetained: false
30443
30806
  },
30444
- outputPath: absolutePath ?? path6.resolve(command.outputPath),
30807
+ outputPath: absolutePath ?? path7.resolve(command.outputPath),
30445
30808
  projectId: command.projectId,
30446
30809
  attempts: { completed: attemptsCompleted, maximum: maximumAttempts },
30447
30810
  remoteState: "unverified",
@@ -30605,8 +30968,8 @@ function canvasOneShotSetupError(kind, projectId, capability, error51) {
30605
30968
  }
30606
30969
 
30607
30970
  // src/commands/canvas.ts
30608
- import { randomUUID as randomUUID2 } from "node:crypto";
30609
- import path7 from "node:path";
30971
+ import { randomUUID as randomUUID3 } from "node:crypto";
30972
+ import path8 from "node:path";
30610
30973
 
30611
30974
  // src/integrations/snapshot-reader.ts
30612
30975
  function createAz8StudioSnapshotReader(config2) {
@@ -31427,10 +31790,10 @@ function mergeDefs(...defs) {
31427
31790
  function cloneDef(schema) {
31428
31791
  return mergeDefs(schema._zod.def);
31429
31792
  }
31430
- function getElementAtPath(obj, path9) {
31431
- if (!path9)
31793
+ function getElementAtPath(obj, path10) {
31794
+ if (!path10)
31432
31795
  return obj;
31433
- return path9.reduce((acc, key) => acc?.[key], obj);
31796
+ return path10.reduce((acc, key) => acc?.[key], obj);
31434
31797
  }
31435
31798
  function promiseAllObject(promisesObj) {
31436
31799
  const keys2 = Object.keys(promisesObj);
@@ -31839,11 +32202,11 @@ function explicitlyAborted(x, startIndex = 0) {
31839
32202
  }
31840
32203
  return false;
31841
32204
  }
31842
- function prefixIssues(path9, issues) {
32205
+ function prefixIssues(path10, issues) {
31843
32206
  return issues.map((iss) => {
31844
32207
  var _a3;
31845
32208
  (_a3 = iss).path ?? (_a3.path = []);
31846
- iss.path.unshift(path9);
32209
+ iss.path.unshift(path10);
31847
32210
  return iss;
31848
32211
  });
31849
32212
  }
@@ -31990,16 +32353,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
31990
32353
  }
31991
32354
  function formatError(error51, mapper = (issue2) => issue2.message) {
31992
32355
  const fieldErrors = { _errors: [] };
31993
- const processError = (error52, path9 = []) => {
32356
+ const processError = (error52, path10 = []) => {
31994
32357
  for (const issue2 of error52.issues) {
31995
32358
  if (issue2.code === "invalid_union" && issue2.errors.length) {
31996
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
32359
+ issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
31997
32360
  } else if (issue2.code === "invalid_key") {
31998
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
32361
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
31999
32362
  } else if (issue2.code === "invalid_element") {
32000
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
32363
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
32001
32364
  } else {
32002
- const fullpath = [...path9, ...issue2.path];
32365
+ const fullpath = [...path10, ...issue2.path];
32003
32366
  if (fullpath.length === 0) {
32004
32367
  fieldErrors._errors.push(mapper(issue2));
32005
32368
  } else {
@@ -32026,17 +32389,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
32026
32389
  }
32027
32390
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
32028
32391
  const result3 = { errors: [] };
32029
- const processError = (error52, path9 = []) => {
32392
+ const processError = (error52, path10 = []) => {
32030
32393
  var _a3, _b;
32031
32394
  for (const issue2 of error52.issues) {
32032
32395
  if (issue2.code === "invalid_union" && issue2.errors.length) {
32033
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
32396
+ issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
32034
32397
  } else if (issue2.code === "invalid_key") {
32035
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
32398
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
32036
32399
  } else if (issue2.code === "invalid_element") {
32037
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
32400
+ processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
32038
32401
  } else {
32039
- const fullpath = [...path9, ...issue2.path];
32402
+ const fullpath = [...path10, ...issue2.path];
32040
32403
  if (fullpath.length === 0) {
32041
32404
  result3.errors.push(mapper(issue2));
32042
32405
  continue;
@@ -32068,8 +32431,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
32068
32431
  }
32069
32432
  function toDotPath(_path) {
32070
32433
  const segs = [];
32071
- const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
32072
- for (const seg of path9) {
32434
+ const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
32435
+ for (const seg of path10) {
32073
32436
  if (typeof seg === "number")
32074
32437
  segs.push(`[${seg}]`);
32075
32438
  else if (typeof seg === "symbol")
@@ -44761,13 +45124,13 @@ function resolveRef(ref, ctx) {
44761
45124
  if (!ref.startsWith("#")) {
44762
45125
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
44763
45126
  }
44764
- const path9 = ref.slice(1).split("/").filter(Boolean);
44765
- if (path9.length === 0) {
45127
+ const path10 = ref.slice(1).split("/").filter(Boolean);
45128
+ if (path10.length === 0) {
44766
45129
  return ctx.rootSchema;
44767
45130
  }
44768
45131
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
44769
- if (path9[0] === defsKey) {
44770
- const key = path9[1];
45132
+ if (path10[0] === defsKey) {
45133
+ const key = path10[1];
44771
45134
  if (!key || !ctx.defs[key]) {
44772
45135
  throw new Error(`Reference not found: ${ref}`);
44773
45136
  }
@@ -45337,7 +45700,7 @@ function registerCanvasCommands(program2, dependencies, setResult) {
45337
45700
  return "invalid-option";
45338
45701
  });
45339
45702
  const config2 = await resolveCliConfig(readConfigOptions(command), dependencies);
45340
- const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID2();
45703
+ const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID3();
45341
45704
  const result3 = await runCanvasOneShot(
45342
45705
  config2,
45343
45706
  {
@@ -45346,7 +45709,7 @@ function registerCanvasCommands(program2, dependencies, setResult) {
45346
45709
  idempotencyKey: options.idempotencyKey,
45347
45710
  ...options.name ? { name: options.name } : {},
45348
45711
  ...options.positionX !== void 0 && options.positionY !== void 0 ? { position: { x: options.positionX, y: options.positionY } } : {},
45349
- source: path7.resolve(dependencies.cwd ?? process.cwd(), options.file)
45712
+ source: path8.resolve(dependencies.cwd ?? process.cwd(), options.file)
45350
45713
  },
45351
45714
  kind: "operation",
45352
45715
  name: "uploadMedia",
@@ -45422,7 +45785,7 @@ function registerCanvasCommands(program2, dependencies, setResult) {
45422
45785
  (issue2) => issue2.path[0] === "input" ? "invalid-input-source" : "invalid-option"
45423
45786
  );
45424
45787
  const config2 = await resolveCliConfig(readConfigOptions(command), dependencies);
45425
- const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID2();
45788
+ const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID3();
45426
45789
  const result3 = await runCanvasOneShot(
45427
45790
  config2,
45428
45791
  {
@@ -45447,7 +45810,7 @@ function registerCanvasCommands(program2, dependencies, setResult) {
45447
45810
  // package.json
45448
45811
  var package_default = {
45449
45812
  name: "@everfir/az8-cli",
45450
- version: "0.3.0-preview.3",
45813
+ version: "0.3.0",
45451
45814
  description: "Semantic Project Canvas client for AZ8 Studio agents.",
45452
45815
  license: "UNLICENSED",
45453
45816
  type: "module",
@@ -45463,7 +45826,7 @@ var package_default = {
45463
45826
  main: "./dist/main.js",
45464
45827
  publishConfig: {
45465
45828
  access: "public",
45466
- tag: "preview"
45829
+ tag: "latest"
45467
45830
  },
45468
45831
  scripts: {
45469
45832
  build: `pnpm build:dependencies && rm -rf dist && esbuild src/main.ts --bundle --platform=node --format=esm --target=node22.12 --banner:js='import { createRequire } from "node:module"; const require = createRequire(import.meta.url);' --outfile=dist/main.js`,
@@ -45514,7 +45877,7 @@ function readAz8CliVersion() {
45514
45877
  }
45515
45878
 
45516
45879
  // src/guide/agent-guide.ts
45517
- import { readFile as readFile4 } from "node:fs/promises";
45880
+ import { readFile as readFile5 } from "node:fs/promises";
45518
45881
  var AGENT_GUIDE_URLS = [
45519
45882
  new URL("../skills/az8-cli/SKILL.md", import.meta.url),
45520
45883
  new URL("../../skills/az8-cli/SKILL.md", import.meta.url)
@@ -45547,7 +45910,7 @@ async function renderAgentGuide(options) {
45547
45910
  async function readPackagedGuide() {
45548
45911
  for (const candidate of AGENT_GUIDE_URLS) {
45549
45912
  try {
45550
- return await readFile4(candidate, "utf8");
45913
+ return await readFile5(candidate, "utf8");
45551
45914
  } catch (error51) {
45552
45915
  if (error51.code !== "ENOENT") throw error51;
45553
45916
  }
@@ -45659,11 +46022,11 @@ async function withProjectClient(command, dependencies, setResult, action) {
45659
46022
  }
45660
46023
 
45661
46024
  // src/commands/session.ts
45662
- import { randomUUID as randomUUID3 } from "node:crypto";
46025
+ import { randomUUID as randomUUID4 } from "node:crypto";
45663
46026
 
45664
46027
  // src/agent-session/manager.ts
45665
46028
  import { spawn } from "node:child_process";
45666
- import path8 from "node:path";
46029
+ import path9 from "node:path";
45667
46030
  var AgentSessionManager = class {
45668
46031
  constructor(options = {}) {
45669
46032
  this.options = options;
@@ -45691,7 +46054,7 @@ var AgentSessionManager = class {
45691
46054
  const descriptorPath = this.store.descriptorPath(sessionId);
45692
46055
  const config2 = {
45693
46056
  ...input.config,
45694
- ...input.config.envFile ? { envFile: path8.resolve(this.store.cwd, input.config.envFile) } : {}
46057
+ ...input.config.envFile ? { envFile: path9.resolve(this.store.cwd, input.config.envFile) } : {}
45695
46058
  };
45696
46059
  const descriptor2 = {
45697
46060
  clientName,
@@ -46170,7 +46533,7 @@ function registerSessionCommands(program2, dependencies, setResult) {
46170
46533
  ...recordOptions(rawOptions),
46171
46534
  session: readSessionOption(command)
46172
46535
  });
46173
- const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID3();
46536
+ const requestId = options.requestId ?? dependencies.randomUUID?.() ?? randomUUID4();
46174
46537
  const { descriptor: descriptor2, value } = await manager.call(
46175
46538
  {
46176
46539
  input: await readCanvasOneShotInputOptions(options, dependencies),
@@ -46250,7 +46613,7 @@ function publicDescriptor(descriptor2) {
46250
46613
  };
46251
46614
  }
46252
46615
  function requireWatchDelivery(value) {
46253
- if (!("result" in value) || !isRecord5(value.result)) {
46616
+ if (!("result" in value) || !isRecord6(value.result)) {
46254
46617
  throw new Error("Agent Session returned an invalid Watch delivery.");
46255
46618
  }
46256
46619
  return value;
@@ -46265,7 +46628,7 @@ function readCanvasSummary(value) {
46265
46628
  return "canvas" in value ? value.canvas : value;
46266
46629
  }
46267
46630
  function readOperationReceipt(value) {
46268
- if (!("receipt" in value) || !isRecord5(value.receipt)) {
46631
+ if (!("receipt" in value) || !isRecord6(value.receipt)) {
46269
46632
  throw new Error("Agent Session returned an invalid Operation Receipt.");
46270
46633
  }
46271
46634
  return value.receipt;
@@ -46288,11 +46651,11 @@ function sessionError(error51) {
46288
46651
  `
46289
46652
  };
46290
46653
  }
46291
- function isRecord5(value) {
46654
+ function isRecord6(value) {
46292
46655
  return typeof value === "object" && value !== null && !Array.isArray(value);
46293
46656
  }
46294
46657
  function recordOptions(value) {
46295
- return isRecord5(value) ? value : {};
46658
+ return isRecord6(value) ? value : {};
46296
46659
  }
46297
46660
 
46298
46661
  // src/cli/program.ts