@kriya-ai/harness 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/edit/core/ffmpeg.js +5 -1
- package/src/edit/core/layout.js +2 -0
- package/src/edit/core/ops.js +71 -4
- package/src/edit/core/project.js +6 -1
- package/src/edit/core/solver.js +27 -12
- package/src/edit/director/ask.js +58 -13
- package/src/edit/director/plan.js +298 -0
- package/src/edit/director/revise.js +207 -12
- package/src/edit/engine/motion.js +59 -16
- package/src/edit/engine/music-bed.js +110 -0
- package/src/edit/engine/reference.js +134 -0
- package/src/edit/engine/sfx.js +63 -0
- package/src/edit/host/client.js +28 -4
- package/src/edit/host/jobs.js +52 -1
- package/src/edit/host/main.js +4 -2
- package/src/edit/host/paths.js +25 -0
- package/src/edit/host/projects.js +187 -16
- package/src/edit/host/server.js +111 -9
- package/src/edit/index/db.js +28 -1
- package/src/edit/index/layers/retakes.js +7 -1
- package/src/edit/loop/make.js +2 -2
- package/src/edit/recipes/reel.js +127 -17
- package/src/edit/runtime/setup.js +12 -8
- package/studio/dist/studio.css +78 -6
- package/studio/dist/studio.js +5 -1
package/package.json
CHANGED
package/src/edit/core/ffmpeg.js
CHANGED
|
@@ -60,11 +60,15 @@ export const animatedZoom = (zoom) => zoom !== undefined && (zoom.x !== undefine
|
|
|
60
60
|
|
|
61
61
|
// A colour match (ED13) is its baked .cube, measured by the Engine; then the person's own values.
|
|
62
62
|
// shortcut: eq only approximates lift, gain and ev; a full lift/gamma/gain grade isn't built
|
|
63
|
-
function gradeSteps({ gamma, saturation, lift, gain, ev, match }, input) {
|
|
63
|
+
function gradeSteps({ gamma, saturation, lift, gain, ev, match, temperature, vibrance, vignette }, input) {
|
|
64
64
|
const steps = match ? [filter("lut3d", { file: input(match.key) })] : []
|
|
65
|
+
if (temperature !== undefined) steps.push(filter("colortemperature", { temperature: Math.round(temperature) }))
|
|
65
66
|
const brightness = (lift ?? 0) + (ev ?? 0) / 8
|
|
66
67
|
const options = Object.fromEntries(Object.entries({ gamma, saturation, brightness: brightness || undefined, contrast: gain }).filter(([, value]) => value !== undefined))
|
|
67
68
|
if (Object.keys(options).length) steps.push(filter("eq", options))
|
|
69
|
+
if (vibrance !== undefined) steps.push(filter("vibrance", { intensity: vibrance.toFixed(3) }))
|
|
70
|
+
// A lens-like darkening at the edges: the angle grows with the strength
|
|
71
|
+
if (vignette) steps.push(filter("vignette", { angle: (0.25 + 0.45 * vignette).toFixed(3) }))
|
|
68
72
|
return steps
|
|
69
73
|
}
|
|
70
74
|
|
package/src/edit/core/layout.js
CHANGED
|
@@ -20,6 +20,8 @@ export function safeZoneFor(project) {
|
|
|
20
20
|
const { width, height } = project.canvas
|
|
21
21
|
const zone = {}
|
|
22
22
|
for (const deliverable of project.deliverables ?? []) {
|
|
23
|
+
// Only exports in this frame's shape: an earlier 9:16 export's margins don't squeeze a 16:9 cut (found in use)
|
|
24
|
+
if (deliverable.size && deliverable.size.width * height !== deliverable.size.height * width) continue
|
|
23
25
|
const share = SAFE_ZONES[deliverable.preset]
|
|
24
26
|
if (!share) continue
|
|
25
27
|
for (const [side, value] of Object.entries(share)) zone[side] = Math.max(zone[side] ?? 0, Math.ceil(value * (side === "top" || side === "bottom" ? height : width)))
|
package/src/edit/core/ops.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { anchorSource, openIndex, wordAfter, wordAt, wordBefore } from "./anchors.js"
|
|
6
6
|
import { check, EFFECTS, SHAPES, validateProject } from "./project.js"
|
|
7
|
+
import { snapToFrame } from "./time.js"
|
|
7
8
|
|
|
8
9
|
class Refused extends Error {
|
|
9
10
|
constructor(code, message) {
|
|
@@ -186,6 +187,21 @@ const OPS = {
|
|
|
186
187
|
clips.splice(op.after === null ? 0 : clips.indexOf(clipOf(s, op.after)) + 1, 0, clip)
|
|
187
188
|
},
|
|
188
189
|
},
|
|
190
|
+
// A cold open (ED story): a moment from later plays first, then the story starts. The
|
|
191
|
+
// clip is marked an echo, so captions and anchors stay on the moment itself; mono puts it
|
|
192
|
+
// in black and white, the classic teaser
|
|
193
|
+
cold_open: {
|
|
194
|
+
fields: { asset: "id", from: "ref", to: "ref", "mono?": "bool" },
|
|
195
|
+
run(op, s) {
|
|
196
|
+
const asset = assetOf(s, op.asset, SEQUENCED)
|
|
197
|
+
checkRange(s, asset, sourceEdge(s, op.from, asset.id, "start"), sourceEdge(s, op.to, asset.id, "end"))
|
|
198
|
+
const clip = addClip(s, "base", { source: { asset: asset.id, in: op.from, out: op.to }, echo: true })
|
|
199
|
+
const clips = sequenceOf(s).clips
|
|
200
|
+
clips.pop()
|
|
201
|
+
clips.splice(0, 0, clip)
|
|
202
|
+
if (op.mono) setEffect(clip, { type: "grade", saturation: 0, gain: 1.12, vignette: 0.4 })
|
|
203
|
+
},
|
|
204
|
+
},
|
|
189
205
|
remove_range: {
|
|
190
206
|
fields: { "asset?": "id", from: "ref", to: "ref" },
|
|
191
207
|
run(op, s) {
|
|
@@ -288,6 +304,53 @@ const OPS = {
|
|
|
288
304
|
writable(s, op.clip).speed = op.rate
|
|
289
305
|
},
|
|
290
306
|
},
|
|
307
|
+
// A speed ramp: the stretch from..to eases up to `peak` and back, in five steps, so a 2×
|
|
308
|
+
// whoosh through a moment or an eased slow motion (peak 1/2) reads as one movement.
|
|
309
|
+
// The sound goes with it, pitch kept (atempo)
|
|
310
|
+
speed_ramp: {
|
|
311
|
+
fields: { clip: "id", from: "ref", to: "ref", peak: "rate" },
|
|
312
|
+
run(op, s) {
|
|
313
|
+
const clip = writable(s, op.clip)
|
|
314
|
+
if (!clip.source) refuse("no_source", `clip "${op.clip}" has no picture to ramp`)
|
|
315
|
+
const ratio = op.peak.n / op.peak.d
|
|
316
|
+
if (!(ratio >= 0.25 && ratio <= 4) || ratio === 1) refuse("bad_value", "a ramp's peak is between 1/4 and 4 times, and not 1")
|
|
317
|
+
const asset = clip.source.asset
|
|
318
|
+
// Joins on frames, so neither side of a step drops or repeats one
|
|
319
|
+
const rate = assetOf(s, asset, SEQUENCED).facts.fps ?? s.project.canvas.fps
|
|
320
|
+
const onFrame = (t) => snapToFrame(t, rate, "nearest")
|
|
321
|
+
const t0 = onFrame(sourceEdge(s, op.from, asset, "start"))
|
|
322
|
+
const t1 = onFrame(sourceEdge(s, op.to, asset, "end"))
|
|
323
|
+
const [start, end] = clipRange(s, clip)
|
|
324
|
+
if (!(t0 >= start && t1 <= end && t1 > t0)) refuse("outside_clip", `that stretch isn't inside clip "${op.clip}"`)
|
|
325
|
+
let region = clip
|
|
326
|
+
if (t0 > start) {
|
|
327
|
+
region = splitClip(s, clip, { out: t0, in: t0 }, t0)
|
|
328
|
+
clip.seamOut = true
|
|
329
|
+
region.seamIn = true
|
|
330
|
+
}
|
|
331
|
+
if (t1 < end) {
|
|
332
|
+
const after = splitClip(s, region, { out: t1, in: t1 }, t1)
|
|
333
|
+
region.seamOut = true
|
|
334
|
+
after.seamIn = true
|
|
335
|
+
}
|
|
336
|
+
// Five equal steps of source: up, up, the peak, down, down
|
|
337
|
+
const shape = [0.4, 0.8, 1, 0.8, 0.4]
|
|
338
|
+
const gcd = (a, b) => (b ? gcd(b, a % b) : a)
|
|
339
|
+
const rateOf = (f) => {
|
|
340
|
+
const n = Math.round((1 + (ratio - 1) * f) * 100)
|
|
341
|
+
const g = gcd(n, 100)
|
|
342
|
+
return { n: n / g, d: 100 / g }
|
|
343
|
+
}
|
|
344
|
+
let piece = region
|
|
345
|
+
for (let i = 0; i < shape.length; i++) {
|
|
346
|
+
const cut = onFrame(t0 + ((t1 - t0) * (i + 1)) / shape.length)
|
|
347
|
+
const next = i < shape.length - 1 ? splitClip(s, piece, { out: cut, in: cut }, cut) : null
|
|
348
|
+
if (next) ((piece.seamOut = true), (next.seamIn = true))
|
|
349
|
+
piece.speed = rateOf(shape[i])
|
|
350
|
+
piece = next
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
},
|
|
291
354
|
freeze: {
|
|
292
355
|
fields: { clip: "id", at: "ref", duration: "flicks" },
|
|
293
356
|
run(op, s) {
|
|
@@ -463,10 +526,14 @@ const OPS = {
|
|
|
463
526
|
|
|
464
527
|
// Colour
|
|
465
528
|
grade: {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
529
|
+
// temperature in kelvin (6500 neutral, lower is warmer), vibrance -2 to 2, vignette 0 to 1
|
|
530
|
+
fields: { clip: "id", "lift?": "num", "gamma?": "num", "gain?": "num", "saturation?": "num", "temperature?": "num", "vibrance?": "num", "vignette?": "num" },
|
|
531
|
+
run(op, s) {
|
|
532
|
+
const values = given(op, ["lift", "gamma", "gain", "saturation", "temperature", "vibrance", "vignette"])
|
|
533
|
+
if (Object.keys(values).length === 0) refuse("needs_a_value", "give at least one of lift, gamma, gain, saturation, temperature, vibrance or vignette")
|
|
534
|
+
if (values.temperature !== undefined && (values.temperature < 2000 || values.temperature > 12000)) refuse("bad_value", "temperature is between 2000 and 12000 kelvin")
|
|
535
|
+
if (values.vibrance !== undefined && Math.abs(values.vibrance) > 2) refuse("bad_value", "vibrance is between -2 and 2")
|
|
536
|
+
if (values.vignette !== undefined && (values.vignette < 0 || values.vignette > 1)) refuse("bad_value", "vignette is between 0 and 1")
|
|
470
537
|
setEffect(writable(s, op.clip), { type: "grade", ...values })
|
|
471
538
|
},
|
|
472
539
|
},
|
package/src/edit/core/project.js
CHANGED
|
@@ -25,7 +25,7 @@ export const EFFECTS = {
|
|
|
25
25
|
reframe: { mode: { enum: ["subject", "fixed"] }, "x?": "int", "y?": "int" },
|
|
26
26
|
zoom: { scale: "num", "ease?": "str", "x?": "int", "y?": "int" },
|
|
27
27
|
matte: { "model?": "str" },
|
|
28
|
-
grade: { "lift?": "num", "gamma?": "num", "gain?": "num", "saturation?": "num", "ev?": "num", "match?": "id" },
|
|
28
|
+
grade: { "lift?": "num", "gamma?": "num", "gain?": "num", "saturation?": "num", "ev?": "num", "match?": "id", "temperature?": "num", "vibrance?": "num", "vignette?": "num" },
|
|
29
29
|
lut: { asset: "id" },
|
|
30
30
|
stabilize: { "strength?": "num" },
|
|
31
31
|
fade: { "in?": "flicks", "out?": "flicks" },
|
|
@@ -96,6 +96,11 @@ export const SHAPES = {
|
|
|
96
96
|
effects: { list: "effect" },
|
|
97
97
|
speed: "rate",
|
|
98
98
|
"linkGroup?": "str",
|
|
99
|
+
// A cold open's teaser: the same words again, before the story. Anchors skip it
|
|
100
|
+
"echo?": "bool",
|
|
101
|
+
// A join, not a cut: this edge continues the clip beside it exactly (a speed ramp's steps)
|
|
102
|
+
"seamIn?": "bool",
|
|
103
|
+
"seamOut?": "bool",
|
|
99
104
|
"audioLead?": "flicks",
|
|
100
105
|
"audioLag?": "flicks",
|
|
101
106
|
createdBy: AUTHOR,
|
package/src/edit/core/solver.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// satisfy and never silently drops a request.
|
|
4
4
|
|
|
5
5
|
import { anchorSource, openIndex, wordAfter, wordAt, wordBefore } from "./anchors.js"
|
|
6
|
+
import { mapBox } from "./faces.js"
|
|
6
7
|
import { safeZoneFor, solveLayout } from "./layout.js"
|
|
7
8
|
import { flicksToFrames, frameAtTimestamp, framesToFlicks, scaleFlicks, snapToFrame } from "./time.js"
|
|
8
9
|
|
|
@@ -74,9 +75,11 @@ function cutPoints(s, clip, asset) {
|
|
|
74
75
|
s.issue("cut_moved_off_word", { clip: clip.id, word: word.id, message: "a cut would have landed inside a word, so it moved to the word's edge" })
|
|
75
76
|
return t
|
|
76
77
|
}
|
|
77
|
-
|
|
78
|
+
// A seam is a join inside one continuous take (a speed ramp's step): it stays exactly where it is
|
|
79
|
+
if (clip.seamIn && clip.seamOut) return { pictureIn: start, pictureOut: end, soundIn: start, soundOut: end }
|
|
80
|
+
const inStart = clip.seamIn ? null : wordAt(words, start)
|
|
78
81
|
if (inStart) start = moved(inStart, inStart.start)
|
|
79
|
-
const inEnd = wordAt(words, end)
|
|
82
|
+
const inEnd = clip.seamOut ? null : wordAt(words, end)
|
|
80
83
|
if (inEnd) end = moved(inEnd, inEnd.end)
|
|
81
84
|
|
|
82
85
|
const floor = wordBefore(words, start)?.end ?? 0
|
|
@@ -114,7 +117,7 @@ function cutPoints(s, clip, asset) {
|
|
|
114
117
|
}
|
|
115
118
|
soundIn = Math.max(0, soundIn - lead)
|
|
116
119
|
soundOut = Math.min(duration, soundOut + lag)
|
|
117
|
-
return { pictureIn, pictureOut, soundIn, soundOut }
|
|
120
|
+
return clip.seamIn ? (clip.seamOut ? { pictureIn: start, pictureOut: end, soundIn: start, soundOut: end } : { pictureIn: start, pictureOut, soundIn: start, soundOut }) : clip.seamOut ? { pictureIn, pictureOut: end, soundIn, soundOut: end } : { pictureIn, pictureOut, soundIn, soundOut }
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
const framesFor = (span, fps) => (span <= 0 ? 0 : flicksToFrames(span - 1, fps) + 1)
|
|
@@ -135,7 +138,7 @@ function layBase(s, clips) {
|
|
|
135
138
|
const piece = (from, to, length, hold) => {
|
|
136
139
|
const frames = framesFor(length, s.fps)
|
|
137
140
|
if (frames === 0) return
|
|
138
|
-
const item = { clip: clip.id, asset: asset.id, in: from, out: to, at: framesToFlicks(frame, s.fps), end: framesToFlicks(frame + frames, s.fps), speed: clip.speed, effects, ...(hold ? { hold } : {}) }
|
|
141
|
+
const item = { clip: clip.id, asset: asset.id, in: from, out: to, at: framesToFlicks(frame, s.fps), end: framesToFlicks(frame + frames, s.fps), speed: clip.speed, effects, ...(hold ? { hold } : {}), ...(clip.echo ? { echo: true } : {}) }
|
|
139
142
|
frame += frames
|
|
140
143
|
s.picture.push(item)
|
|
141
144
|
return item
|
|
@@ -169,7 +172,8 @@ function layBase(s, clips) {
|
|
|
169
172
|
/** Where a time in an asset sits on the timeline, or null if it was cut. */
|
|
170
173
|
function mapSource(s, place, anchor, spot) {
|
|
171
174
|
const edge = anchor.edge ?? "start"
|
|
172
|
-
|
|
175
|
+
// A word lives where the story says it: never in a hold, never in a cold open's echo of it
|
|
176
|
+
const hit = s.picture.find(({ asset, in: from, out, hold, echo }) => !hold && !echo && asset === spot.asset && (edge === "start" ? from <= spot.t && spot.t < out : from < spot.t && spot.t <= out))
|
|
173
177
|
if (hit) return hit.at + scaleFlicks(spot.t - hit.in, inverse(hit.speed))
|
|
174
178
|
for (const clip of s.rest) {
|
|
175
179
|
if (clip.source?.asset !== spot.asset || s.tracks.get(clip.track).role === "ambience") continue
|
|
@@ -329,19 +333,30 @@ function placeRest(s) {
|
|
|
329
333
|
}
|
|
330
334
|
}
|
|
331
335
|
|
|
332
|
-
//
|
|
336
|
+
// Faces under a caption, on the output, mapped as the render draws the frame (faces.js's mapBox:
|
|
337
|
+
// one scale that covers the frame, centred). Found in use: scaling width and height apart put
|
|
338
|
+
// faces in the wrong place whenever the take's shape differs from the frame, so captions sat on them.
|
|
339
|
+
// shortcut: a reframe's crop path isn't known yet here (plan.js makes it after the solver), so x is
|
|
340
|
+
// the centred crop's; a caption is a full-width row, so its y, which this gets exactly, is what matters
|
|
341
|
+
const FACE_REACH = 705_600_000 // faces are sampled once a second (L8), so look a second either side
|
|
333
342
|
function facesDuring(s, at, end) {
|
|
334
|
-
const
|
|
343
|
+
const canvas = s.project.canvas
|
|
335
344
|
const boxes = []
|
|
345
|
+
const zooms = s.zooms.filter((z) => z.at < end && at < z.end)
|
|
336
346
|
for (const piece of s.picture) {
|
|
337
347
|
if (piece.end <= at || piece.at >= end) continue
|
|
338
348
|
const facts = s.assets.get(piece.asset).facts
|
|
339
|
-
const
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
const to = piece.in + scaleFlicks(Math.min(piece.end, end) - piece.at, piece.speed)
|
|
349
|
+
const size = { width: facts.width ?? canvas.width, height: facts.height ?? canvas.height }
|
|
350
|
+
const from = piece.in + scaleFlicks(Math.max(0, at - piece.at), piece.speed) - FACE_REACH
|
|
351
|
+
const to = piece.in + scaleFlicks(Math.min(piece.end, end) - piece.at, piece.speed) + FACE_REACH
|
|
343
352
|
for (const face of s.raw.faces ?? []) {
|
|
344
|
-
if (face.asset
|
|
353
|
+
if (face.asset !== piece.asset || face.t < from || face.t > to) continue
|
|
354
|
+
// Clear the face both as shot and inside any punch-in over the caption
|
|
355
|
+
for (const zoom of [undefined, ...zooms]) {
|
|
356
|
+
const box = mapBox(face.box, { zoom }, size, canvas, canvas, face.t)
|
|
357
|
+
// A little room around the face: a caption touching the chin still reads as on it
|
|
358
|
+
if (box) boxes.push({ x: box.x - Math.round(box.w * 0.1), y: box.y - Math.round(box.h * 0.1), w: Math.round(box.w * 1.2), h: Math.round(box.h * 1.25) })
|
|
359
|
+
}
|
|
345
360
|
}
|
|
346
361
|
}
|
|
347
362
|
return boxes
|
package/src/edit/director/ask.js
CHANGED
|
@@ -54,12 +54,48 @@ export function schemaErrors(schema, value, path = "$") {
|
|
|
54
54
|
return problems
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
/**
|
|
58
|
+
* The JSON in a reply: the whole text, or else the first complete object in it, so a
|
|
59
|
+
* thinking block, a fence or a sentence around it doesn't sink a good answer.
|
|
60
|
+
* A reply cut off by its output limit says so, since "too long" is what to fix.
|
|
61
|
+
*/
|
|
62
|
+
export function parseReply(text, finish) {
|
|
63
|
+
// Some providers send the content as parts: [{ type: "text", text }]
|
|
64
|
+
const joined = Array.isArray(text) ? text.map((part) => (typeof part === "string" ? part : (part?.text ?? ""))).join("") : text
|
|
65
|
+
const raw = String(joined ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim()
|
|
66
|
+
// A trailing comma is the commonest near-miss; a comma before a closer is never meaningful
|
|
67
|
+
const lenient = (json) => {
|
|
68
|
+
try {
|
|
69
|
+
return { value: JSON.parse(json) }
|
|
70
|
+
} catch {
|
|
71
|
+
try {
|
|
72
|
+
return { value: JSON.parse(json.replace(/,(\s*[}\]])/g, "$1")) }
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const whole = lenient(raw.replace(/^```(?:json)?\s*|\s*```$/g, ""))
|
|
79
|
+
if (whole) return whole
|
|
80
|
+
// The first balanced {...}, skipping braces inside strings
|
|
81
|
+
for (let start = raw.indexOf("{"); start !== -1; start = raw.indexOf("{", start + 1)) {
|
|
82
|
+
let depth = 0
|
|
83
|
+
let quoted = false
|
|
84
|
+
for (let i = start; i < raw.length; i++) {
|
|
85
|
+
const c = raw[i]
|
|
86
|
+
if (quoted) {
|
|
87
|
+
if (c === "\\") i++
|
|
88
|
+
else if (c === '"') quoted = false
|
|
89
|
+
} else if (c === '"') quoted = true
|
|
90
|
+
else if (c === "{") depth++
|
|
91
|
+
else if (c === "}" && --depth === 0) {
|
|
92
|
+
const found = lenient(raw.slice(start, i + 1))
|
|
93
|
+
if (found) return found
|
|
94
|
+
break
|
|
95
|
+
}
|
|
96
|
+
}
|
|
62
97
|
}
|
|
98
|
+
return finish === "length" || !raw ? { problem: "was cut off before it finished (too long)", kind: "cut_off" } : { problem: "isn't valid JSON", kind: "no_json" }
|
|
63
99
|
}
|
|
64
100
|
|
|
65
101
|
/**
|
|
@@ -67,6 +103,8 @@ const parse = (text) => {
|
|
|
67
103
|
*/
|
|
68
104
|
// One slot's wait: a call's own limit (120 s, director/gateway.js) and a little queue
|
|
69
105
|
export const SLOT_WAIT_MS = 150_000
|
|
106
|
+
// Room for a reasoning model's thinking on top of the answer's own budget
|
|
107
|
+
export const THINKING = 1500
|
|
70
108
|
|
|
71
109
|
export function createAsk({ governor, record = () => {}, budget = { take: () => true }, slotWaitMs = SLOT_WAIT_MS }) {
|
|
72
110
|
// The gateway has been refusing this job for as long as a slot will wait: its other slots
|
|
@@ -74,10 +112,11 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
|
|
|
74
112
|
// through the Governor's backoff for half an hour
|
|
75
113
|
let unavailable = false
|
|
76
114
|
/**
|
|
77
|
-
* @param {{ task: string, tier?: string, schema: object, recipe?: string, view: string, request: string, maxOutput: number, check?: (value: any) => string[], fallback: () => any, priority?: number, signal?: AbortSignal }} slot
|
|
115
|
+
* @param {{ task: string, tier?: string, schema: object, recipe?: string, view: string, request: string, maxOutput: number, check?: (value: any) => string[], clean?: (value: any) => any, fallback: () => any, priority?: number, signal?: AbortSignal }} slot
|
|
116
|
+
* clean: tidies a parsed answer before the schema sees it (a model's nulls for absent fields)
|
|
78
117
|
* @returns {Promise<{ value: any, source: "model" | "repaired" | "default", reason?: string, calls: number }>}
|
|
79
118
|
*/
|
|
80
|
-
return async function ask({ task, tier = "budget", schema, recipe = "", view, request, maxOutput, check = () => [], fallback, priority = PRIORITY.job, signal }) {
|
|
119
|
+
return async function ask({ task, tier = "budget", schema, recipe = "", view, request, maxOutput, check = () => [], clean = (value) => value, fallback, priority = PRIORITY.job, signal }) {
|
|
81
120
|
const messages = [
|
|
82
121
|
{ role: "system", content: `${DIRECTOR_CORE}\n\n${recipe}`.trim() },
|
|
83
122
|
{ role: "user", content: `${view}\n\n${request}` },
|
|
@@ -91,7 +130,9 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
|
|
|
91
130
|
const limit = AbortSignal.timeout(slotWaitMs)
|
|
92
131
|
try {
|
|
93
132
|
calls++
|
|
94
|
-
|
|
133
|
+
// Low reasoning effort: a thinking model spends its output limit thinking otherwise,
|
|
134
|
+
// and answers with nothing (found in use: every console call ended at its 800 tokens)
|
|
135
|
+
reply = await governor.call({ model: tier, messages, response_format: { type: "json_schema", json_schema: { name: task, strict: false, schema } }, reasoning: { effort: "low" } }, { maxTokens: maxOutput + THINKING, priority, signal: signal ? AbortSignal.any([signal, limit]) : limit })
|
|
95
136
|
} catch (error) {
|
|
96
137
|
if (signal?.aborted) throw error
|
|
97
138
|
if (limit.aborted) {
|
|
@@ -100,17 +141,21 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
|
|
|
100
141
|
return { value: fallback(), source: "default", reason: "The model wasn't available for this job.", calls }
|
|
101
142
|
}
|
|
102
143
|
record({ task, tier, ms: Date.now() - started, result: `error:${error.code ?? error.status ?? "unknown"}` })
|
|
103
|
-
return { value: fallback(), source: "default", reason: `The model couldn't answer
|
|
144
|
+
return { value: fallback(), source: "default", reason: `The model couldn't answer: ${String(error.message || error.code || "unknown").replace(/\.$/, "")}.`, calls }
|
|
104
145
|
}
|
|
105
146
|
const usage = reply?.usage ?? {}
|
|
106
147
|
const content = reply?.choices?.[0]?.message?.content
|
|
107
|
-
const parsed =
|
|
108
|
-
|
|
109
|
-
|
|
148
|
+
const parsed = parseReply(content, reply?.choices?.[0]?.finish_reason)
|
|
149
|
+
if (!parsed.problem) parsed.value = clean(parsed.value)
|
|
150
|
+
const shape = parsed.problem ? [] : schemaErrors(schema, parsed.value)
|
|
151
|
+
const problems = parsed.problem ? [parsed.problem] : [...shape, ...(shape.length ? [] : check(parsed.value))]
|
|
152
|
+
// Why it was refused, never what it said: the journal holds no answer (ES-12)
|
|
153
|
+
const why = parsed.kind ?? (shape.length ? "schema" : "meaning")
|
|
154
|
+
record({ task, tier, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? `invalid:${why}` : attempt ? "repaired" : "ok" })
|
|
110
155
|
if (!problems.length) return { value: parsed.value, source: attempt ? "repaired" : "model", calls }
|
|
111
156
|
if (attempt === 0) {
|
|
112
157
|
// One repair, with the exact reasons
|
|
113
|
-
messages.push({ role: "assistant", content: String(content ?? "") }, { role: "user", content: `That answer was refused: ${problems.slice(0, 5).join("; ")}. Answer again with JSON that fits the schema, using only ids you were shown.` })
|
|
158
|
+
messages.push({ role: "assistant", content: String(content ?? "") }, { role: "user", content: `That answer was refused: ${problems.slice(0, 5).join("; ")}. Answer again with only the JSON that fits the schema, shorter if you can, using only ids you were shown. No explanation, no thinking aloud.` })
|
|
114
159
|
continue
|
|
115
160
|
}
|
|
116
161
|
return { value: fallback(), source: "default", reason: `The model's answer didn't fit, twice: ${problems[0]}.`, calls }
|