gooseworks 0.5.9-dev.53.c1bd6be2 → 0.5.9-dev.56.eca9486d

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.
Files changed (150) hide show
  1. package/dist/agents/claude-mcp.d.ts +7 -1
  2. package/dist/agents/claude-mcp.d.ts.map +1 -1
  3. package/dist/agents/claude-mcp.js +43 -10
  4. package/dist/agents/claude-mcp.js.map +1 -1
  5. package/dist/auth/credentials.d.ts +8 -0
  6. package/dist/auth/credentials.d.ts.map +1 -1
  7. package/dist/auth/credentials.js +35 -1
  8. package/dist/auth/credentials.js.map +1 -1
  9. package/dist/auth/device-flow.d.ts +4 -1
  10. package/dist/auth/device-flow.d.ts.map +1 -1
  11. package/dist/auth/device-flow.js +8 -3
  12. package/dist/auth/device-flow.js.map +1 -1
  13. package/dist/auth/oauth-server.d.ts +9 -1
  14. package/dist/auth/oauth-server.d.ts.map +1 -1
  15. package/dist/auth/oauth-server.js +19 -11
  16. package/dist/auth/oauth-server.js.map +1 -1
  17. package/dist/auth/revoke.d.ts +10 -0
  18. package/dist/auth/revoke.d.ts.map +1 -0
  19. package/dist/auth/revoke.js +31 -0
  20. package/dist/auth/revoke.js.map +1 -0
  21. package/dist/commands/login.d.ts +15 -1
  22. package/dist/commands/login.d.ts.map +1 -1
  23. package/dist/commands/login.js +34 -10
  24. package/dist/commands/login.js.map +1 -1
  25. package/dist/commands/logout.d.ts.map +1 -1
  26. package/dist/commands/logout.js +29 -11
  27. package/dist/commands/logout.js.map +1 -1
  28. package/dist/commands/video.d.ts +35 -0
  29. package/dist/commands/video.d.ts.map +1 -1
  30. package/dist/commands/video.js +475 -39
  31. package/dist/commands/video.js.map +1 -1
  32. package/dist/index.js +2 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/kit/core/canonical.d.ts +3 -1
  35. package/dist/kit/core/canonical.d.ts.map +1 -1
  36. package/dist/kit/core/canonical.js +1 -1
  37. package/dist/kit/core/canonical.js.map +1 -1
  38. package/dist/kit/core/check.d.ts +2 -0
  39. package/dist/kit/core/check.d.ts.map +1 -1
  40. package/dist/kit/core/check.js +12 -2
  41. package/dist/kit/core/check.js.map +1 -1
  42. package/dist/kit/core/detach.d.ts +11 -0
  43. package/dist/kit/core/detach.d.ts.map +1 -0
  44. package/dist/kit/core/detach.js +72 -0
  45. package/dist/kit/core/detach.js.map +1 -0
  46. package/dist/kit/core/diff.d.ts +5 -0
  47. package/dist/kit/core/diff.d.ts.map +1 -0
  48. package/dist/kit/core/diff.js +132 -0
  49. package/dist/kit/core/diff.js.map +1 -0
  50. package/dist/kit/core/errors.d.ts +7 -1
  51. package/dist/kit/core/errors.d.ts.map +1 -1
  52. package/dist/kit/core/errors.js +11 -1
  53. package/dist/kit/core/errors.js.map +1 -1
  54. package/dist/kit/core/eyes.d.ts +80 -0
  55. package/dist/kit/core/eyes.d.ts.map +1 -0
  56. package/dist/kit/core/eyes.js +366 -0
  57. package/dist/kit/core/eyes.js.map +1 -0
  58. package/dist/kit/core/files.js +2 -2
  59. package/dist/kit/core/files.js.map +1 -1
  60. package/dist/kit/core/lock.d.ts +4 -0
  61. package/dist/kit/core/lock.d.ts.map +1 -0
  62. package/dist/kit/core/lock.js +13 -0
  63. package/dist/kit/core/lock.js.map +1 -0
  64. package/dist/kit/core/log.d.ts +38 -2
  65. package/dist/kit/core/log.d.ts.map +1 -1
  66. package/dist/kit/core/log.js +38 -5
  67. package/dist/kit/core/log.js.map +1 -1
  68. package/dist/kit/core/outcome.d.ts +114 -0
  69. package/dist/kit/core/outcome.d.ts.map +1 -0
  70. package/dist/kit/core/outcome.js +246 -0
  71. package/dist/kit/core/outcome.js.map +1 -0
  72. package/dist/kit/core/patch.d.ts +64 -0
  73. package/dist/kit/core/patch.d.ts.map +1 -0
  74. package/dist/kit/core/patch.js +289 -0
  75. package/dist/kit/core/patch.js.map +1 -0
  76. package/dist/kit/core/paths.d.ts +17 -0
  77. package/dist/kit/core/paths.d.ts.map +1 -1
  78. package/dist/kit/core/paths.js +21 -0
  79. package/dist/kit/core/paths.js.map +1 -1
  80. package/dist/kit/core/pieces.d.ts +16 -4
  81. package/dist/kit/core/pieces.d.ts.map +1 -1
  82. package/dist/kit/core/pieces.js +84 -27
  83. package/dist/kit/core/pieces.js.map +1 -1
  84. package/dist/kit/core/progress-reporter.d.ts +21 -4
  85. package/dist/kit/core/progress-reporter.d.ts.map +1 -1
  86. package/dist/kit/core/progress-reporter.js +74 -12
  87. package/dist/kit/core/progress-reporter.js.map +1 -1
  88. package/dist/kit/core/progress.d.ts +18 -1
  89. package/dist/kit/core/progress.d.ts.map +1 -1
  90. package/dist/kit/core/progress.js +44 -1
  91. package/dist/kit/core/progress.js.map +1 -1
  92. package/dist/kit/core/refusal-log.d.ts +7 -0
  93. package/dist/kit/core/refusal-log.d.ts.map +1 -0
  94. package/dist/kit/core/refusal-log.js +54 -0
  95. package/dist/kit/core/refusal-log.js.map +1 -0
  96. package/dist/kit/core/run.d.ts +35 -5
  97. package/dist/kit/core/run.d.ts.map +1 -1
  98. package/dist/kit/core/run.js +497 -79
  99. package/dist/kit/core/run.js.map +1 -1
  100. package/dist/kit/core/save.d.ts +7 -3
  101. package/dist/kit/core/save.d.ts.map +1 -1
  102. package/dist/kit/core/save.js +57 -20
  103. package/dist/kit/core/save.js.map +1 -1
  104. package/dist/kit/core/style.js +1 -1
  105. package/dist/kit/core/style.js.map +1 -1
  106. package/dist/kit/line/client.d.ts +14 -2
  107. package/dist/kit/line/client.d.ts.map +1 -1
  108. package/dist/kit/line/client.js +40 -20
  109. package/dist/kit/line/client.js.map +1 -1
  110. package/dist/kit/line/types.d.ts +33 -1
  111. package/dist/kit/line/types.d.ts.map +1 -1
  112. package/dist/kit/maker/inputs.js +1 -1
  113. package/dist/kit/maker/make.d.ts.map +1 -1
  114. package/dist/kit/maker/make.js +4 -2
  115. package/dist/kit/maker/make.js.map +1 -1
  116. package/dist/kit/maker/parts/html-frames/{1.2.0 → 1.2.1}/part.json +1 -1
  117. package/dist/kit/parts/catalog.d.ts +3 -20
  118. package/dist/kit/parts/catalog.d.ts.map +1 -1
  119. package/dist/kit/parts/catalog.js +6 -41
  120. package/dist/kit/parts/catalog.js.map +1 -1
  121. package/dist/kit/parts/loader.d.ts +7 -2
  122. package/dist/kit/parts/loader.d.ts.map +1 -1
  123. package/dist/kit/parts/loader.js +88 -23
  124. package/dist/kit/parts/loader.js.map +1 -1
  125. package/dist/skills/master-skill.d.ts +1 -3
  126. package/dist/skills/master-skill.d.ts.map +1 -1
  127. package/dist/skills/master-skill.js +12 -14
  128. package/dist/skills/master-skill.js.map +1 -1
  129. package/dist/skills/routes.js +4 -4
  130. package/dist/skills/routes.js.map +1 -1
  131. package/dist/skills/server-entry-skills.d.ts +6 -6
  132. package/dist/skills/server-entry-skills.js +15 -15
  133. package/dist/skills/server-entry-skills.js.map +1 -1
  134. package/dist/utils/browser-preflight.d.ts +3 -0
  135. package/dist/utils/browser-preflight.d.ts.map +1 -1
  136. package/dist/utils/browser-preflight.js +27 -6
  137. package/dist/utils/browser-preflight.js.map +1 -1
  138. package/dist/utils/exit.d.ts +6 -0
  139. package/dist/utils/exit.d.ts.map +1 -0
  140. package/dist/utils/exit.js +37 -0
  141. package/dist/utils/exit.js.map +1 -0
  142. package/package.json +13 -2
  143. package/skills/goose-ads/SKILL.md +3 -3
  144. package/skills/goose-product-photos/SKILL.md +3 -3
  145. package/skills/goose-video/SKILL.md +5 -5
  146. package/skills/goose-video-local/SKILL.md +3 -3
  147. package/skills/gooseworks/SKILL.md +6 -8
  148. package/skills/make-custom-video/SKILL.md +2 -2
  149. package/skills/manifest.json +7 -7
  150. package/skills/routes.json +3 -3
@@ -33,8 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.LAYER_ORDER = void 0;
36
+ exports.CEILING_WORDS = exports.RUN_CEILING_MIN_MS = exports.RUN_CEILING_MAX_MS = exports.LAYER_ORDER = void 0;
37
37
  exports.expectationOf = expectationOf;
38
+ exports.startLine = startLine;
38
39
  exports.makeVideo = makeVideo;
39
40
  // `gooseworks video make <id>`, in order (part-interface.md section 8):
40
41
  // 1. the hand-over (token, frozen plan, parts lock, style package);
@@ -55,10 +56,14 @@ const path = __importStar(require("path"));
55
56
  const client_1 = require("../line/client");
56
57
  const types_1 = require("../line/types");
57
58
  const bind_1 = require("./bind");
59
+ const eyes_1 = require("./eyes");
60
+ const outcome_1 = require("./outcome");
58
61
  const canonical_1 = require("./canonical");
59
62
  const device_1 = require("./device");
60
63
  const errors_1 = require("./errors");
61
64
  const files_1 = require("./files");
65
+ const lock_1 = require("./lock");
66
+ const patch_1 = require("./patch");
62
67
  const paths_1 = require("./paths");
63
68
  const pieces_1 = require("./pieces");
64
69
  const plain_words_1 = require("./plain-words");
@@ -66,12 +71,14 @@ const progress_1 = require("./progress");
66
71
  const progress_reporter_1 = require("./progress-reporter");
67
72
  const save_1 = require("./save");
68
73
  const schema_1 = require("./schema");
74
+ const refusal_log_1 = require("./refusal-log");
69
75
  const secrets_1 = require("./secrets");
70
76
  const style_1 = require("./style");
71
77
  const toolchain_1 = require("./toolchain");
72
78
  const loader_1 = require("../parts/loader");
73
79
  const env_1 = require("../env");
74
80
  const version_1 = require("./version");
81
+ const version_2 = require("../../version");
75
82
  exports.LAYER_ORDER = ['brand', 'captions', 'sound', 'check'];
76
83
  const SLOT_KIND = { brand: 'compose', captions: 'caption', sound: 'mix', check: 'check' };
77
84
  /** The server's checks a layer can redo. */
@@ -83,33 +90,99 @@ const ASPECT_SIZE = {
83
90
  '4:5': { width: 1080, height: 1350 },
84
91
  '16:9': { width: 1920, height: 1080 },
85
92
  };
93
+ /** The longest one run may take, whatever its parts: past it the run stops and the same command carries on. */
94
+ exports.RUN_CEILING_MAX_MS = 60 * 60_000;
95
+ /** The shortest ceiling, so a style of quick parts still has room for a slow provider. */
96
+ exports.RUN_CEILING_MIN_MS = 20 * 60_000;
97
+ /** A run may take this many times its parts' typical time before it is cut short. */
98
+ const CEILING_FACTOR = 4;
99
+ /** After the last word's deadline, how long the process may still take to end on its own. */
100
+ const EXIT_GRACE_MS = 5_000;
101
+ /** Whatever the last word's deadline, the process ends this soon after the run does. */
102
+ const EXIT_WITHIN_MS = 30_000;
103
+ /** The person's words when the run reached its ceiling. */
104
+ exports.CEILING_WORDS = 'Making this video took much longer than it should, so this run stopped. Run the same command again; what was made so far is kept.';
86
105
  const CHECK_FAILED = 'The video didn’t pass the final check.';
87
106
  /** For a failure that repeats on every run of the same plan. */
88
107
  const PLAN_FIX = 'Change the plan, then make it again.';
108
+ /** For a failure a new run of the same command may get past. */
109
+ const RUN_AGAIN = 'Run the same command again; what was made so far is kept.';
89
110
  const PLAN_CHANGE = `This video can’t be made from this plan. ${PLAN_FIX}`;
90
111
  /** The server's `failure.code` shape. */
91
112
  const FAILURE_CODE = /^[a-z][a-z0-9_]{0,39}$/;
92
- /** Codes the server keeps the video in Making for (gooseworks-app video-line/run-failure.ts RESUMABLE_CODES). */
93
- const RESUMABLE_CODES = new Set(['timeout', 'tool_failed', 'needs_missing']);
113
+ /** Codes the line blames on the plan only when a part refused it (`from_part`), not when the kit's own check did. */
114
+ const PLAN_CODES = new Set(['bad_input', 'output_invalid']);
115
+ /** Stops the person chose: Ctrl-C here, or Stop on the card (the line's refusal). They need no support. */
116
+ const OWN_STOPS = new Set(['stopped_here', 'video_stopped']);
117
+ /**
118
+ * Stops on this computer's side or ours that the line must hear, or the video waits in Making until it
119
+ * goes quiet. This computer's own trouble goes as `tool_failed`, which never counts against us; the
120
+ * rest keep their code, so the line alerts us. Stale-plan and the line's own refusals are left out.
121
+ */
122
+ const REPORTED_STOPS = new Map([
123
+ ['stopped_here', 'stopped_here'],
124
+ ['unreachable', 'tool_failed'],
125
+ ['bad_cache', 'tool_failed'],
126
+ ['style_unreachable', 'tool_failed'],
127
+ ['parts_not_ready', 'parts_not_ready'],
128
+ ['price_unavailable', 'price_unavailable'],
129
+ ['file_unavailable', 'file_unavailable'],
130
+ ['piece_lost', 'piece_lost'],
131
+ ]);
132
+ /** At most this many warnings go up with the video, for its delivery summary. */
133
+ const MAX_SENT_WARNINGS = 6;
134
+ /** What the final check noted without failing the video, in its own words. */
135
+ function verdictWarnings(verdict) {
136
+ const warned = [];
137
+ for (const check of verdict.checks) {
138
+ if (check.status === 'warn' && typeof check.message === 'string' && check.message.trim())
139
+ warned.push({ check: check.code, message: check.message.trim() });
140
+ }
141
+ return warned;
142
+ }
143
+ /** The finished video and its captions while our server checks them; final.mp4 only once it passes. */
144
+ const CANDIDATE = 'final.candidate.mp4';
145
+ const CANDIDATE_CAPTIONS = 'captions.candidate.vtt';
146
+ /** A step ran out of time while a piece it ordered was still being made at the maker. */
147
+ const PROVIDER_SLOW = 'provider_slow';
148
+ /**
149
+ * The person's words for a piece the maker didn't send back in time, by the step's row (the server's
150
+ * nouns). Whether it was charged is the server's to say: the piece may still finish after the step gave up.
151
+ */
152
+ function slowWords(row) {
153
+ const what = row === 'voice' ? 'One of the voice lines' : row === 'pictures' ? 'One of the pictures' : row === 'clips' || row === 'lips' ? 'One of the clips' : row === 'music' ? 'The music' : 'One of the parts';
154
+ return `${what} we ordered for this video didn’t come back in time. ${RUN_AGAIN}`;
155
+ }
156
+ /** The line refused the hand-over because this computer has no video browser yet. */
157
+ function missingBrowser(error) {
158
+ const missing = error.details?.missing;
159
+ return Array.isArray(missing) && missing.includes('browser');
160
+ }
161
+ /** An older line refused the hand-over's `setup` claim as a field it doesn't know. */
162
+ function namesSetup(error) {
163
+ if (error.status !== 400)
164
+ return false;
165
+ const fields = Array.isArray(error.details?.fields) ? error.details.fields : [];
166
+ if (fields.some((f) => typeof f === 'string' && /(^|\.)setup$/.test(f)))
167
+ return true;
168
+ return /\bsetup\b/.test(`${error.fix} ${error.message}`);
169
+ }
94
170
  /** A part that would not load, in plain words: which part and why go to the log. */
95
171
  function loadStop(error) {
96
172
  const code = error instanceof loader_1.PartLoadError ? error.code : undefined;
97
173
  switch (code) {
98
174
  case 'kit_range':
99
- return new errors_1.KitStop('This video needs a newer video kit. Nothing was spent.', 'update_kit', code);
175
+ return new errors_1.KitStop('This video needs a newer video kit.', 'update_kit', code);
100
176
  case 'unreachable':
101
- return new errors_1.KitStop('This video’s parts could not be downloaded right now. Run the same command again in a minute. Nothing was spent.', 'stop', code);
177
+ return new errors_1.KitStop('This video’s parts could not be downloaded right now. Run the same command again in a minute.', 'stop', code);
102
178
  case 'bad_cache':
103
- return new errors_1.KitStop('The video kit’s folder on this computer is busy or can’t be used. Run the same command again in a minute. Nothing was spent.', 'stop', code);
179
+ return new errors_1.KitStop('The video kit’s folder on this computer is busy or can’t be used. Run the same command again in a minute.', 'stop', code);
104
180
  case 'withdrawn':
105
- return new errors_1.KitStop(`A part this video uses was withdrawn. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', code);
181
+ return new errors_1.KitStop(`A part this video uses was withdrawn. ${PLAN_CHANGE}`, 'change_request', code);
106
182
  default:
107
- return new errors_1.KitStop(`A part this video uses can’t run. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', code);
183
+ return new errors_1.KitStop(`A part this video uses can’t run. ${PLAN_CHANGE}`, 'change_request', code);
108
184
  }
109
185
  }
110
- function lineWords(error) {
111
- return [error.message, error.fix].filter(Boolean).join(' ');
112
- }
113
186
  /**
114
187
  * The code the line hears for a step's last failure. A provider failure a later run can get past
115
188
  * (its piece has an attempt left, or no piece is named) is reported as `tool_failed`, which keeps
@@ -136,7 +209,7 @@ function failureWords(error, names = []) {
136
209
  if (error instanceof pieces_1.PieceFailure && error.spent)
137
210
  return pieces_1.FAILED_TWICE;
138
211
  if (error instanceof pieces_1.PieceFailure)
139
- return [error.line.error, error.line.fix].filter(Boolean).join(' ');
212
+ return pieceWords(error);
140
213
  switch (error.code) {
141
214
  case 'provider_rejected':
142
215
  return 'One part of this video was refused by the maker. Change that scene in the plan, then make it again.';
@@ -153,6 +226,11 @@ function failureWords(error, names = []) {
153
226
  return 'Part of this video could not be made. Run the same command again; what was made so far is kept.';
154
227
  }
155
228
  }
229
+ /** A failed piece in the server's words: its sentence for the person, else its error and fix. The money and the next step are the server's to say. */
230
+ function pieceWords(error) {
231
+ const { line } = error;
232
+ return line.say?.trim() || [line.error, line.fix].filter(Boolean).join(' ');
233
+ }
156
234
  /** A part's refusal first, then what to do, within the card's length; the generic words when it has none. */
157
235
  function refusalWords(error, names) {
158
236
  if (!error.fromPart || !error.detail)
@@ -164,10 +242,10 @@ function refusalWords(error, names) {
164
242
  function checkLock(raw, videoId, plan) {
165
243
  const lock = raw;
166
244
  if (!lock || lock.lock !== 1 || lock.video_id !== videoId || !lock.parts || !lock.layers || !lock.style) {
167
- throw new errors_1.KitStop('This video’s parts list can’t be read. Nothing was spent.', 'change_request');
245
+ throw new errors_1.KitStop('This video’s parts list can’t be read.', 'change_request');
168
246
  }
169
247
  if (lock.style.id !== plan.style_id || lock.style.version !== plan.style_version)
170
- throw new errors_1.KitStop('This video’s parts list is for another style. Nothing was spent.', 'change_request');
248
+ throw new errors_1.KitStop('This video’s parts list is for another style.', 'change_request');
171
249
  return lock;
172
250
  }
173
251
  /** What the finished video must be, handed to every layer as `expect`. Exported for tests. */
@@ -189,6 +267,8 @@ function expectationOf(style, plan) {
189
267
  qc_flags: Array.isArray(style.traits?.qc_flags) ? style.traits.qc_flags : [],
190
268
  ...(script.length ? { script } : {}),
191
269
  ...(captionLook ? { caption_look: captionLook } : {}),
270
+ // So the check layer holds loudness to the sound layer's mark only when that layer ran.
271
+ layers: { brand: style.layers?.brand === true, captions: style.layers?.captions === true, sound: style.layers?.sound === true, check: true },
192
272
  };
193
273
  }
194
274
  /** The style's caption look, copied as written when it is an object; the captions layer checks its fields. */
@@ -221,7 +301,8 @@ class Maker {
221
301
  now;
222
302
  stop = new AbortController();
223
303
  fatal = null;
224
- book = new progress_1.ProgressBook();
304
+ stepLines = new progress_1.StepLines();
305
+ book = new progress_1.ProgressBook(() => this.printSteps());
225
306
  reporter;
226
307
  store;
227
308
  layout;
@@ -232,6 +313,8 @@ class Maker {
232
313
  browserReady = false;
233
314
  handed;
234
315
  lock = null;
316
+ /** The edited steps this run makes the video with, sent with every hand-over. */
317
+ patch = null;
235
318
  style;
236
319
  planScope;
237
320
  brand;
@@ -240,45 +323,136 @@ class Maker {
240
323
  pieceLocks = new Map();
241
324
  /** Where the run is, for the failure report: a step id or a stage before or after the steps. */
242
325
  at = 'hand-over';
326
+ /** This run's name: its log file and its keys in the order journal. */
327
+ runId = '';
243
328
  failureSent = false;
329
+ /** The run ended on a stop the person chose (Ctrl-C, or Stop on the card), which needs no support. */
330
+ ownStop = false;
331
+ ceilingTimer = null;
332
+ ceilingFrom = 0;
333
+ exitTimer = null;
334
+ progressSaved = Promise.resolve();
335
+ /** How the run ended, once it has: what a forced end reports. */
336
+ result = null;
244
337
  constructor(videoId, deps) {
245
338
  this.videoId = videoId;
246
339
  this.deps = deps;
247
340
  this.sleep = deps.sleep ?? client_1.sleep;
248
341
  this.now = deps.now ?? (() => new Date());
249
- deps.signal?.addEventListener('abort', () => this.halt(new errors_1.KitStop('Stopped on this computer. Run the same command to carry on.', 'stop')), { once: true });
342
+ deps.signal?.addEventListener('abort', () => this.halt(new errors_1.KitStop('Stopped on this computer. Run the same command to carry on.', 'stop', 'stopped_here')), { once: true });
250
343
  }
251
344
  halt(stop) {
252
345
  this.fatal ??= stop;
253
346
  if (!this.stop.signal.aborted)
254
347
  this.stop.abort(stop);
348
+ this.armExit();
349
+ }
350
+ /**
351
+ * The run is over, however it ended: whatever still listens to its stop signal (a piece being asked
352
+ * about, a download, a browser) stops too, and the process gets to end within the last word's deadline.
353
+ */
354
+ endRun() {
355
+ if (this.ceilingTimer)
356
+ clearTimeout(this.ceilingTimer);
357
+ this.ceilingTimer = null;
358
+ if (!this.stop.signal.aborted)
359
+ this.stop.abort(new errors_1.KitStop('This run is over.', 'stop'));
360
+ this.armExit();
361
+ }
362
+ /** Once the run has stopped, the command ends the process if the run hasn't returned by the last word's deadline. */
363
+ armExit() {
364
+ if (this.exitTimer || !this.deps.forceEnd)
365
+ return;
366
+ const end = this.deps.forceEnd;
367
+ this.exitTimer = setTimeout(() => {
368
+ this.deps.log.write('error', 'the run did not end on its own, so the process ends now', { step: this.at });
369
+ if (this.result)
370
+ return end(this.result);
371
+ const stop = this.fatal;
372
+ const message = stop?.message ?? 'This video could not be made right now. Run the same command again; what was made so far is kept.';
373
+ end(stop?.reason === 'update_kit' ? { status: 'update_kit', message, code: stop.code } : { status: stop?.reason === 'stop' ? 'stopped' : 'failed', message, code: stop?.code ?? 'tool_failed' });
374
+ }, Math.min((this.deps.lastWordMs ?? progress_reporter_1.LAST_WORD_MS) + EXIT_GRACE_MS, EXIT_WITHIN_MS));
375
+ this.exitTimer.unref?.();
376
+ }
377
+ /** From now on this run may take `ms` in all (counted from the first arming); past it, it stops and can carry on. */
378
+ armCeiling(ms) {
379
+ if (this.stop.signal.aborted)
380
+ return;
381
+ if (this.ceilingTimer)
382
+ clearTimeout(this.ceilingTimer);
383
+ this.ceilingFrom ||= Date.now();
384
+ const left = Math.max(this.ceilingFrom + ms - Date.now(), 0);
385
+ this.ceilingTimer = setTimeout(() => {
386
+ this.ceilingTimer = null;
387
+ this.deps.log.write('warn', 'the run reached its time limit', { step: this.at, minutes: Math.round(ms / 60_000) });
388
+ this.halt(new errors_1.KitStop(exports.CEILING_WORDS, 'failed', 'timeout'));
389
+ }, left);
390
+ this.ceilingTimer.unref?.();
391
+ }
392
+ /** The run's ceiling from its parts' typical times; a fixed one from the deps wins. */
393
+ ceilingFor() {
394
+ if (this.deps.ceilingMs)
395
+ return this.deps.ceilingMs;
396
+ let typical = 0;
397
+ for (const loaded of this.parts.values())
398
+ typical += Math.max(loaded.manifest.timing?.typical_s ?? 0, 0);
399
+ return Math.min(Math.max(typical * 1000 * CEILING_FACTOR, exports.RUN_CEILING_MIN_MS), exports.RUN_CEILING_MAX_MS);
255
400
  }
256
401
  say(line) {
257
402
  this.deps.log.say(line);
258
403
  }
259
404
  async make() {
405
+ try {
406
+ return await this.makeOnce();
407
+ }
408
+ finally {
409
+ this.endRun();
410
+ if (this.exitTimer)
411
+ clearTimeout(this.exitTimer);
412
+ }
413
+ }
414
+ async makeOnce() {
260
415
  const { deps } = this;
261
416
  let dev;
262
417
  try {
263
418
  dev = this.devFolders();
419
+ if (deps.patched?.length)
420
+ this.patch = await this.readPatch(dev);
264
421
  }
265
422
  catch (error) {
266
423
  return this.ended(error);
267
424
  }
425
+ // The lock comes before the hand-over: a second command for the same video must not take the
426
+ // line's lease from the run already making it.
427
+ // The ceiling counts from here (after the account check), so a slow or stuck setup is bounded too;
428
+ // it is tightened, from the same start, once the parts' timing is known.
429
+ this.armCeiling(deps.ceilingMs ?? exports.RUN_CEILING_MAX_MS);
430
+ this.layout = (0, paths_1.runLayout)(deps.home, this.videoId);
431
+ const release = await (0, save_1.takeRunLock)(this.layout, this.now());
432
+ try {
433
+ return await this.makeLocked(dev);
434
+ }
435
+ finally {
436
+ await release();
437
+ }
438
+ }
439
+ async makeLocked(dev) {
440
+ const { deps } = this;
441
+ // Every hand-over needs the video tools, so they are set up first. Without the browser yet, the
442
+ // hand-over is a claim, so the card shows the video started while a first run downloads it.
268
443
  this.tools = deps.tools ?? (await (0, toolchain_1.inspectFfmpeg)({ home: deps.home, env: deps.env, setup: true, download: (u, m) => deps.line.download(u, m), say: (l) => this.say(l) }));
269
- const browser = await deps.host.browser.check({ home: deps.home, setup: true, env: deps.env, say: (l) => this.say(l) });
270
- this.browserReady = browser.ok;
271
- this.toolchain = (0, toolchain_1.toolchainId)(this.tools, browser.ok ? browser.version : null);
272
- const report = await (0, device_1.deviceReport)({ home: deps.home, worker: deps.line.isWorker, tools: this.tools, browser });
444
+ let browser = await this.checkBrowser(false);
273
445
  let answer;
446
+ let claimed;
274
447
  try {
275
- answer = await deps.line.handOver(this.videoId, report);
448
+ ({ answer, browser, claimed } = await this.handOverFirst(browser));
276
449
  }
277
450
  catch (error) {
278
451
  if (error instanceof client_1.LineError) {
452
+ (0, refusal_log_1.recordRefusal)(deps.home, this.videoId, 'hand-over refused', error);
279
453
  if (error.next === 'update_kit')
280
- return { status: 'update_kit', message: lineWords(error) };
281
- return { status: 'stopped', message: lineWords(error) };
454
+ return { status: 'update_kit', message: (0, client_1.lineWords)(error), code: error.code, next: error.next };
455
+ return { status: 'stopped', message: (0, client_1.lineWords)(error), code: error.code, next: error.next };
282
456
  }
283
457
  throw error;
284
458
  }
@@ -287,34 +461,156 @@ class Maker {
287
461
  if (!answer.line)
288
462
  return { status: 'stopped', message: 'This video can’t be made on this computer right now.' };
289
463
  this.handed = answer.line;
290
- this.layout = (0, paths_1.runLayout)(deps.home, this.videoId);
291
- const release = await (0, save_1.takeRunLock)(this.layout, this.now());
292
- // From here on the lock is always given back, whatever fails.
464
+ let runLog = null;
465
+ let result = null;
466
+ // From here on the pending report is always kept, whatever fails.
293
467
  try {
294
- deps.log.attach(this.layout.log);
295
- deps.log.write('info', 'video handed over', { quote_id: this.handed.quote_id, stage: this.handed.stage, kit: version_1.KIT_VERSION });
468
+ const run = deps.log.attachRun({
469
+ index: this.layout.log,
470
+ dir: this.layout.runs,
471
+ name: (0, paths_1.runName)(this.now(), this.handed.quote_id),
472
+ packageVersion: (0, version_2.getVersion)(),
473
+ fields: { quote_id: this.handed.quote_id },
474
+ });
475
+ this.runId = run.run;
476
+ runLog = run.file;
477
+ const video = answer.line.video ?? answer.video;
478
+ deps.log.write('info', 'video handed over', { quote_id: this.handed.quote_id, stage: this.handed.stage, kit: version_1.KIT_VERSION, video: video ?? null, setup_claimed: claimed });
479
+ this.say(startLine(video, deps.environment));
296
480
  this.store = new save_1.RunStore(this.layout);
297
481
  this.cache = new pieces_1.PieceCache(this.layout.pieces);
298
- this.reporter = new progress_reporter_1.ProgressReporter(deps.line, this.videoId, this.book, deps.log, (message, reason, code) => this.halt(new errors_1.KitStop(message, reason, code)), deps.heartbeatMs, this.stop.signal);
482
+ this.reporter = new progress_reporter_1.ProgressReporter(deps.line, this.videoId, this.book, deps.log, (message, reason, code, next) => this.halt(new errors_1.KitStop(message, reason, code, next)), deps.heartbeatMs, this.stop.signal, deps.lastWordMs);
483
+ this.useBrowser(browser);
299
484
  const replayed = await this.replayPending();
300
485
  if (replayed)
301
- return replayed;
486
+ return (result = replayed);
302
487
  if (this.fatal)
303
488
  throw this.fatal;
304
489
  // Reports start now, so checking the style and parts never looks quiet.
305
490
  this.reporter.start();
306
- void this.reporter.send(true);
307
- return await this.makeHandedOver(dev);
491
+ if (browser.ok)
492
+ void this.reporter.send(true);
493
+ else
494
+ await this.setUpBrowser(claimed);
495
+ return (result = await this.makeHandedOver(dev));
308
496
  }
309
497
  catch (error) {
310
- return await this.ended(error);
498
+ return (result = await this.ended(error));
311
499
  }
312
500
  finally {
313
- this.reporter?.stopTimer();
501
+ this.reporter?.close();
502
+ if (result && runLog)
503
+ result.log = runLog;
504
+ this.result = result ?? null;
505
+ this.endRun();
314
506
  await this.reporter?.flush().catch(() => undefined);
315
507
  await this.keepPendingReport().catch((error) => deps.log.write('warn', 'the failure report could not be saved', { error: error instanceof Error ? error.message : String(error) }));
316
- await release();
508
+ // The lock is released by makeOnce, after this.
509
+ await this.progressSaved;
510
+ // Support reads what happened in this run's own log.
511
+ if (runLog && (result?.status === 'failed' || (result?.status === 'stopped' && !this.ownStop)))
512
+ this.say(`If you contact support, share this file: ${runLog}`);
513
+ }
514
+ }
515
+ /** Each change of the card's rows, as a line for the person running the kit. */
516
+ printSteps() {
517
+ const request = this.book.request();
518
+ const rows = this.stepLines.changed(request.steps, this.now().getTime());
519
+ for (const row of rows)
520
+ this.deps.log.step(row, (0, progress_1.lineOf)(row));
521
+ if (rows.length && this.layout)
522
+ this.saveProgress(request.note, request.steps ?? []);
523
+ }
524
+ /** The rows as shown, for `video status`; saved one after another, and never at the run's cost. */
525
+ saveProgress(note, steps) {
526
+ const record = { note, steps, at: this.now().toISOString() };
527
+ const target = this.layout.progress;
528
+ this.progressSaved = this.progressSaved.then(() => (0, save_1.writeJson)(target, record)).catch(() => undefined);
529
+ }
530
+ checkBrowser(setup) {
531
+ return this.deps.host.browser.check({ home: this.deps.home, setup, env: this.deps.env, say: (l) => this.say(l) });
532
+ }
533
+ useBrowser(browser) {
534
+ this.browserReady = browser.ok;
535
+ this.toolchain = (0, toolchain_1.toolchainId)(this.tools, browser.ok ? browser.version : null);
536
+ }
537
+ /**
538
+ * The hand-over. Without the browser it is first a claim (`setup: in_progress`), which an older
539
+ * line refuses as an unknown field: it then hands over on the full report as before, setting up
540
+ * the browser first only when the line won't hand over without it. A worker never claims.
541
+ */
542
+ async handOverFirst(browser) {
543
+ const { line } = this.deps;
544
+ if (!browser.ok && !line.isWorker) {
545
+ try {
546
+ return { answer: await line.handOver(this.videoId, { ...(await this.report(browser)), setup: 'in_progress' }, this.patch), browser, claimed: true };
547
+ }
548
+ catch (error) {
549
+ if (!(error instanceof client_1.LineError && namesSetup(error)))
550
+ throw error;
551
+ this.deps.log.write('info', 'the line does not take a hand-over before setup', { code: error.code });
552
+ }
553
+ }
554
+ try {
555
+ return { answer: await line.handOver(this.videoId, await this.report(browser), this.patch), browser, claimed: false };
317
556
  }
557
+ catch (error) {
558
+ if (!(error instanceof client_1.LineError && error.code === 'device_cannot_make' && !browser.ok && missingBrowser(error)))
559
+ throw error;
560
+ const ready = await this.checkBrowser(true);
561
+ return { answer: await line.handOver(this.videoId, await this.report(ready), this.patch), browser: ready, claimed: false };
562
+ }
563
+ }
564
+ /**
565
+ * A first run's browser download, after the hand-over: the card hears from the kit all the while.
566
+ * Then the full report goes to the line, which still holds a claim or a report without the browser.
567
+ */
568
+ async setUpBrowser(claimed) {
569
+ const note = this.book.note;
570
+ this.book.note = 'Setting up your computer for the video';
571
+ void this.reporter.send(true);
572
+ const browser = await this.checkBrowser(true);
573
+ this.useBrowser(browser);
574
+ if (this.fatal)
575
+ throw this.fatal;
576
+ if (claimed || (browser.ok && !this.deps.line.isWorker))
577
+ await this.confirmHandOver(browser, claimed);
578
+ this.book.note = note;
579
+ if (this.fatal)
580
+ throw this.fatal;
581
+ void this.reporter.send(true);
582
+ }
583
+ /**
584
+ * The full report as a second hand-over, so the line checks what this computer can make and keeps
585
+ * it. A claim must be confirmed: the line checked nothing for it. A report that only adds the browser may fail.
586
+ */
587
+ async confirmHandOver(browser, claimed) {
588
+ // The new hand-over gives the run a new lease, so no report may be on its way under the old one.
589
+ this.reporter.pause();
590
+ try {
591
+ await this.reporter.flush();
592
+ const answer = await this.deps.line.handOver(this.videoId, await this.report(browser), this.patch);
593
+ if (!answer.kit.ok)
594
+ throw new errors_1.KitStop('This video kit is too old for this video.', 'update_kit');
595
+ if (answer.line?.quote_id !== this.handed.quote_id)
596
+ throw new errors_1.KitStop('The plan for this video changed after this run started. Run the make command again to make the current plan.', 'stop', 'plan_changed');
597
+ this.handed = answer.line;
598
+ }
599
+ catch (error) {
600
+ if (error instanceof errors_1.KitStop)
601
+ throw error;
602
+ if (error instanceof client_1.LineError && (claimed || error.code === 'device_cannot_make'))
603
+ throw (0, errors_1.lineStop)((0, client_1.lineWords)(error), error.next, error.code);
604
+ if (claimed)
605
+ throw error;
606
+ this.deps.log.write('warn', 'the report with the browser could not be sent', { error: error instanceof Error ? error.message : String(error) });
607
+ }
608
+ finally {
609
+ this.reporter.resume();
610
+ }
611
+ }
612
+ report(browser) {
613
+ return (0, device_1.deviceReport)({ home: this.deps.home, worker: this.deps.line.isWorker, tools: this.tools, browser });
318
614
  }
319
615
  reportKey() {
320
616
  try {
@@ -344,7 +640,7 @@ class Maker {
344
640
  !!saved.failure &&
345
641
  typeof saved.failure.code === 'string' &&
346
642
  typeof saved.failure.detail === 'string' &&
347
- !RESUMABLE_CODES.has(saved.failure.code) &&
643
+ !outcome_1.RESUMABLE_CODES.has(saved.failure.code) &&
348
644
  !!key &&
349
645
  Object.keys(key).every((field) => saved[field] === key[field]);
350
646
  if (!stands) {
@@ -360,7 +656,7 @@ class Maker {
360
656
  if (sent === 'refused')
361
657
  return null;
362
658
  this.failureSent = true;
363
- return { status: 'failed', message: saved.failure.detail };
659
+ return { status: 'failed', message: saved.failure.detail, code: saved.failure.code };
364
660
  }
365
661
  /** Keeps a failure report the line never took for the next run; one taken, or a finished video, clears it. */
366
662
  async keepPendingReport() {
@@ -377,6 +673,16 @@ class Maker {
377
673
  await (0, promises_1.rm)(this.layout.pendingReport, { force: true });
378
674
  }
379
675
  }
676
+ /** The edits named on the command, read before the hand-over that carries them. */
677
+ async readPatch(dev) {
678
+ if (dev.parts)
679
+ throw new errors_1.KitStop(`An edited step runs from the published parts; unset ${env_1.KIT_DEV_ENV.partsDir} to make the video with it.`, 'refused');
680
+ if (this.deps.line.isWorker)
681
+ throw new errors_1.KitStop('An edited step is made on the computer it was edited on.', 'refused');
682
+ const patch = await (0, patch_1.readPatch)((0, paths_1.runLayout)(this.deps.home, this.videoId), this.deps.patched ?? []);
683
+ this.deps.log.write('info', 'making with edited steps', { patch_sha256: patch.sha256, steps: patch.steps.map((s) => ({ step: s.step, part: `${s.part.id}@${s.part.version}`, files: s.files.map((f) => f.path) })) });
684
+ return patch;
685
+ }
380
686
  devFolders() {
381
687
  const parts = this.deps.env[env_1.KIT_DEV_ENV.partsDir] || null;
382
688
  const styles = this.deps.env[env_1.KIT_DEV_ENV.stylesDir] || null;
@@ -386,35 +692,41 @@ class Maker {
386
692
  return { parts, styles };
387
693
  }
388
694
  async ended(error) {
695
+ // Nothing but the failure report goes out from here.
696
+ this.reporter?.close();
389
697
  const stop = this.fatal ?? (error instanceof errors_1.KitStop ? error : null);
698
+ this.endRun();
699
+ this.ownStop = stop?.reason === 'stop' && OWN_STOPS.has(stop.code ?? '');
390
700
  if (stop)
391
701
  this.deps.log.write('warn', 'the run stopped', { reason: stop.reason, code: stop.code ?? null, message: stop.message });
392
702
  if (this.run) {
393
703
  this.run.status = stop && stop.reason === 'stop' ? 'stopped' : 'failed';
394
704
  await this.saveRun().catch(() => undefined);
395
705
  }
396
- if (stop && (stop.reason === 'failed' || stop.reason === 'change_request' || stop.reason === 'refused')) {
397
- this.reportFailure(this.at, stop.code ?? 'change_request', stop.message);
706
+ const reported = !stop || stop.reason === 'update_kit' ? undefined : stop.reason === 'stop' ? REPORTED_STOPS.get(stop.code ?? '') : (stop.code ?? 'change_request');
707
+ if (stop && reported) {
708
+ this.reportFailure(this.at, reported, stop.message);
398
709
  await this.reporter?.flush().catch(() => undefined);
399
710
  }
400
711
  if (stop) {
712
+ const code = stop.code ?? (stop.reason === 'stop' ? undefined : 'change_request');
401
713
  if (stop.reason === 'update_kit')
402
- return { status: 'update_kit', message: stop.message };
403
- return { status: stop.reason === 'stop' ? 'stopped' : 'failed', message: stop.message };
714
+ return { status: 'update_kit', message: stop.message, ...(code ? { code } : {}) };
715
+ return { status: stop.reason === 'stop' ? 'stopped' : 'failed', message: stop.message, ...(code ? { code } : {}), ...(stop.next ? { next: stop.next } : {}) };
404
716
  }
405
717
  this.deps.log.write('error', 'the run ended on an error', { step: this.at, error: error instanceof Error ? error.message : String(error) });
406
718
  const message = 'This video could not be made right now. Run the same command again; what was made so far is kept.';
407
719
  // Not a step's failure (a download or a disk write, say): a new run may get past it.
408
720
  this.reportFailure(this.at, 'tool_failed', message);
409
721
  await this.reporter?.flush().catch(() => undefined);
410
- return { status: 'failed', message };
722
+ return { status: 'failed', message, code: 'tool_failed' };
411
723
  }
412
724
  /** Tells the line once why the run gave up; the line's own refusals already ended it on its words. */
413
- reportFailure(step, code, detail) {
725
+ reportFailure(step, code, detail, fromPart) {
414
726
  if (!this.reporter || this.failureSent || this.reporter.refused)
415
727
  return;
416
728
  this.failureSent = true;
417
- void this.reporter.fail({ step: step.slice(0, 60), code: FAILURE_CODE.test(code) ? code : 'change_request', detail: detail.trim().slice(0, 2000) });
729
+ void this.reporter.fail({ step: step.slice(0, 60), code: FAILURE_CODE.test(code) ? code : 'change_request', detail: detail.trim().slice(0, 2000), ...(fromPart === undefined ? {} : { from_part: fromPart }) });
418
730
  }
419
731
  async saveRun() {
420
732
  this.run.updated_at = this.now().toISOString();
@@ -423,14 +735,19 @@ class Maker {
423
735
  async makeHandedOver(dev) {
424
736
  const { deps, handed } = this;
425
737
  const plan = handed.plan;
738
+ // Until the parts say how long they take, the run may take the longest any run may.
739
+ this.armCeiling(deps.ceilingMs ?? exports.RUN_CEILING_MAX_MS);
426
740
  this.at = 'plan';
427
741
  if (!plan || plan.project_id !== this.videoId || plan.style_id !== handed.style_package?.style_id || plan.style_version !== handed.style_package?.version) {
428
- throw new errors_1.KitStop('The plan handed over is not this video’s. Nothing was spent.', 'change_request');
742
+ throw new errors_1.KitStop('The plan handed over is not this video’s.', 'change_request');
429
743
  }
430
744
  if (handed.parts_lock)
431
745
  this.lock = checkLock(handed.parts_lock, this.videoId, plan);
432
746
  else if (!dev.parts)
433
- throw new errors_1.KitStop('This video’s parts are not ready yet. Run the same command again in a few minutes. Nothing was spent.', 'stop');
747
+ throw new errors_1.KitStop('This video’s parts are not ready yet. Run the same command again in a few minutes.', 'stop', 'parts_not_ready');
748
+ const patchProblem = this.patch && this.lock ? (0, patch_1.patchLockProblem)(this.patch, this.lock) : null;
749
+ if (patchProblem)
750
+ throw new errors_1.KitStop(`${patchProblem}`, 'stop', 'patch_refused');
434
751
  const planCopy = (0, secrets_1.withoutSignedLinks)(plan);
435
752
  await (0, promises_1.mkdir)(this.layout.root, { recursive: true, mode: 0o700 });
436
753
  await (0, save_1.writeJson)(this.layout.plan, planCopy);
@@ -453,6 +770,7 @@ class Maker {
453
770
  local_fix_used: previous?.quote_id === handed.quote_id ? previous.local_fix_used : false,
454
771
  fixes: previous?.quote_id === handed.quote_id ? (previous.fixes ?? []) : [],
455
772
  upload_attempt: previous?.quote_id === handed.quote_id ? previous.upload_attempt : 0,
773
+ patch_sha256: this.patch?.sha256 ?? null,
456
774
  started_at: previous?.started_at ?? started,
457
775
  updated_at: started,
458
776
  };
@@ -460,7 +778,7 @@ class Maker {
460
778
  // The style, then every part: all checked before anything is spent.
461
779
  // The style must be exactly the one approved: the package's hash and the plan's must agree.
462
780
  if (!plan.style_hash || handed.style_package.style_hash !== plan.style_hash) {
463
- throw new errors_1.KitStop('The style handed over is not the one approved for this video. Nothing was spent.', 'change_request');
781
+ throw new errors_1.KitStop('The style handed over is not the one approved for this video.', 'change_request');
464
782
  }
465
783
  const pin = { id: plan.style_id, version: plan.style_version, hash: plan.style_hash };
466
784
  this.at = 'style';
@@ -469,6 +787,7 @@ class Maker {
469
787
  ? await (0, style_1.readLocalStyle)(dev.styles, pin, note)
470
788
  : await (0, style_1.fetchStyle)({ ref: handed.style_package, projectId: this.videoId, dir: this.layout.style, download: (u, m) => deps.line.download(u, m, this.stop.signal), note });
471
789
  await this.loadParts(!!dev.parts);
790
+ this.armCeiling(this.ceilingFor());
472
791
  // The card's rows show from here, all still to do, while the plan's files come down.
473
792
  const planned = (id) => ({ id, row: (0, progress_1.rowOf)(this.parts.get(id).manifest), typical_s: this.parts.get(id).manifest.timing.typical_s });
474
793
  this.book.plan([...this.style.style.timeline.map((s) => planned(s.id)), ...this.layersOn().map((slot) => planned(`layer-${slot}`))]);
@@ -481,7 +800,7 @@ class Maker {
481
800
  download: (u, m) => deps.line.download(u, m, this.stop.signal),
482
801
  hostedLink: (fileId) => deps.line.hostedFileLink(this.videoId, fileId, this.stop.signal).catch((error) => {
483
802
  if (error instanceof client_1.LineError)
484
- throw new errors_1.KitStop(`${lineWords(error)} Nothing was spent.`, error.next === 'update_kit' ? 'update_kit' : error.next === 'change_request' ? 'change_request' : 'stop', error.code);
803
+ throw (0, errors_1.lineStop)((0, client_1.lineWords)(error), error.next, error.code);
485
804
  throw error;
486
805
  }),
487
806
  // A hosted plan file goes into a payload as the line already knows it.
@@ -516,66 +835,72 @@ class Maker {
516
835
  const lock = this.lock;
517
836
  const layerRefs = lock?.layers ?? this.handed.plan.layers;
518
837
  const wanted = [
519
- ...this.style.style.timeline.map((s) => ({ key: s.id, ref: s.part })),
838
+ ...this.style.style.timeline.map((s) => ({ key: s.id, ref: (0, lock_1.lockedRef)(s.part, lock) })),
520
839
  ...this.layersOn().map((slot) => ({ key: `layer-${slot}`, ref: layerRefs?.[slot], slot })),
521
840
  ];
522
841
  for (const { key, ref, slot } of wanted) {
523
842
  this.at = key;
524
843
  if (!ref || typeof ref.id !== 'string' || typeof ref.version !== 'string')
525
- throw new errors_1.KitStop('This video names a part it has no version for. Nothing was spent.', 'change_request');
844
+ throw new errors_1.KitStop('This video names a part it has no version for.', 'change_request');
526
845
  if (lock) {
527
846
  const entry = lock.parts[ref.id];
528
847
  if (!entry || entry.version !== ref.version) {
529
848
  this.deps.log.write('error', 'part not in the parts list', { step: key, part: `${ref.id}@${ref.version}`, locked: entry?.version ?? null });
530
- throw new errors_1.KitStop(`A part this video uses is not in this video’s parts list, so it can’t run. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', 'not_locked');
849
+ throw new errors_1.KitStop(`A part this video uses is not in this video’s parts list, so it can’t run. ${PLAN_CHANGE}`, 'change_request', 'not_locked');
531
850
  }
532
851
  const tooOld = (0, version_1.kitRangeRefusal)({ id: ref.id, version: ref.version, kit: entry.kit });
533
852
  if (tooOld) {
534
853
  this.deps.log.write('error', 'part needs another kit', { step: key, refusal: tooOld });
535
- throw new errors_1.KitStop('This video needs a newer video kit. Nothing was spent.', 'update_kit', 'kit_range');
854
+ throw new errors_1.KitStop('This video needs a newer video kit.', 'update_kit', 'kit_range');
536
855
  }
537
856
  }
538
857
  }
539
858
  for (const { key, ref, slot } of wanted) {
540
859
  this.at = key;
541
860
  let loaded;
861
+ const edit = this.patchOf(key);
862
+ const patched = edit && lock ? { dir: path.join(this.layout.patches, key), files: (0, patch_1.patchedFiles)(edit, lock) } : undefined;
542
863
  try {
543
- loaded = await this.deps.host.loader.load({ ref, lock, dev, home: this.deps.home, env: this.deps.env, signal: this.stop.signal });
864
+ loaded = await this.deps.host.loader.load({ ref, lock, dev, home: this.deps.home, env: this.deps.env, signal: this.stop.signal, ...(patched ? { patched } : {}) });
544
865
  }
545
866
  catch (error) {
546
867
  this.deps.log.write('error', 'part could not be loaded', {
547
868
  step: key,
548
869
  part: `${ref.id}@${ref.version}`,
870
+ edited: !!patched,
549
871
  code: error instanceof loader_1.PartLoadError ? error.code : null,
550
872
  error: error instanceof Error ? error.message : String(error),
551
873
  });
874
+ // The edit is this computer's own: the video is fine, so it only stops.
875
+ if (patched && error instanceof loader_1.PartLoadError && error.code === 'hash_mismatch')
876
+ throw new errors_1.KitStop(error.message, 'stop', 'patch_refused');
552
877
  throw loadStop(error);
553
878
  }
554
879
  const m = loaded.manifest;
555
880
  const refused = (why, fields = {}) => this.deps.log.write('error', why, { step: key, part: `${ref.id}@${ref.version}`, ...fields });
556
881
  if (m.id !== ref.id || m.version !== ref.version) {
557
882
  refused('part loaded as another version', { loaded: `${m.id}@${m.version}` });
558
- throw new errors_1.KitStop(`A part this video uses loaded as another version, so it can’t run. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', 'manifest_mismatch');
883
+ throw new errors_1.KitStop(`A part this video uses loaded as another version, so it can’t run. ${PLAN_CHANGE}`, 'change_request', 'manifest_mismatch');
559
884
  }
560
885
  const refusal = (0, version_1.interfaceRefusal)(m);
561
886
  if (refusal) {
562
887
  refused('part needs another interface', { refusal });
563
- throw new errors_1.KitStop('This video needs a newer video kit. Nothing was spent.', 'update_kit', 'interface');
888
+ throw new errors_1.KitStop('This video needs a newer video kit.', 'update_kit', 'interface');
564
889
  }
565
890
  if (slot && (m.layer !== slot || m.kind !== SLOT_KIND[slot])) {
566
891
  refused('part can’t fill its layer', { slot, layer: m.layer ?? null, kind: m.kind });
567
- throw new errors_1.KitStop(`A part this video uses can’t do the job its plan gives it. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', 'wrong_layer');
892
+ throw new errors_1.KitStop(`A part this video uses can’t do the job its plan gives it. ${PLAN_CHANGE}`, 'change_request', 'wrong_layer');
568
893
  }
569
894
  const lockModels = lock ? lock.parts[ref.id].models : m.needs.models;
570
895
  const paid = m.needs.network || m.needs.models.length > 0 || m.kind.startsWith('generate_');
571
896
  if (paid && (!Array.isArray(lockModels) || lockModels.length === 0)) {
572
897
  refused('paid part has no models in the parts list');
573
- throw new errors_1.KitStop(`A part this video uses would order paid pieces its approved price doesn’t allow. ${PLAN_CHANGE} Nothing was spent.`, 'change_request', 'no_models');
898
+ throw new errors_1.KitStop(`A part this video uses would order paid pieces its approved price doesn’t allow. ${PLAN_CHANGE}`, 'change_request', 'no_models');
574
899
  }
575
900
  const missing = this.missingNeeds(m.needs);
576
901
  if (missing) {
577
902
  refused('part needs what this computer lacks', { missing });
578
- throw new errors_1.KitStop(`This computer can’t make this video: ${missing}. Run the computer check, then make the video again. Nothing was spent.`, 'refused', 'needs_missing');
903
+ throw new errors_1.KitStop(`This computer can’t make this video: ${missing}. Run the computer check, then make the video again.`, 'refused', 'needs_missing');
579
904
  }
580
905
  try {
581
906
  (0, schema_1.assertCheckable)(m.inputs);
@@ -583,7 +908,7 @@ class Maker {
583
908
  }
584
909
  catch (error) {
585
910
  refused('part schema can’t be checked', { error: error.message });
586
- throw new errors_1.KitStop('This video needs a newer video kit. Nothing was spent.', 'update_kit', 'schema');
911
+ throw new errors_1.KitStop('This video needs a newer video kit.', 'update_kit', 'schema');
587
912
  }
588
913
  this.parts.set(key, loaded);
589
914
  }
@@ -622,7 +947,8 @@ class Maker {
622
947
  for (const step of this.style.style.timeline) {
623
948
  const loaded = this.parts.get(step.id);
624
949
  const { inputs, round } = fixed(step.id, this.bind(step.id, step.inputs, scope));
625
- const out = await this.runStep({ id: step.id, ref: step.part, loaded, inputs, models: this.modelsOf(step.part, loaded), fix: round }, hashes);
950
+ const ref = (0, lock_1.lockedRef)(step.part, this.lock);
951
+ const out = await this.runStep({ id: step.id, ref, loaded, inputs, models: this.modelsOf(ref, loaded), fix: round }, hashes);
626
952
  outputs.set(step.id, out);
627
953
  if (out.timeline && typeof out.timeline === 'object')
628
954
  timeline = out.timeline;
@@ -663,7 +989,7 @@ class Maker {
663
989
  }
664
990
  if (!verdict || typeof verdict.pass !== 'boolean' || !Array.isArray(verdict.checks))
665
991
  throw new errors_1.KitStop('The final check gave no verdict.', 'change_request');
666
- return { cut, captions, verdict, steps: hashes };
992
+ return { cut, captions, verdict, steps: hashes, timeline };
667
993
  }
668
994
  /** A style step's inputs: a reference the kit can't resolve goes to the log, plain words to the person. */
669
995
  bind(stepId, inputs, scope) {
@@ -692,6 +1018,17 @@ class Maker {
692
1018
  throw new errors_1.KitStop('The video’s length and size could not be read.', 'failed');
693
1019
  return { duration_s, width, height, fps, scenes: [], speech: [] };
694
1020
  }
1021
+ /** This step's remade pieces from the plan's takes (a video_fix remake), by piece key; null when none. */
1022
+ takesOf(stepId) {
1023
+ const listed = this.handed.plan.body.takes;
1024
+ const takes = {};
1025
+ for (const entry of Array.isArray(listed) ? listed : []) {
1026
+ const { piece_key, take } = (entry ?? {});
1027
+ if (typeof piece_key === 'string' && piece_key.startsWith(`${stepId}.`) && Number.isInteger(take) && take > 1)
1028
+ takes[piece_key] = take;
1029
+ }
1030
+ return Object.keys(takes).length ? takes : null;
1031
+ }
695
1032
  /** One step: reused when its saved record has the same hash and intact files, else run (and retried once). */
696
1033
  async runStep(spec, hashes) {
697
1034
  const { manifest } = spec.loaded;
@@ -701,7 +1038,9 @@ class Maker {
701
1038
  this.deps.log.write('error', 'step inputs refused', { step: spec.id, errors: inputErrors });
702
1039
  throw new errors_1.KitStop(`One step of this video was given something it can’t take, so the video stopped there. ${PLAN_CHANGE}`, 'change_request', 'bad_input');
703
1040
  }
704
- const hash = (0, canonical_1.stepHash)({ interface: manifest.interface, part: spec.ref, toolchain: this.toolchain, inputs: spec.inputs, fix: spec.fix });
1041
+ const edit = this.patchOf(spec.id);
1042
+ const takes = this.takesOf(spec.id);
1043
+ const hash = (0, canonical_1.stepHash)({ interface: manifest.interface, part: spec.ref, toolchain: this.toolchain, inputs: spec.inputs, fix: spec.fix, ...(edit ? { patch: (0, patch_1.stepPatchHash)(edit) } : {}), ...(takes ? { takes } : {}) });
705
1044
  hashes[spec.id] = hash;
706
1045
  const saved = await this.store.readStep(spec.id);
707
1046
  if (saved && saved.status === 'done' && saved.step_hash === hash && saved.outputs && this.run.steps[spec.id]?.status === 'done') {
@@ -739,11 +1078,19 @@ class Maker {
739
1078
  this.deps.log.write('info', 'step started', { step: spec.id, part: `${spec.ref.id}@${spec.ref.version}`, attempt });
740
1079
  void this.reporter.send();
741
1080
  const timeoutMs = manifest.timing.timeout_s * 1000;
742
- const link = (0, client_1.linkedSignal)([this.stop.signal], timeoutMs);
1081
+ // Aborted as the step ends, however it ends, so nothing the part left running outlives it.
1082
+ const over = new AbortController();
1083
+ const link = (0, client_1.linkedSignal)([this.stop.signal, over.signal], timeoutMs);
1084
+ const waiting = new Set();
1085
+ // Read as the time runs out, before the cut-short calls give up their pieces.
1086
+ let slowAtLine = false;
743
1087
  try {
744
- const ctx = this.context(spec, attempt, workDir, tmpDir, link.signal, record);
1088
+ const ctx = this.context(spec, attempt, workDir, tmpDir, link.signal, record, waiting);
745
1089
  const outputs = await new Promise((resolve, reject) => {
746
- const ended = () => reject(this.stop.signal.aborted ? new errors_1.PartError('stopped') : new errors_1.PartError('timeout', `${spec.id} ran past ${manifest.timing.timeout_s} s`));
1090
+ const ended = () => {
1091
+ slowAtLine = !this.stop.signal.aborted && waiting.size > 0;
1092
+ reject(this.stop.signal.aborted ? new errors_1.PartError('stopped') : new errors_1.PartError('timeout', `${spec.id} ran past ${manifest.timing.timeout_s} s${slowAtLine ? ' waiting on the line' : ''}`));
1093
+ };
747
1094
  // Stopped while the step was being saved: the part never starts.
748
1095
  if (link.signal.aborted)
749
1096
  return ended();
@@ -785,13 +1132,16 @@ class Maker {
785
1132
  this.deps.log.write('warn', 'step failed', { step: spec.id, attempt, code: failure.code, detail: record.error?.detail ?? null });
786
1133
  if (failure.retryable && attempt === 1 && manifest.retry?.transient !== 0)
787
1134
  continue;
788
- const words = failureWords(failure, this.idNames());
789
- const code = reportedCode(failure);
1135
+ const slow = failure.code === 'timeout' && slowAtLine;
1136
+ const words = slow ? slowWords((0, progress_1.rowOf)(manifest)) : failureWords(failure, this.idNames());
1137
+ const code = slow ? PROVIDER_SLOW : reportedCode(failure);
790
1138
  this.book.finish(spec.id, 'failed');
791
- this.reportFailure(spec.id, code, words);
1139
+ this.reporter.close();
1140
+ this.reportFailure(spec.id, code, words, PLAN_CODES.has(code) ? failure.fromPart : undefined);
792
1141
  throw new errors_1.KitStop(words, failure.code === 'over_quote' ? 'stop' : 'failed', code);
793
1142
  }
794
1143
  finally {
1144
+ over.abort(new errors_1.PartError('stopped'));
795
1145
  link.done();
796
1146
  }
797
1147
  }
@@ -810,7 +1160,7 @@ class Maker {
810
1160
  throw new errors_1.PartError('output_invalid', 'an output file does not match its hash');
811
1161
  }
812
1162
  }
813
- context(spec, attempt, workDir, tmpDir, signal, record) {
1163
+ context(spec, attempt, workDir, tmpDir, signal, record, waiting) {
814
1164
  const { manifest } = spec.loaded;
815
1165
  const tools = (0, toolchain_1.kitTools)({ ffmpeg: this.tools.ffmpeg.path ?? '', ffprobe: this.tools.ffprobe.path ?? '', toolchain: this.toolchain }, signal);
816
1166
  const seedInput = spec.inputs.seed ?? null;
@@ -821,6 +1171,7 @@ class Maker {
821
1171
  stepId: spec.id,
822
1172
  part: spec.ref,
823
1173
  models: spec.models,
1174
+ runId: this.runId,
824
1175
  workDir,
825
1176
  runRoot: this.layout.root,
826
1177
  cache: this.cache,
@@ -830,6 +1181,8 @@ class Maker {
830
1181
  hosted: this.hosted,
831
1182
  locks: this.pieceLocks,
832
1183
  onWait: () => void this.reporter.send(),
1184
+ waiting,
1185
+ takes: this.takesOf(spec.id) ?? undefined,
833
1186
  onPiece: async (piece) => {
834
1187
  record.pieces.push(piece);
835
1188
  await this.store.writeStep(record);
@@ -908,12 +1261,13 @@ class Maker {
908
1261
  const message = (typeof said?.message === 'string' && said.message.trim()) || reasonFor(verdict, code);
909
1262
  const detail = (0, plain_words_1.plainWords)(message, CHECK_FAILED, this.idNames());
910
1263
  this.deps.log.write('warn', 'the final check failed', { check: code, message, detail });
1264
+ this.reporter.close();
911
1265
  this.reportFailure('layer-check', 'check_failed', detail);
912
1266
  await this.reporter.flush();
913
1267
  this.run.status = 'failed';
914
1268
  await this.saveRun();
915
1269
  const notSent = 'The video didn’t pass the final check, so it wasn’t sent. Nothing more will be charged for it.';
916
- return { status: 'failed', message: detail === CHECK_FAILED ? notSent : `${detail} ${notSent}` };
1270
+ return { status: 'failed', message: detail === CHECK_FAILED ? notSent : `${detail} ${notSent}`, code: 'check_failed' };
917
1271
  }
918
1272
  /** Part, step and layer ids, which the person never sees. */
919
1273
  idNames() {
@@ -930,10 +1284,23 @@ class Maker {
930
1284
  await (0, save_1.writeJson)(path.join(this.layout.final, 'check.json'), verdict);
931
1285
  if (!result)
932
1286
  return null;
933
- const final = path.join(this.layout.final, 'final.mp4');
934
- await (0, promises_1.copyFile)(result.cut.path, final);
1287
+ // A candidate until our server passes it: a failed one never replaces an earlier good final.
1288
+ const candidate = path.join(this.layout.final, CANDIDATE);
1289
+ await (0, promises_1.copyFile)(result.cut.path, candidate);
935
1290
  if (result.captions)
936
- await (0, promises_1.copyFile)(result.captions.path, path.join(this.layout.final, 'captions.vtt'));
1291
+ await (0, promises_1.copyFile)(result.captions.path, path.join(this.layout.final, CANDIDATE_CAPTIONS));
1292
+ else
1293
+ await (0, promises_1.rm)(path.join(this.layout.final, CANDIDATE_CAPTIONS), { force: true });
1294
+ return candidate;
1295
+ }
1296
+ /** The passed candidate becomes the final, in one rename each. */
1297
+ async promoteFinal(hasCaptions) {
1298
+ const final = path.join(this.layout.final, 'final.mp4');
1299
+ await (0, promises_1.rename)(path.join(this.layout.final, CANDIDATE), final);
1300
+ if (hasCaptions)
1301
+ await (0, promises_1.rename)(path.join(this.layout.final, CANDIDATE_CAPTIONS), path.join(this.layout.final, 'captions.vtt'));
1302
+ else
1303
+ await (0, promises_1.rm)(path.join(this.layout.final, 'captions.vtt'), { force: true });
937
1304
  return final;
938
1305
  }
939
1306
  manifestFor(steps) {
@@ -947,15 +1314,20 @@ class Maker {
947
1314
  steps,
948
1315
  kit: { version: version_1.KIT_VERSION, toolchain: this.toolchain },
949
1316
  parts_source: this.run.kit.parts_source,
1317
+ // The server matches it with the edit the hand-over registered.
1318
+ ...(this.patch ? { patch: { sha256: this.patch.sha256, steps: this.patch.steps.map((s) => ({ step: s.step, part: `${s.part.id}@${s.part.version}` })) } } : {}),
950
1319
  };
951
1320
  }
1321
+ patchOf(step) {
1322
+ return this.patch?.steps.find((s) => s.step === step) ?? null;
1323
+ }
952
1324
  /** Upload, our server's check, and one fix after a first failed check. */
953
1325
  async upload(result) {
954
1326
  let current = result;
955
1327
  this.at = 'upload';
956
1328
  for (;;) {
957
- const final = (await this.writeFinal(current, current.verdict));
958
- const data = await (0, promises_1.readFile)(final);
1329
+ const candidate = (await this.writeFinal(current, current.verdict));
1330
+ const data = await (0, promises_1.readFile)(candidate);
959
1331
  if (data.length > types_1.MAX_UPLOAD_BYTES)
960
1332
  throw new errors_1.KitStop('The finished video is larger than the line takes.', 'failed');
961
1333
  const sha256 = (0, canonical_1.sha256Hex)(data);
@@ -973,33 +1345,48 @@ class Maker {
973
1345
  throw new errors_1.KitStop('The captions file is larger than the line takes.', 'failed');
974
1346
  captions_vtt = captions.toString('utf8');
975
1347
  }
1348
+ const eyes = await this.lookAt(candidate, current);
976
1349
  this.book.note = 'Sending your video for its final check';
977
1350
  this.run.status = 'uploading';
978
1351
  await this.saveRun();
979
1352
  void this.reporter.send(true);
980
1353
  let check;
981
1354
  try {
982
- check = await this.sendUpload(sha256, data, captions_vtt, this.manifestFor(current.steps));
1355
+ const noted = [...verdictWarnings(current.verdict), ...(eyes?.warnings ?? [])].slice(0, MAX_SENT_WARNINGS);
1356
+ check = await this.sendUpload(sha256, data, captions_vtt, { ...this.manifestFor(current.steps), ...(noted.length ? { check_warnings: noted } : {}) });
983
1357
  }
984
1358
  catch (error) {
985
1359
  if (error instanceof client_1.LineError)
986
- throw new errors_1.KitStop(lineWords(error), error.next === 'update_kit' ? 'update_kit' : error.next === 'change_request' ? 'change_request' : 'stop', error.code);
1360
+ throw (0, errors_1.lineStop)((0, client_1.lineWords)(error), error.next, error.code);
987
1361
  throw error;
988
1362
  }
989
1363
  this.run.upload_attempt = check.attempt;
990
1364
  if (check.result === 'pass') {
1365
+ const final = await this.promoteFinal(!!current.captions);
991
1366
  this.run.status = 'done';
992
1367
  await this.saveRun();
993
1368
  await this.cleanTmp();
994
- return { status: 'done', message: `Your video is ready. It passed the final check. Saved here: ${final}` };
1369
+ return {
1370
+ status: 'done',
1371
+ message: `Your video is ready. It passed the final check. Saved here: ${final}`,
1372
+ final,
1373
+ ...(eyes?.contact_sheet ? { contact_sheet: eyes.contact_sheet } : {}),
1374
+ ...(eyes?.warnings.length ? { warnings: eyes.warnings.map((w) => w.message) } : {}),
1375
+ };
995
1376
  }
996
1377
  const reasons = check.reasons.map((r) => r.message).filter(Boolean).join(' ');
997
1378
  const serverFixUsed = (this.run.fixes ?? []).some((f) => f.from === 'server');
998
1379
  const fix = check.fixes_left > 0 && !serverFixUsed ? this.fixFrom(current.verdict, check.reasons.map((r) => r.check), 'server') : null;
999
1380
  if (!fix) {
1381
+ this.reporter.close();
1382
+ // The line went back to Making for a fix this run can't make, so it must hear the check failed.
1383
+ if (check.fixes_left > 0) {
1384
+ this.reportFailure('final-check', 'check_failed', (0, plain_words_1.plainWords)(reasons, CHECK_FAILED, this.idNames()));
1385
+ await this.reporter.flush();
1386
+ }
1000
1387
  this.run.status = 'failed';
1001
1388
  await this.saveRun();
1002
- return { status: 'failed', message: `The video didn’t pass our check. ${reasons}`.trim() };
1389
+ return { status: 'failed', message: `The video didn’t pass our check. ${reasons}`.trim(), code: 'check_failed' };
1003
1390
  }
1004
1391
  this.run.fixes = [...(this.run.fixes ?? []), fix];
1005
1392
  this.run.status = 'running';
@@ -1057,11 +1444,42 @@ class Maker {
1057
1444
  await this.store.writeUpload(saved);
1058
1445
  return finish(stage);
1059
1446
  }
1447
+ /** The contact sheet and the product-presence warning, next to the final; never at the video's cost. */
1448
+ async lookAt(final, made) {
1449
+ const ffmpeg = this.tools.ffmpeg.path;
1450
+ if (!ffmpeg)
1451
+ return null;
1452
+ const listed = this.planScope?.products;
1453
+ const products = Array.isArray(listed) ? listed : [];
1454
+ try {
1455
+ return await (0, eyes_1.lookAtFinal)({
1456
+ ffmpeg,
1457
+ final,
1458
+ timeline: made.timeline,
1459
+ products: products.map((p) => ({
1460
+ ...(typeof p?.name === 'string' ? { name: p.name } : {}),
1461
+ photos: (Array.isArray(p?.images) ? p.images : []).filter((ref) => (0, canonical_1.isFileRef)(ref) && ref.media === 'image').map((ref) => ref.path),
1462
+ })),
1463
+ signal: this.stop.signal,
1464
+ });
1465
+ }
1466
+ catch (error) {
1467
+ this.deps.log.write('warn', 'the contact sheet could not be made', { error: error instanceof Error ? error.message : String(error) });
1468
+ return null;
1469
+ }
1470
+ }
1060
1471
  async cleanTmp() {
1061
1472
  for (const key of this.parts.keys())
1062
1473
  await (0, promises_1.rm)(path.join(this.store.stepDir(key), 'out', '.tmp'), { recursive: true, force: true }).catch(() => undefined);
1063
1474
  }
1064
1475
  }
1476
+ /** The first line after the hand-over: which video, for which brand, on which GooseWorks. */
1477
+ function startLine(video, environment) {
1478
+ const name = video?.name?.trim();
1479
+ const brand = video?.brand?.trim();
1480
+ const where = video?.environment?.trim() || environment;
1481
+ return `Making ${name ? `“${name}”` : 'your video'}${brand ? ` for ${brand}` : ''} on GooseWorks ${where}.`;
1482
+ }
1065
1483
  async function makeVideo(videoId, deps) {
1066
1484
  return new Maker(videoId, deps).make();
1067
1485
  }