@larkup/tool-video-intelligence 0.3.14 → 0.3.26
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/README.md +19 -0
- package/dist/agent.d.ts +15 -0
- package/dist/agent.js +336 -63
- package/dist/contracts.d.ts +3 -0
- package/dist/identity-grounding.d.ts +2 -0
- package/dist/identity-grounding.js +154 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/investigation-skills.d.ts +21 -0
- package/dist/investigation-skills.js +28 -0
- package/package.json +3 -3
- package/runtime/app/services/brain.py +5 -1
- package/runtime/app/services/transcription.py +9 -1
- package/runtime/app/services/vision.py +41 -0
- package/tool.manifest.json +1 -1
package/README.md
CHANGED
|
@@ -349,3 +349,22 @@ The AWS control plane and GPU provider tests/validation run privately -- see `de
|
|
|
349
349
|
The runtime is the default path for indexed videos. Removing this package, its
|
|
350
350
|
v3 catalog record, and the optional installed-tool entry cleanly removes the
|
|
351
351
|
implementation.
|
|
352
|
+
|
|
353
|
+
### Long recordings and creator exports
|
|
354
|
+
|
|
355
|
+
For a complete question-and-answer inventory, ask the agent to use source scope,
|
|
356
|
+
enumerate, speech evidence, and `recordSet: source-questions`. Follow every
|
|
357
|
+
continuation cursor before presenting a complete result. The shared chat host
|
|
358
|
+
renders the inventory as a paginated, downloadable table; summaries do not
|
|
359
|
+
replace its rows. Keep timestamps and unanswered questions, and report any
|
|
360
|
+
incomplete source coverage. The corpus sandbox can transform mounted source
|
|
361
|
+
files with `larkup_table` or `larkup_document` for grouped Q&A, chapters, lecture
|
|
362
|
+
notes, quotes, and clip plans.
|
|
363
|
+
|
|
364
|
+
Deepgram transcription requests diarization and preserves voice labels in the
|
|
365
|
+
source evidence. A voice label is scoped to its audio chunk and does not prove
|
|
366
|
+
a person's name or identity across chunks. Use source introductions or visible
|
|
367
|
+
name labels for names and retain unknown attribution explicitly. Supplied
|
|
368
|
+
timestamped transcripts remain available through `transcriptContext` and
|
|
369
|
+
`skipTranscription`; otherwise the existing runtime uses the selected audio
|
|
370
|
+
provider rather than a separate transcription pipeline.
|
package/dist/agent.d.ts
CHANGED
|
@@ -20,6 +20,8 @@ interface InspectVideoKnowledgeInput {
|
|
|
20
20
|
interface QueryVideoEvidenceInput {
|
|
21
21
|
mediaAssetId: string;
|
|
22
22
|
query: string;
|
|
23
|
+
/** User-supplied alternatives; no expected/correct option is accepted. */
|
|
24
|
+
answerOptions?: string[];
|
|
23
25
|
/**
|
|
24
26
|
* Optional semantic instruction produced by the chat model. The evidence
|
|
25
27
|
* action still has a safe focused retrieval path when a weak model cannot
|
|
@@ -52,6 +54,16 @@ export declare const AGENT_TOOLS: ({
|
|
|
52
54
|
minLength: number;
|
|
53
55
|
maxLength: number;
|
|
54
56
|
};
|
|
57
|
+
answerOptions: {
|
|
58
|
+
type: string;
|
|
59
|
+
maxItems: number;
|
|
60
|
+
items: {
|
|
61
|
+
type: string;
|
|
62
|
+
minLength: number;
|
|
63
|
+
maxLength: number;
|
|
64
|
+
};
|
|
65
|
+
description: string;
|
|
66
|
+
};
|
|
55
67
|
investigation: {
|
|
56
68
|
type: string;
|
|
57
69
|
additionalProperties: boolean;
|
|
@@ -60,10 +72,12 @@ export declare const AGENT_TOOLS: ({
|
|
|
60
72
|
scope: {
|
|
61
73
|
type: string;
|
|
62
74
|
enum: string[];
|
|
75
|
+
description: string;
|
|
63
76
|
};
|
|
64
77
|
goal: {
|
|
65
78
|
type: string;
|
|
66
79
|
enum: string[];
|
|
80
|
+
description: string;
|
|
67
81
|
};
|
|
68
82
|
evidence: {
|
|
69
83
|
type: string;
|
|
@@ -166,6 +180,7 @@ export declare const AGENT_TOOLS: ({
|
|
|
166
180
|
type: string;
|
|
167
181
|
};
|
|
168
182
|
query?: undefined;
|
|
183
|
+
answerOptions?: undefined;
|
|
169
184
|
investigation?: undefined;
|
|
170
185
|
limit?: undefined;
|
|
171
186
|
exhaustive?: undefined;
|
package/dist/agent.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { groundVideoIdentityEvidence } from './identity-grounding.js';
|
|
1
2
|
import { VIDEO_INVESTIGATION_GUIDE } from './investigation-skills.js';
|
|
2
3
|
import { trackUsageEvent } from '@larkup/core/analytics-store';
|
|
3
4
|
const MAX_INSPECTION_CHUNK_SECS = 60;
|
|
@@ -11,7 +12,7 @@ const MAX_PARALLEL_INSPECTIONS = 4;
|
|
|
11
12
|
/** The whole evidence-query fallback shares one deadline, including re-watch. */
|
|
12
13
|
const INTERACTIVE_INSPECTION_BUDGET_MS = 40_000;
|
|
13
14
|
/** Leave part of the shared deadline for a provider-backed inspection if needed. */
|
|
14
|
-
const INTERACTIVE_REWATCH_BUDGET_MS =
|
|
15
|
+
const INTERACTIVE_REWATCH_BUDGET_MS = 30_000;
|
|
15
16
|
/** Chat actions stay inside the installed tool; the host only sees workflow roles. */
|
|
16
17
|
export const AGENT_TOOLS = [
|
|
17
18
|
{
|
|
@@ -24,15 +25,26 @@ export const AGENT_TOOLS = [
|
|
|
24
25
|
properties: {
|
|
25
26
|
mediaAssetId: { type: 'string', minLength: 1 },
|
|
26
27
|
query: { type: 'string', minLength: 1, maxLength: 2_000 },
|
|
28
|
+
answerOptions: {
|
|
29
|
+
type: 'array',
|
|
30
|
+
maxItems: 10,
|
|
31
|
+
items: { type: 'string', minLength: 1, maxLength: 500 },
|
|
32
|
+
description: 'Preserve any alternatives supplied with the question so direct readers can compare the actual candidates. Do not include an expected answer.',
|
|
33
|
+
},
|
|
27
34
|
investigation: {
|
|
28
35
|
type: 'object',
|
|
29
36
|
additionalProperties: false,
|
|
30
37
|
required: ['scope', 'goal'],
|
|
31
38
|
properties: {
|
|
32
|
-
scope: {
|
|
39
|
+
scope: {
|
|
40
|
+
type: 'string',
|
|
41
|
+
enum: ['focused', 'temporal', 'source'],
|
|
42
|
+
description: 'Search one moment, compare moments, or search the whole source. Source scope alone does not request an exhaustive inventory.',
|
|
43
|
+
},
|
|
33
44
|
goal: {
|
|
34
45
|
type: 'string',
|
|
35
46
|
enum: ['answer', 'compare', 'trace', 'resolve', 'enumerate', 'synthesize'],
|
|
47
|
+
description: 'Use compare for changes between observed states, resolve for a missing specific fact, enumerate for a complete inventory, and synthesize for an overall topic or summary.',
|
|
36
48
|
},
|
|
37
49
|
evidence: {
|
|
38
50
|
type: 'array',
|
|
@@ -93,7 +105,7 @@ export const AGENT_TOOLS = [
|
|
|
93
105
|
];
|
|
94
106
|
export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.fetch) {
|
|
95
107
|
const inspectVideoKnowledge = createInspector(fetcher);
|
|
96
|
-
|
|
108
|
+
const actions = {
|
|
97
109
|
inspectVideoKnowledge,
|
|
98
110
|
async queryVideoEvidence(input, context) {
|
|
99
111
|
if (!isValidQueryInput(input))
|
|
@@ -123,7 +135,11 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
123
135
|
// Requests that span a whole recording need deterministic pagination
|
|
124
136
|
// through the index. Callers should not need to know this tool's query
|
|
125
137
|
// planner well enough to opt into exhaustive retrieval themselves.
|
|
126
|
-
exhaustive: input.exhaustive ??
|
|
138
|
+
exhaustive: input.exhaustive ??
|
|
139
|
+
(plan.requiresBroadCoverage === true &&
|
|
140
|
+
directive.goal !== 'resolve' &&
|
|
141
|
+
directive.goal !== 'compare' &&
|
|
142
|
+
input.investigation?.goal !== 'synthesize'),
|
|
127
143
|
};
|
|
128
144
|
const durationSecs = asset.durationSecs;
|
|
129
145
|
// The compact aggregate is revision-cached and carries protocol-backed
|
|
@@ -131,9 +147,9 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
131
147
|
// apart. Load it before either answer path so even a conservative source
|
|
132
148
|
// scan retains the visibility ledger when the conversational planner
|
|
133
149
|
// chooses a broader record set than `observed`.
|
|
134
|
-
const
|
|
135
|
-
?
|
|
136
|
-
: undefined;
|
|
150
|
+
const aggregatePromise = mediaEvidence.aggregate
|
|
151
|
+
? mediaEvidence.aggregate(input.mediaAssetId)
|
|
152
|
+
: Promise.resolve(undefined);
|
|
137
153
|
// Complete inventories are a deterministic database scan, never an
|
|
138
154
|
// expanded Top-K query. The chat route follows the opaque cursor itself,
|
|
139
155
|
// so a model cannot stop early or mistake its context window for source
|
|
@@ -141,14 +157,17 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
141
157
|
if (plan.route === 'scan' && mediaEvidence.scan) {
|
|
142
158
|
const sourceInventory = focusedInput.investigation.recordSet === 'source-authored' ||
|
|
143
159
|
focusedInput.investigation.recordSet === 'source-questions';
|
|
144
|
-
const scanned = await
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
160
|
+
const [aggregate, scanned] = await Promise.all([
|
|
161
|
+
aggregatePromise,
|
|
162
|
+
mediaEvidence.scan(input.mediaAssetId, {
|
|
163
|
+
kind: sourceInventory ? 'source-inventory' : 'all-evidence',
|
|
164
|
+
cursor: input.cursor,
|
|
165
|
+
limit: input.limit,
|
|
166
|
+
...(!sourceInventory && (plan.modalities?.length ?? 0) > 0
|
|
167
|
+
? { modalities: plan.modalities }
|
|
168
|
+
: {}),
|
|
169
|
+
}),
|
|
170
|
+
]);
|
|
152
171
|
if (scanned) {
|
|
153
172
|
// A source inventory can contain headings, slides, and literal list
|
|
154
173
|
// items too. A question table must contain only source questions;
|
|
@@ -246,16 +265,40 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
246
265
|
// first so a whole-recording overview cannot displace its evidence.
|
|
247
266
|
const explicitRanges = directiveTimeRange(directive, durationSecs);
|
|
248
267
|
const explicitLookupRanges = directiveLookupRanges(directive, durationSecs);
|
|
249
|
-
const [rankedHits, explicitlyScopedHits] = await Promise.all([
|
|
268
|
+
const [rankedHits, explicitlyScopedHits, aggregate] = await Promise.all([
|
|
250
269
|
retrieve(mediaEvidence, focusedInput, plan, durationSecs),
|
|
251
270
|
explicitLookupRanges.length > 0
|
|
252
271
|
? retrieveEvidenceInRanges(mediaEvidence, focusedInput, plan, durationSecs, explicitLookupRanges)
|
|
253
272
|
: Promise.resolve([]),
|
|
273
|
+
aggregatePromise,
|
|
254
274
|
]);
|
|
255
275
|
let hits = mergeHits(explicitlyScopedHits, rankedHits, aggregate ? aggregateToHits(aggregate) : []);
|
|
276
|
+
let deliveredBySourceWideRead = false;
|
|
256
277
|
let investigation;
|
|
257
278
|
let locatedRanges = explicitRanges;
|
|
258
279
|
let assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, undefined);
|
|
280
|
+
if (!assessment.sufficient) {
|
|
281
|
+
// Targeted retrieval locates; it does not get to decide the source is
|
|
282
|
+
// silent. Ranked and scoped lookups can return nothing -- or nothing
|
|
283
|
+
// that bears on the question -- when the moment was indexed in words
|
|
284
|
+
// unlike the question, which is common across languages and for broad
|
|
285
|
+
// thematic questions. For plans that did not already read the source
|
|
286
|
+
// wide, pull a source-wide read now and merge it behind the targeted
|
|
287
|
+
// hits, so an answer-bearing record indexed differently can reach the
|
|
288
|
+
// reader instead of staying ranked away from it. This is a bounded
|
|
289
|
+
// read, not a guaranteed complete scan -- the deterministic `scan`
|
|
290
|
+
// route owns exhaustive coverage -- and it runs before narrowing to
|
|
291
|
+
// located ranges, which miss for the same reason the query did.
|
|
292
|
+
if (!needsSourceWideView(plan)) {
|
|
293
|
+
const broad = await sourceWideIndexRead(mediaEvidence, focusedInput, plan, durationSecs);
|
|
294
|
+
const before = hits.length;
|
|
295
|
+
hits = mergeHits(hits, broad);
|
|
296
|
+
deliveredBySourceWideRead = hits.length > before;
|
|
297
|
+
if (deliveredBySourceWideRead) {
|
|
298
|
+
assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, undefined);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
259
302
|
if (!assessment.sufficient) {
|
|
260
303
|
const [plannedInvestigation, semanticRanges] = await Promise.all([
|
|
261
304
|
mediaEvidence.planInvestigation?.(input.mediaAssetId, focusedInput.query, focusedInput.investigation),
|
|
@@ -282,14 +325,18 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
282
325
|
// When the index cannot answer, the agent goes and watches the moments
|
|
283
326
|
// the index pointed at rather than reporting that the source is silent.
|
|
284
327
|
if (!assessment.sufficient && plan.requiresInspectionWhenInsufficient) {
|
|
285
|
-
const targets = inspectionTargets(hits, focusedInput.query, plan, assessment, durationSecs, investigation, locatedRanges)
|
|
328
|
+
const targets = inspectionTargets(hits, focusedInput.query, plan, assessment, durationSecs, investigation, locatedRanges).map((range) => ({
|
|
329
|
+
...range,
|
|
330
|
+
// Aggregate records may span the source; an interactive read never does.
|
|
331
|
+
endSecs: Math.min(range.endSecs, range.startSecs + MAX_INSPECTION_CHUNK_SECS),
|
|
332
|
+
}));
|
|
286
333
|
// Re-reading the source directly is the cheap way to settle this, so it
|
|
287
334
|
// goes first. Dispatching a re-index below costs minutes on a cold
|
|
288
335
|
// worker and frequently outlives the turn, which is what turns an
|
|
289
336
|
// answerable question into an unconfirmed one.
|
|
290
337
|
if (targets.length > 0 && mediaEvidence.reWatch) {
|
|
291
338
|
const readings = await mediaEvidence
|
|
292
|
-
.reWatch(input.mediaAssetId, focusedInput
|
|
339
|
+
.reWatch(input.mediaAssetId, observationQuestion(focusedInput),
|
|
293
340
|
// The host reads these windows together, so a fourth costs
|
|
294
341
|
// little wall time and a progression usually needs more than two.
|
|
295
342
|
targets.slice(0, 4).map((range) => ({
|
|
@@ -300,9 +347,14 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
300
347
|
knownEntities: inspectionEntityHints(hits, plan),
|
|
301
348
|
})
|
|
302
349
|
.catch(() => []);
|
|
303
|
-
const established = readings.filter((reading) => reading.settlesQuestion && reading.found.trim());
|
|
304
|
-
|
|
305
|
-
|
|
350
|
+
const established = readings.filter((reading) => reading.settlesQuestion && reading.coverageComplete !== false && reading.found.trim());
|
|
351
|
+
const observed = readings.filter((reading) => !('error' in reading && reading.error) && reading.found.trim());
|
|
352
|
+
const paired = plan.requiresBothRanges && observed.length >= 2;
|
|
353
|
+
const partial = (plan.investigation?.goal === 'resolve' || plan.investigation?.goal === 'compare') &&
|
|
354
|
+
observed.length > 0;
|
|
355
|
+
if (established.length > 0 || paired || partial) {
|
|
356
|
+
const returnedReadings = paired || partial ? observed : established;
|
|
357
|
+
const supportingClip = returnedReadings[0].range;
|
|
306
358
|
const observedSubjects = observedSubjectsForAnswer(aggregate, focusedInput.investigation);
|
|
307
359
|
const indexedEvidence = evidenceHitsFor(hits, assessment, plan, focusedInput, durationSecs);
|
|
308
360
|
return {
|
|
@@ -312,13 +364,16 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
312
364
|
...(sourceLanguage ? { sourceLanguage } : {}),
|
|
313
365
|
evidence: indexedEvidence,
|
|
314
366
|
supportingClip,
|
|
315
|
-
ui: citationSurface(asset, context,
|
|
367
|
+
ui: citationSurface(asset, context, returnedReadings.map((reading) => ({
|
|
316
368
|
modality: 'visual',
|
|
317
369
|
timeRange: { ...reading.range, precision: 'estimated' },
|
|
318
370
|
})), supportingClip),
|
|
319
371
|
directObservation: {
|
|
320
|
-
readings:
|
|
321
|
-
rule:
|
|
372
|
+
readings: returnedReadings,
|
|
373
|
+
rule: (established.length === 0
|
|
374
|
+
? 'No individual reading settles the full request. Combine only observed facts, and keep missing subjects or attributes unresolved. '
|
|
375
|
+
: '') +
|
|
376
|
+
'These are direct readings taken by re-watching the source just now, for this ' +
|
|
322
377
|
'question. Answer from them and cite the timestamps they came from, and do not ' +
|
|
323
378
|
'report that the source fails to show something a reading here establishes. ' +
|
|
324
379
|
'Weigh them against each other and against the indexed evidence rather than ' +
|
|
@@ -333,14 +388,16 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
333
388
|
},
|
|
334
389
|
...temporalContextResult(hits, plan),
|
|
335
390
|
claimVerification: {
|
|
336
|
-
status: 'directly-established',
|
|
337
|
-
directlyEstablished:
|
|
338
|
-
rule:
|
|
391
|
+
status: established.length > 0 ? 'directly-established' : 'needs-corroboration',
|
|
392
|
+
directlyEstablished: established.length > 0,
|
|
393
|
+
rule: established.length > 0
|
|
394
|
+
? 'The source was re-watched for this question; answer from what it established.'
|
|
395
|
+
: 'These are partial direct observations. Use only their observed facts; no reading established the full requested claim. State any remaining gap.',
|
|
339
396
|
},
|
|
340
397
|
investigation: {
|
|
341
398
|
answerPath: 'rag+rewatch',
|
|
342
399
|
responseTimeMs: Date.now() - startedAt,
|
|
343
|
-
analyzedRanges:
|
|
400
|
+
analyzedRanges: returnedReadings.map((reading) => reading.range),
|
|
344
401
|
broadCoverage: plan.requiresBroadCoverage === true,
|
|
345
402
|
coverage: investigation?.coverage,
|
|
346
403
|
directive: investigationDirectiveForOutput(focusedInput.investigation),
|
|
@@ -440,7 +497,7 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
440
497
|
? 'directly-established'
|
|
441
498
|
: 'needs-corroboration',
|
|
442
499
|
directlyEstablished: assessment.sufficient && !assessment.establishedByTrail,
|
|
443
|
-
rule: answeringRule(assessment, plan, analysisUnavailable),
|
|
500
|
+
rule: answeringRule(assessment, plan, analysisUnavailable, deliveredBySourceWideRead),
|
|
444
501
|
},
|
|
445
502
|
investigation: {
|
|
446
503
|
answerPath,
|
|
@@ -458,6 +515,12 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
458
515
|
...temporalContextResult(hits, plan),
|
|
459
516
|
};
|
|
460
517
|
},
|
|
518
|
+
};
|
|
519
|
+
return Object.assign(client, {
|
|
520
|
+
...actions,
|
|
521
|
+
async queryVideoEvidence(input, context) {
|
|
522
|
+
return groundVideoIdentityEvidence(await actions.queryVideoEvidence(input, context));
|
|
523
|
+
},
|
|
461
524
|
});
|
|
462
525
|
}
|
|
463
526
|
/**
|
|
@@ -471,6 +534,22 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
|
|
|
471
534
|
* matter.
|
|
472
535
|
*/
|
|
473
536
|
function windowObjective(plan) {
|
|
537
|
+
if (plan.investigation?.goal === 'compare') {
|
|
538
|
+
return ('For each requested state or label visible in this window, record the requested subject and property at that time. ' +
|
|
539
|
+
'List the observed states in source timestamp order, with a timestamp for each. A state seen BEFORE the described initial state cannot establish what happens AFTER it. ' +
|
|
540
|
+
'Include later appearances of the same grounded subject instead of stopping at the first similar appearance. ' +
|
|
541
|
+
'Record a visible state even when the other comparison state lies outside this window. ' +
|
|
542
|
+
'Keep the subject binding grounded in source continuity or independently established identity. ' +
|
|
543
|
+
'The property being compared may change: use initial appearance to locate the subject, not to require the old property in every later state. ' +
|
|
544
|
+
'Describe the later state as visibly shown even if the question uses an imprecise object category. ' +
|
|
545
|
+
'Separate what is visible here from any unobserved transition, and never substitute a different subject.');
|
|
546
|
+
}
|
|
547
|
+
if (plan.investigation?.goal === 'resolve') {
|
|
548
|
+
return ('Resolve the exact requested detail for the subject matching every qualifier in the question. ' +
|
|
549
|
+
'Do not substitute a similar person with conflicting clothing, action, or position. ' +
|
|
550
|
+
'For monochrome material, report the visible grayscale appearance separately from any original hue that cannot be recovered; ' +
|
|
551
|
+
'an unknown original hue does not erase an observable light or dark appearance.');
|
|
552
|
+
}
|
|
474
553
|
if (plan.subjectName) {
|
|
475
554
|
return `Which visible person is "${plan.subjectName}", and what the question asks about them.`;
|
|
476
555
|
}
|
|
@@ -499,7 +578,22 @@ function evidenceHitsFor(hits, assessment, plan, input, durationSecs) {
|
|
|
499
578
|
// subject to the local, merely described subject. This relies only on the
|
|
500
579
|
// typed time boundary, so it applies to any language and kind of media.
|
|
501
580
|
const localAnchor = explicitlyRequestedMomentEvidence(hits, plan, durationSecs);
|
|
502
|
-
|
|
581
|
+
const selected = selectAnswerEvidence(hits, assessment, plan, input, durationSecs);
|
|
582
|
+
const needsVisualSource = plan.modalities?.includes('visual') ||
|
|
583
|
+
plan.kinds.some((kind) => ['visual-fact', 'person-attribute'].includes(kind));
|
|
584
|
+
// Reconciled accounts orient the answer; they must not consume every slot
|
|
585
|
+
// when the requested detail is present in a primary visual observation.
|
|
586
|
+
const primary = !assessment.needsBreadth &&
|
|
587
|
+
needsVisualSource &&
|
|
588
|
+
!selected.some((hit) => hit.evidence.modality === 'visual') &&
|
|
589
|
+
!selected.some((hit) => isDirectVerdict(hit, input.query, plan))
|
|
590
|
+
? hits
|
|
591
|
+
.filter((hit) => hit.evidence.modality === 'visual' && isAccountOfMoment(hit))
|
|
592
|
+
.slice(0, 4)
|
|
593
|
+
: [];
|
|
594
|
+
const combined = mergeHits(localAnchor, primary, selected).filter((hit) => !plan.modalities?.length ||
|
|
595
|
+
plan.modalities.some((modality) => modality === hit.evidence.modality));
|
|
596
|
+
return (primary.length > 0 ? combined.slice(0, Math.min(input.limit ?? 36, 48)) : combined).map((hit) => toEvidence(hit, plan));
|
|
503
597
|
}
|
|
504
598
|
function explicitlyRequestedMomentEvidence(hits, plan, durationSecs) {
|
|
505
599
|
const requestedRanges = directiveTimeRange(plan.investigation, durationSecs);
|
|
@@ -673,12 +767,19 @@ function aggregateToHits(aggregate) {
|
|
|
673
767
|
];
|
|
674
768
|
}
|
|
675
769
|
async function retrieve(mediaEvidence, input, plan, durationSecs) {
|
|
676
|
-
const options = {
|
|
770
|
+
const options = {
|
|
771
|
+
queryPlan: plan,
|
|
772
|
+
videoDurationSecs: durationSecs,
|
|
773
|
+
...(plan.modalities?.length ? { modalities: plan.modalities } : {}),
|
|
774
|
+
};
|
|
677
775
|
// A named person and an identity anchor are extra retrieval handles for the
|
|
678
776
|
// same index, not separate strategies. Issuing them alongside the ranked
|
|
679
777
|
// lookup costs one round trip instead of three.
|
|
680
778
|
const crossEvidence = isCrossEvidenceClaim(plan);
|
|
681
|
-
const
|
|
779
|
+
const needsVisualSource = crossEvidence ||
|
|
780
|
+
plan.modalities?.includes('visual') ||
|
|
781
|
+
plan.kinds.some((kind) => ['visual-fact', 'person-attribute'].includes(kind));
|
|
782
|
+
const [ranked, subjectHits, identityHits, visualHits, computedHits, alternatives] = await Promise.all([
|
|
682
783
|
mediaEvidence.search(input.mediaAssetId, input.query, 16, options),
|
|
683
784
|
plan.subjectName
|
|
684
785
|
? mediaEvidence.search(input.mediaAssetId, plan.subjectName, 12, options)
|
|
@@ -686,7 +787,7 @@ async function retrieve(mediaEvidence, input, plan, durationSecs) {
|
|
|
686
787
|
plan.requiresIdentityContext
|
|
687
788
|
? mediaEvidence.search(input.mediaAssetId, 'participant names roster lineup name labels captions speaker identities', 8, options)
|
|
688
789
|
: Promise.resolve([]),
|
|
689
|
-
|
|
790
|
+
needsVisualSource
|
|
690
791
|
? mediaEvidence.search(input.mediaAssetId, input.query, 16, {
|
|
691
792
|
...options,
|
|
692
793
|
modalities: ['visual'],
|
|
@@ -698,9 +799,31 @@ async function retrieve(mediaEvidence, input, plan, durationSecs) {
|
|
|
698
799
|
modalities: ['computed'],
|
|
699
800
|
})
|
|
700
801
|
: Promise.resolve([]),
|
|
802
|
+
Promise.all((input.answerOptions ?? []).map((option) => mediaEvidence.search(input.mediaAssetId, option, Math.max(1, Math.floor(12 / (input.answerOptions?.length || 1))), options))),
|
|
701
803
|
]);
|
|
804
|
+
// Give every supplied alternative the same bounded source lookup. Search
|
|
805
|
+
// similarity locates possible support; the evidence contract still verifies it.
|
|
806
|
+
const alternativeHits = alternatives.flat();
|
|
807
|
+
const priority = alternativeHits.length > 0 ? ranked.slice(0, 8) : ranked;
|
|
702
808
|
if (!needsSourceWideView(plan)) {
|
|
703
|
-
return mergeHits(
|
|
809
|
+
return mergeHits(priority, alternativeHits, visualHits, computedHits, ranked, subjectHits, identityHits);
|
|
810
|
+
}
|
|
811
|
+
if (plan.investigation?.goal === 'synthesize' &&
|
|
812
|
+
!input.exhaustive &&
|
|
813
|
+
durationSecs &&
|
|
814
|
+
durationSecs > 0) {
|
|
815
|
+
const primary = (plan.modalities ?? []).filter((modality) => modality !== 'computed');
|
|
816
|
+
const groups = await Promise.all(Array.from({ length: 8 }, (_, index) => mediaEvidence.search(input.mediaAssetId, '', 8, {
|
|
817
|
+
...options,
|
|
818
|
+
...(primary.length ? { modalities: primary } : {}),
|
|
819
|
+
timeRange: {
|
|
820
|
+
startSecs: (durationSecs * index) / 8,
|
|
821
|
+
endSecs: (durationSecs * (index + 1)) / 8,
|
|
822
|
+
},
|
|
823
|
+
minimumRangeDistanceSecs: 2,
|
|
824
|
+
})));
|
|
825
|
+
const samples = groups.flat().filter((hit) => !spansWholeSource(hit, durationSecs));
|
|
826
|
+
return mergeHits(priority, alternativeHits, samples, visualHits, computedHits, ranked, subjectHits);
|
|
704
827
|
}
|
|
705
828
|
// A question about breadth or order cannot be served by the top matches
|
|
706
829
|
// alone: the relevant moment may share no words with the question. Scanning
|
|
@@ -719,6 +842,14 @@ async function retrieve(mediaEvidence, input, plan, durationSecs) {
|
|
|
719
842
|
// the whole timeline with near-identical records from that one minute.
|
|
720
843
|
minimumRangeDistanceSecs: 2,
|
|
721
844
|
});
|
|
845
|
+
const authoredModalities = (plan.modalities ?? []).filter((modality) => modality === 'transcript' || modality === 'ocr');
|
|
846
|
+
const sourceAuthored = plan.kinds.includes('state-change') && authoredModalities.length > 0
|
|
847
|
+
? await mediaEvidence.search(input.mediaAssetId, '', 2_000, {
|
|
848
|
+
...options,
|
|
849
|
+
modalities: authoredModalities,
|
|
850
|
+
minimumRangeDistanceSecs: 0,
|
|
851
|
+
})
|
|
852
|
+
: [];
|
|
722
853
|
const sourceTimeline = transitionTimeline && timeline.length < CORROBORATION_FLOOR
|
|
723
854
|
? await mediaEvidence.search(input.mediaAssetId, '', input.exhaustive ? 2_000 : 500, {
|
|
724
855
|
...options,
|
|
@@ -726,8 +857,26 @@ async function retrieve(mediaEvidence, input, plan, durationSecs) {
|
|
|
726
857
|
})
|
|
727
858
|
: timeline;
|
|
728
859
|
return plan.requiresIdentityContext
|
|
729
|
-
? mergeHits(ranked.slice(0, 3), identityHits.slice(0, 3), visualHits, computedHits, ranked, subjectHits, sourceTimeline)
|
|
730
|
-
: mergeHits(
|
|
860
|
+
? mergeHits(ranked.slice(0, 3), alternativeHits, identityHits.slice(0, 3), visualHits, computedHits, ranked, subjectHits, sourceTimeline, sourceAuthored)
|
|
861
|
+
: mergeHits(priority, alternativeHits, visualHits, computedHits, ranked, subjectHits, sourceTimeline, sourceAuthored);
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Last-resort retrieval: an unranked, source-wide read of the index.
|
|
865
|
+
*
|
|
866
|
+
* Used only when targeted retrieval returned nothing. It issues the empty
|
|
867
|
+
* query so matching cannot exclude a moment described in words unlike the
|
|
868
|
+
* question, and spaces repeated readings so one richly re-inspected minute
|
|
869
|
+
* cannot fill the whole result. Whatever the index holds for this source is
|
|
870
|
+
* returned in time order for the reader to synthesize; an empty return here
|
|
871
|
+
* means the index itself is empty, which is the only case the caller then
|
|
872
|
+
* treats as a genuinely silent source.
|
|
873
|
+
*/
|
|
874
|
+
async function sourceWideIndexRead(mediaEvidence, input, plan, durationSecs) {
|
|
875
|
+
return mediaEvidence.search(input.mediaAssetId, '', input.exhaustive ? 2_000 : 500, {
|
|
876
|
+
queryPlan: plan,
|
|
877
|
+
videoDurationSecs: durationSecs,
|
|
878
|
+
minimumRangeDistanceSecs: 2,
|
|
879
|
+
});
|
|
731
880
|
}
|
|
732
881
|
/**
|
|
733
882
|
* Fetch observations emitted by the immediately preceding live inspection.
|
|
@@ -769,9 +918,17 @@ function needsSourceWideView(plan) {
|
|
|
769
918
|
plan.kinds.includes('outcome'));
|
|
770
919
|
}
|
|
771
920
|
function assessEvidence(hits, question, plan, durationSecs, investigation, watched = { ranges: [], since: '' }) {
|
|
772
|
-
const
|
|
773
|
-
|
|
774
|
-
|
|
921
|
+
const requestedModalities = plan.modalities;
|
|
922
|
+
if (requestedModalities?.length) {
|
|
923
|
+
hits = hits.filter((hit) => requestedModalities.some((modality) => modality === hit.evidence.modality));
|
|
924
|
+
}
|
|
925
|
+
// Source scope can mean searching everywhere for one missing detail.
|
|
926
|
+
// Indexed coverage does not establish that detail or a requested comparison.
|
|
927
|
+
const detailUnresolved = plan.investigation?.goal === 'resolve' || plan.investigation?.goal === 'compare';
|
|
928
|
+
const needsBreadth = !detailUnresolved &&
|
|
929
|
+
(plan.requiresBroadCoverage === true ||
|
|
930
|
+
plan.kinds.includes('coverage') ||
|
|
931
|
+
plan.kinds.includes('state-change'));
|
|
775
932
|
const usable = hits.filter((hit) => !hit.conflict &&
|
|
776
933
|
['transcript', 'ocr', 'visual', 'computed'].includes(hit.evidence.modality));
|
|
777
934
|
if (needsBreadth) {
|
|
@@ -811,9 +968,7 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
|
|
|
811
968
|
.filter((hit) => !spansWholeSource(hit, durationSecs) && isAccountOfMoment(hit))
|
|
812
969
|
.map((hit) => Math.floor(hit.evidence.timeRange.startSecs / 15))).size;
|
|
813
970
|
const sequenceReady = !plan.kinds.includes('state-change') || distinctMoments >= 3;
|
|
814
|
-
|
|
815
|
-
distinctMoments >= 3 &&
|
|
816
|
-
answerBearing.every((hit) => hit.evidence.source?.provider === 'video-intelligence-index');
|
|
971
|
+
// Index provenance does not prove source-wide temporal coverage.
|
|
817
972
|
return {
|
|
818
973
|
needsBreadth,
|
|
819
974
|
coverageRatio,
|
|
@@ -827,14 +982,25 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
|
|
|
827
982
|
? answerBearing.length > 0
|
|
828
983
|
: plan.kinds.includes('evaluation')
|
|
829
984
|
? evaluationEvidenceReady(answerBearing)
|
|
830
|
-
:
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
sequenceReady),
|
|
985
|
+
: answerBearing.length >= 3 &&
|
|
986
|
+
coverageRatio >= 0.6 &&
|
|
987
|
+
hierarchyReady &&
|
|
988
|
+
sequenceReady,
|
|
835
989
|
};
|
|
836
990
|
}
|
|
837
991
|
const direct = answerEstablishedHits(hits, question, plan, watched);
|
|
992
|
+
// A resolve directive records an outstanding evidence gap. A relevant
|
|
993
|
+
// indexed scene locates that gap; only a question-specific observation can
|
|
994
|
+
// close it. Do not let generic summaries or retrieval scores close it again.
|
|
995
|
+
if (plan.investigation?.goal === 'resolve' || plan.investigation?.goal === 'compare') {
|
|
996
|
+
return {
|
|
997
|
+
needsBreadth,
|
|
998
|
+
coverageRatio: 1,
|
|
999
|
+
established: direct,
|
|
1000
|
+
corroborating: usable.filter(isAccountOfMoment),
|
|
1001
|
+
sufficient: direct.length > 0,
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
838
1004
|
const reconciled = direct.length === 0 ? indexedReconciledAnswerHits(hits, plan, durationSecs) : [];
|
|
839
1005
|
const trail = direct.length === 0 && reconciled.length === 0 && isCrossEvidenceClaim(plan)
|
|
840
1006
|
? indexedCrossEvidenceTrail(hits, durationSecs, plan)
|
|
@@ -1126,6 +1292,18 @@ function inventoryContext(text) {
|
|
|
1126
1292
|
function temporalContextResult(hits, plan) {
|
|
1127
1293
|
if (!plan.kinds.includes('outcome') && !plan.kinds.includes('state-change'))
|
|
1128
1294
|
return {};
|
|
1295
|
+
const sourceReadings = plan.kinds.includes('state-change')
|
|
1296
|
+
? chronological(hits)
|
|
1297
|
+
.filter((hit) => ['transcript', 'ocr'].includes(hit.evidence.modality))
|
|
1298
|
+
.slice(0, 2_000)
|
|
1299
|
+
.map((hit) => ({
|
|
1300
|
+
id: hit.evidence.id,
|
|
1301
|
+
modality: hit.evidence.modality,
|
|
1302
|
+
atSecs: hit.evidence.timeRange.startSecs,
|
|
1303
|
+
endSecs: hit.evidence.timeRange.endSecs,
|
|
1304
|
+
text: evidenceText(hit.evidence.payload),
|
|
1305
|
+
}))
|
|
1306
|
+
: [];
|
|
1129
1307
|
const readings = chronological(temporalSequenceHits(hits))
|
|
1130
1308
|
.filter((hit) => {
|
|
1131
1309
|
const text = evidenceText(hit.evidence.payload).trim();
|
|
@@ -1142,12 +1320,15 @@ function temporalContextResult(hits, plan) {
|
|
|
1142
1320
|
atSecs: hit.evidence.timeRange.startSecs,
|
|
1143
1321
|
text: evidenceText(hit.evidence.payload).slice(0, 700),
|
|
1144
1322
|
}));
|
|
1145
|
-
if (readings.length === 0)
|
|
1323
|
+
if (readings.length === 0 && sourceReadings.length === 0)
|
|
1146
1324
|
return {};
|
|
1147
1325
|
return {
|
|
1148
1326
|
temporalContext: {
|
|
1149
1327
|
readings,
|
|
1150
|
-
|
|
1328
|
+
sourceReadings,
|
|
1329
|
+
sourceReadingsLimitReached: sourceReadings.length === 2_000,
|
|
1330
|
+
rule: 'Compare original sourceReadings with synthesized readings; a later summary must not erase an earlier introduction. A mentioned concept is not necessarily the requested event; identify the event meaning before ordering it. The source-reading retrieval cap does not prove exhaustive coverage. ' +
|
|
1331
|
+
'Read the timestamped states as a trajectory. Earlier and later counters can belong to ' +
|
|
1151
1332
|
'different scopes: a reset or a change in labels, unit, or scale is a scope boundary. ' +
|
|
1152
1333
|
'Resolve the ending state of the sequence relevant to the question from its changes and ' +
|
|
1153
1334
|
'labels. Within one uninterrupted scope, an unlabeled state inherits the nearest earlier ' +
|
|
@@ -1334,6 +1515,23 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1334
1515
|
: plan.requiresBothRanges || plan.kinds.includes('outcome')
|
|
1335
1516
|
? 3
|
|
1336
1517
|
: 2;
|
|
1518
|
+
const requestedScope = directiveTimeRange(plan.investigation, durationSecs);
|
|
1519
|
+
if (requestedScope.length > 0) {
|
|
1520
|
+
// An explicit source range bounds every inspection, including fallback
|
|
1521
|
+
// looks. Similar subjects elsewhere cannot establish this scene's detail.
|
|
1522
|
+
const chunks = requestedScope.flatMap((range) => splitRange(range.startSecs, range.endSecs, MAX_INSPECTION_CHUNK_SECS));
|
|
1523
|
+
if (plan.requiresBothRanges && !assessment.needsBreadth && chunks.length > 1) {
|
|
1524
|
+
const last = requestedScope[requestedScope.length - 1];
|
|
1525
|
+
return uniqueRanges([
|
|
1526
|
+
chunks[0],
|
|
1527
|
+
{
|
|
1528
|
+
startSecs: Math.max(last.startSecs, last.endSecs - MAX_INSPECTION_CHUNK_SECS),
|
|
1529
|
+
endSecs: last.endSecs,
|
|
1530
|
+
},
|
|
1531
|
+
]);
|
|
1532
|
+
}
|
|
1533
|
+
return evenlySpaced(chunks, budget);
|
|
1534
|
+
}
|
|
1337
1535
|
const fromHits = rangesAroundHits(hits, durationSecs, budget * 2);
|
|
1338
1536
|
const fromHierarchy = (investigation?.candidateRanges ?? []).map((range) => ({
|
|
1339
1537
|
startSecs: Math.max(0, range.startSecs),
|
|
@@ -1344,7 +1542,8 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1344
1542
|
// closing moments often resemble it least -- they may show a result with
|
|
1345
1543
|
// none of the question's words. Putting the ending first is what the word
|
|
1346
1544
|
// "conclusion" means for any recording, not a fact about its subject.
|
|
1347
|
-
const
|
|
1545
|
+
const seeksClosing = plan.kinds.includes('outcome') && plan.investigation?.goal !== 'resolve';
|
|
1546
|
+
const closing = seeksClosing ? closingRanges(durationSecs) : [];
|
|
1348
1547
|
// A question about how something changed is answered at the moments it
|
|
1349
1548
|
// changed, and the index already recorded where those are. Aiming there beats
|
|
1350
1549
|
// an even spread, which lands between the transitions and reports the states
|
|
@@ -1352,7 +1551,7 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1352
1551
|
const transitions = plan.kinds.includes('state-change')
|
|
1353
1552
|
? // An account of the whole progression needs every moment it moved.
|
|
1354
1553
|
outcomeTransitionRanges(hits, durationSecs, { limit: budget, lateOnly: false })
|
|
1355
|
-
:
|
|
1554
|
+
: seeksClosing
|
|
1356
1555
|
? outcomeTransitionRanges(hits, durationSecs, { limit: 1 })
|
|
1357
1556
|
: [];
|
|
1358
1557
|
// For a conclusion, a located window inside the closing phase beats the
|
|
@@ -1386,7 +1585,7 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1386
1585
|
endSecs: Math.min(durationSecs ?? hit.evidence.timeRange.endSecs + TARGET_PADDING_SECS, hit.evidence.timeRange.endSecs + TARGET_PADDING_SECS),
|
|
1387
1586
|
}))
|
|
1388
1587
|
: [];
|
|
1389
|
-
const locatedFirst =
|
|
1588
|
+
const locatedFirst = seeksClosing && phase
|
|
1390
1589
|
? [
|
|
1391
1590
|
...closing.slice(0, 1),
|
|
1392
1591
|
...transitions,
|
|
@@ -1407,7 +1606,8 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1407
1606
|
// An index with nothing to say about the question is the strongest
|
|
1408
1607
|
// reason to go and watch, not a reason to stop. With no moment to aim
|
|
1409
1608
|
// at, sample the source instead of returning empty-handed.
|
|
1410
|
-
|
|
1609
|
+
const selected = (candidates.length > 0 ? candidates : evenlySpacedAnchors(durationSecs, budget)).slice(0, budget);
|
|
1610
|
+
return straddleComparison(selected, candidates, plan, durationSecs, budget);
|
|
1411
1611
|
}
|
|
1412
1612
|
// Breadth needs the looks spread over the source rather than clustered on
|
|
1413
1613
|
// whichever part retrieval happened to rank highest, so gaps in the index
|
|
@@ -1417,7 +1617,48 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
|
|
|
1417
1617
|
const spread = evenlySpaced(uniqueRanges([...candidates, ...evenlySpacedAnchors(durationSecs, budget)])
|
|
1418
1618
|
.filter((range) => !transitions.some((moment) => moment.startSecs === range.startSecs))
|
|
1419
1619
|
.sort((left, right) => left.startSecs - right.startSecs), Math.max(1, budget - transitions.length));
|
|
1420
|
-
return uniqueRanges([...transitions, ...spread]).slice(0, budget);
|
|
1620
|
+
return straddleComparison(uniqueRanges([...transitions, ...spread]).slice(0, budget), candidates, plan, durationSecs, budget);
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* A comparison asks about two moments the question itself separates in time --
|
|
1624
|
+
* "what changed from X to Y". Retrieval ranks the more quotable side higher, so
|
|
1625
|
+
* a small inspection budget can spend every look on one side and never watch the
|
|
1626
|
+
* other state; the change then cannot be seen and the turn abstains. When a plan
|
|
1627
|
+
* needs both ranges but every chosen window landed on one side of the source,
|
|
1628
|
+
* pull the strongest window from the missing side into the budget. This is a
|
|
1629
|
+
* generic timeline property of any paired-state question, not an assumption
|
|
1630
|
+
* about the recording's subject, and leaves single-range (focused) questions,
|
|
1631
|
+
* which do not require both ranges, untouched.
|
|
1632
|
+
*/
|
|
1633
|
+
function straddleComparison(selected, pool, plan, durationSecs, budget) {
|
|
1634
|
+
if (!plan.requiresBothRanges ||
|
|
1635
|
+
plan.investigation?.timeRange !== undefined ||
|
|
1636
|
+
plan.kinds.includes('outcome') ||
|
|
1637
|
+
!durationSecs ||
|
|
1638
|
+
!Number.isFinite(durationSecs) ||
|
|
1639
|
+
durationSecs <= 0 ||
|
|
1640
|
+
budget < 2 ||
|
|
1641
|
+
selected.length === 0) {
|
|
1642
|
+
return selected;
|
|
1643
|
+
}
|
|
1644
|
+
const mid = durationSecs / 2;
|
|
1645
|
+
const isEarly = (range) => range.startSecs < mid;
|
|
1646
|
+
// Already covers both halves -- the comparison can see both states.
|
|
1647
|
+
if (selected.some(isEarly) && selected.some((range) => !isEarly(range)))
|
|
1648
|
+
return selected;
|
|
1649
|
+
const haveEarly = selected.some(isEarly);
|
|
1650
|
+
const fromMissingSide = pool
|
|
1651
|
+
.filter((range) => (haveEarly ? !isEarly(range) : isEarly(range)))
|
|
1652
|
+
// Prefer the window farthest from the cluster: the opposite extreme is the
|
|
1653
|
+
// likeliest place the paired state lives.
|
|
1654
|
+
.sort((left, right) => haveEarly ? right.startSecs - left.startSecs : left.startSecs - right.startSecs)[0];
|
|
1655
|
+
// Both states may occur in one local scene. A missing indexed anchor
|
|
1656
|
+
// does not justify replacing it with an unrelated opening or ending.
|
|
1657
|
+
if (!fromMissingSide)
|
|
1658
|
+
return selected;
|
|
1659
|
+
const opposite = fromMissingSide;
|
|
1660
|
+
// Keep the strongest clustered windows and give one look to the missing side.
|
|
1661
|
+
return uniqueRanges([...selected.slice(0, Math.max(1, budget - 1)), opposite]).slice(0, budget);
|
|
1421
1662
|
}
|
|
1422
1663
|
function directiveTimeRange(directive, durationSecs) {
|
|
1423
1664
|
const requested = directive?.timeRange;
|
|
@@ -1577,7 +1818,7 @@ async function inspectRanges(options) {
|
|
|
1577
1818
|
endSecs: range.endSecs,
|
|
1578
1819
|
purpose: inspectionPurpose(plan.kinds),
|
|
1579
1820
|
queryId: stableQueryId(input.query),
|
|
1580
|
-
question: input
|
|
1821
|
+
question: observationQuestion(input),
|
|
1581
1822
|
maxFrames: plan.kinds.includes('state-change')
|
|
1582
1823
|
? 24
|
|
1583
1824
|
: plan.kinds.includes('person-attribute') || plan.requiresIdentityContext
|
|
@@ -1719,11 +1960,12 @@ function selectAnswerEvidence(hits, assessment, plan, input, durationSecs) {
|
|
|
1719
1960
|
const cursor = Math.min(Math.max(0, input.cursor ?? 0), ordered.length);
|
|
1720
1961
|
return ordered.slice(cursor, cursor + limit);
|
|
1721
1962
|
}
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1963
|
+
const ordered = chronological(assessment.established);
|
|
1964
|
+
if (ordered.length <= limit)
|
|
1965
|
+
return ordered;
|
|
1966
|
+
// Early direct claims must not crowd the closing source out of a synopsis.
|
|
1967
|
+
const direct = evenlySpaced(ordered.filter((hit) => /Claim verdict:\s*direct/i.test(evidenceText(hit.evidence.payload))), Math.floor(limit / 3));
|
|
1968
|
+
return chronological(mergeHits(direct, evenlySpaced(ordered, limit - direct.length)));
|
|
1727
1969
|
}
|
|
1728
1970
|
const limit = Math.min(input.limit ?? (plan.requiresBothRanges || isCrossEvidenceClaim(plan) ? 12 : 8), 12);
|
|
1729
1971
|
const requestedRanges = directiveTimeRange(plan.investigation, durationSecs);
|
|
@@ -1935,7 +2177,7 @@ function identityAnchorNames(hits) {
|
|
|
1935
2177
|
.filter((name) => Boolean(name));
|
|
1936
2178
|
});
|
|
1937
2179
|
}
|
|
1938
|
-
function answeringRule(assessment, plan, analysisUnavailable) {
|
|
2180
|
+
function answeringRule(assessment, plan, analysisUnavailable, deliveredBySourceWideRead = false) {
|
|
1939
2181
|
const hasTrail = assessment.corroborating.length >= CORROBORATION_FLOOR;
|
|
1940
2182
|
if (plan.requiresIdentityContext === true &&
|
|
1941
2183
|
!plan.subjectName &&
|
|
@@ -1964,6 +2206,14 @@ function answeringRule(assessment, plan, analysisUnavailable) {
|
|
|
1964
2206
|
// explicit about how far it goes.
|
|
1965
2207
|
return 'No single observation states this outright, which is expected for a claim of this shape. Read across the returned observations in time order and give the answer they lead to, with the timestamps it rests on and how confident you are. Do not say the source does not show this -- say what the observations establish and where they stop short.';
|
|
1966
2208
|
}
|
|
2209
|
+
if (!assessment.sufficient && deliveredBySourceWideRead) {
|
|
2210
|
+
// Targeted retrieval returned nothing usable, so the evidence is a broad
|
|
2211
|
+
// read across the whole source. That the index holds material does not make
|
|
2212
|
+
// it answer the question -- so the reader weighs it rather than being told
|
|
2213
|
+
// to abstain outright. This sits after the identity and attribute guards so
|
|
2214
|
+
// those stronger constraints still govern who a detail may be attached to.
|
|
2215
|
+
return 'Targeted retrieval returned nothing matching the question, so these are a broad read of the index across the whole source rather than question-scoped hits. Judge whether they actually answer the question. If they do, give the best-supported answer with the timestamps it rests on and how confident you are -- for an overall topic weigh what recurs across the source, for a specific detail use the observations of the requested moment. If they only touch the topic without settling it, say what they establish and what remains unshown. Do not treat a record as the answer merely because it was indexed, and do not report the source as silent when it was not read.';
|
|
2216
|
+
}
|
|
1967
2217
|
if (!assessment.sufficient) {
|
|
1968
2218
|
return 'The returned evidence does not settle this. Say which part is established and which part the source did not show, rather than inferring the rest.';
|
|
1969
2219
|
}
|
|
@@ -1972,9 +2222,17 @@ function answeringRule(assessment, plan, analysisUnavailable) {
|
|
|
1972
2222
|
return 'These are the frame-grounded visible-subject observations retained across the source. Include every returned named and unnamed subject with its observed times. The list is complete for the active observation ledger, but sampled intervals do not prove that nobody appeared between observations; never turn an omitted or unsampled moment into an absence claim.';
|
|
1973
2223
|
}
|
|
1974
2224
|
return plan.kinds.includes('state-change')
|
|
1975
|
-
? 'These are timestamped source observations selected across the video. Give the account in their order, keep their timestamps for specific claims, and say where the source is silent rather than filling the gap.'
|
|
2225
|
+
? 'These are timestamped source observations selected across the video. Give the account in their order, keep their timestamps for specific claims, and say where the source is silent rather than filling the gap. When the question asks for an order, read what it asks is being ordered: if it asks when each thing is introduced, presented, or mentioned, rank by the timestamp of its FIRST mention, not by where it is later explained in most depth or repeated, so a brief early mention precedes a detailed later treatment; if it asks the order in which events happen or occur, rank by when each occurs on the source clock, and note that something being spoken about is not the same as it occurring.'
|
|
1976
2226
|
: 'The evidence is distributed across the source. Synthesize the requested complete list or overview, deduplicate repeated items, preserve timestamps for specific claims, and state any explicit coverage limitation without exposing the evidence-gathering process.';
|
|
1977
2227
|
}
|
|
2228
|
+
if (plan.kinds.includes('visual-fact') || plan.kinds.includes('exact-ocr')) {
|
|
2229
|
+
// Precision questions -- a colour, a worn item, on-screen text, which of
|
|
2230
|
+
// two objects is present -- are settled by what the frame shows, not by
|
|
2231
|
+
// what is said. Reading the attribute off the narration, or off a frame
|
|
2232
|
+
// adjacent to the asked-for moment, is the recurring cause of hat/glasses,
|
|
2233
|
+
// colour, and pattern errors.
|
|
2234
|
+
return 'This is a visual detail. Read the asked-for attribute -- colour, worn item, on-screen text, pattern, or which object is present -- directly off the observations of the requested moment, not from what is spoken: narration mentioning something does not fix its on-screen appearance. Where readings of the same moment disagree, prefer the detail that recurs across them and the nearest on-screen label or text. Give the specific observed value rather than a category, and say plainly if the moment does not show it clearly instead of guessing the most likely option.';
|
|
2235
|
+
}
|
|
1978
2236
|
return 'Answer only from the returned source evidence.';
|
|
1979
2237
|
}
|
|
1980
2238
|
function chronological(hits) {
|
|
@@ -2179,6 +2437,8 @@ function answerEstablishedHits(hits, question, plan, watched = { ranges: [], sin
|
|
|
2179
2437
|
const accounts = fromWatching.filter(isAccountOfMoment);
|
|
2180
2438
|
if (accounts.length > 0)
|
|
2181
2439
|
return [...accounts, ...fromWatching.filter((hit) => !isAccountOfMoment(hit))];
|
|
2440
|
+
if (plan.investigation?.goal === 'resolve')
|
|
2441
|
+
return [];
|
|
2182
2442
|
// Direct source observations already materialized during indexing should
|
|
2183
2443
|
// answer straightforward speech, visible-text, and visual-fact questions
|
|
2184
2444
|
// immediately. Aggregates, comparisons, identity attribution, and
|
|
@@ -2408,11 +2668,24 @@ function focusQuestion(question, fileName) {
|
|
|
2408
2668
|
.trim();
|
|
2409
2669
|
return focused || normalized;
|
|
2410
2670
|
}
|
|
2671
|
+
function observationQuestion(input) {
|
|
2672
|
+
if (!input.answerOptions?.length)
|
|
2673
|
+
return input.query;
|
|
2674
|
+
return (input.query +
|
|
2675
|
+
'\nAnswer alternatives supplied with the question:\n' +
|
|
2676
|
+
input.answerOptions
|
|
2677
|
+
.map((option, index) => /^[A-Z][.)]\s/.test(option) ? option : `${String.fromCharCode(65 + index)}. ${option}`)
|
|
2678
|
+
.join('\n'));
|
|
2679
|
+
}
|
|
2411
2680
|
function isValidQueryInput(input) {
|
|
2412
2681
|
return (typeof input.mediaAssetId === 'string' &&
|
|
2413
2682
|
input.mediaAssetId.length > 0 &&
|
|
2414
2683
|
typeof input.query === 'string' &&
|
|
2415
|
-
input.query.trim().length > 0
|
|
2684
|
+
input.query.trim().length > 0 &&
|
|
2685
|
+
(input.answerOptions === undefined ||
|
|
2686
|
+
(Array.isArray(input.answerOptions) &&
|
|
2687
|
+
input.answerOptions.length <= 10 &&
|
|
2688
|
+
input.answerOptions.every((option) => typeof option === 'string' && option.trim().length > 0 && option.length <= 500))));
|
|
2416
2689
|
}
|
|
2417
2690
|
function validInvestigation(value) {
|
|
2418
2691
|
if (!value || typeof value !== 'object')
|
package/dist/contracts.d.ts
CHANGED
|
@@ -121,6 +121,9 @@ export interface VideoMaterializationJob {
|
|
|
121
121
|
error: string | null;
|
|
122
122
|
}
|
|
123
123
|
export interface TranscriptEvidence {
|
|
124
|
+
speaker?: string;
|
|
125
|
+
/** Voice labels are comparable only inside this transcription chunk. */
|
|
126
|
+
speakerScope?: string;
|
|
124
127
|
startMs: number;
|
|
125
128
|
endMs: number;
|
|
126
129
|
text: string;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
2
|
+
const key = (value) => value.normalize('NFKC').toLocaleLowerCase().trim();
|
|
3
|
+
const label = (value) => (typeof value === 'string' ? value.trim() : '');
|
|
4
|
+
function mentions(text, name) {
|
|
5
|
+
const escaped = name.normalize('NFKC').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'iu').test(text.normalize('NFKC'));
|
|
7
|
+
}
|
|
8
|
+
/** Project source records into answer evidence without changing the stored index. */
|
|
9
|
+
export function groundVideoIdentityEvidence(value) {
|
|
10
|
+
const input = record(value);
|
|
11
|
+
if (!input || !Array.isArray(input.evidence))
|
|
12
|
+
return value;
|
|
13
|
+
const subjects = Array.isArray(input.observedSubjects) ? input.observedSubjects : [];
|
|
14
|
+
const knownIdentities = subjects.flatMap((item) => {
|
|
15
|
+
const subject = record(item);
|
|
16
|
+
return subject && label(subject.identity) ? [label(subject.identity)] : [];
|
|
17
|
+
});
|
|
18
|
+
let withheld = 0;
|
|
19
|
+
const authored = ['source-authored', 'source-questions', 'speech'].includes(label(record(input.inventory)?.recordSet));
|
|
20
|
+
const sanitize = (text, timeRange, context = text) => {
|
|
21
|
+
if (!text.trim())
|
|
22
|
+
return text;
|
|
23
|
+
const local = context.split(/\r?\n/).flatMap((line) => {
|
|
24
|
+
if (!line.startsWith('Visible subject:'))
|
|
25
|
+
return [];
|
|
26
|
+
try {
|
|
27
|
+
const item = record(JSON.parse(line.slice('Visible subject:'.length)));
|
|
28
|
+
return item ? [item] : [];
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const allowed = new Set(local
|
|
35
|
+
.filter((item) => item.identityBasis === 'source-named' || item.identityBasis === 'source-described')
|
|
36
|
+
.map((item) => key(label(item.identity))));
|
|
37
|
+
// An identity established elsewhere is useful only at its observed range.
|
|
38
|
+
for (const item of subjects) {
|
|
39
|
+
const subject = record(item);
|
|
40
|
+
if (!subject ||
|
|
41
|
+
!['source-named', 'source-described'].includes(label(subject.identityBasis)) ||
|
|
42
|
+
!timeRange ||
|
|
43
|
+
!Array.isArray(subject.appearances))
|
|
44
|
+
continue;
|
|
45
|
+
if (subject.appearances.some((entry) => {
|
|
46
|
+
const range = record(entry);
|
|
47
|
+
return (range &&
|
|
48
|
+
typeof range.startSecs === 'number' &&
|
|
49
|
+
typeof range.endSecs === 'number' &&
|
|
50
|
+
typeof timeRange.startSecs === 'number' &&
|
|
51
|
+
typeof timeRange.endSecs === 'number' &&
|
|
52
|
+
range.startSecs <= timeRange.endSecs &&
|
|
53
|
+
range.endSecs >= timeRange.startSecs);
|
|
54
|
+
}))
|
|
55
|
+
allowed.add(key(label(subject.identity)));
|
|
56
|
+
}
|
|
57
|
+
for (const item of local)
|
|
58
|
+
if (item.identityBasis === 'unresolved')
|
|
59
|
+
allowed.delete(key(label(item.identity)));
|
|
60
|
+
const candidates = [
|
|
61
|
+
...knownIdentities,
|
|
62
|
+
...local
|
|
63
|
+
.filter((item) => item.identityBasis === 'unresolved')
|
|
64
|
+
.map((item) => label(item.identity)),
|
|
65
|
+
...Array.from(context.matchAll(/^Present:\s*(.+?)\s+—/gm), (match) => match[1].trim()),
|
|
66
|
+
];
|
|
67
|
+
const blocked = [...new Set(candidates.filter((name) => name && !allowed.has(key(name))))];
|
|
68
|
+
const hasProtocol = /^(?:Visible subject:|Present:|On screen:|Happened(?: \(inferred\))?:|Direct component:|Claim bindings:)/mu.test(context);
|
|
69
|
+
const lines = text.split(/\r?\n/).filter((line) => {
|
|
70
|
+
const inferred = /^Happened \(inferred\):/u.test(line);
|
|
71
|
+
const unsafe = !line.startsWith('On screen:') && blocked.some((name) => mentions(line, name));
|
|
72
|
+
// Legacy prose can bind unlisted actors or repeat inferred events as facts.
|
|
73
|
+
const unqualifiedSummary = text === context && hasProtocol && line.trim() && !/^[\w -]+:/.test(line);
|
|
74
|
+
if (inferred || unsafe || unqualifiedSummary) {
|
|
75
|
+
withheld++;
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
});
|
|
80
|
+
return (lines.join('\n').trim() ||
|
|
81
|
+
'Visual attribution withheld: the source does not establish the actor identity or action.');
|
|
82
|
+
};
|
|
83
|
+
const byId = new Map();
|
|
84
|
+
const evidence = input.evidence.map((entry) => {
|
|
85
|
+
const item = record(entry);
|
|
86
|
+
const payload = record(item?.payload);
|
|
87
|
+
if (!item ||
|
|
88
|
+
!payload ||
|
|
89
|
+
typeof payload.text !== 'string' ||
|
|
90
|
+
authored ||
|
|
91
|
+
item.modality === 'transcript' ||
|
|
92
|
+
/^(?:Source (?:question|item|structure))/u.test(payload.text))
|
|
93
|
+
return entry;
|
|
94
|
+
const text = sanitize(payload.text, record(item.timeRange));
|
|
95
|
+
if (typeof item.id === 'string')
|
|
96
|
+
byId.set(item.id, { text, context: payload.text, range: record(item.timeRange) });
|
|
97
|
+
return { ...item, payload: { ...payload, text } };
|
|
98
|
+
});
|
|
99
|
+
const rows = Array.isArray(input.rows)
|
|
100
|
+
? input.rows.map((entry) => {
|
|
101
|
+
const row = record(entry);
|
|
102
|
+
if (!row || typeof row.id !== 'string' || !byId.has(row.id))
|
|
103
|
+
return entry;
|
|
104
|
+
const item = byId.get(row.id);
|
|
105
|
+
return {
|
|
106
|
+
...row,
|
|
107
|
+
Content: item.text,
|
|
108
|
+
Answer: sanitize(label(row.Answer), item.range, item.context),
|
|
109
|
+
Respondent: sanitize(label(row.Respondent), item.range, item.context),
|
|
110
|
+
};
|
|
111
|
+
})
|
|
112
|
+
: undefined;
|
|
113
|
+
const extra = (entry) => {
|
|
114
|
+
if (Array.isArray(entry))
|
|
115
|
+
return entry.map(extra);
|
|
116
|
+
const item = record(entry);
|
|
117
|
+
if (!item)
|
|
118
|
+
return entry;
|
|
119
|
+
return Object.fromEntries(Object.entries(item).map(([name, child]) => [
|
|
120
|
+
name,
|
|
121
|
+
['text', 'found', 'summary', 'overview'].includes(name) && typeof child === 'string'
|
|
122
|
+
? sanitize(child, record(item.range) ?? record(item.timeRange))
|
|
123
|
+
: extra(child),
|
|
124
|
+
]));
|
|
125
|
+
};
|
|
126
|
+
const directObservation = input.directObservation ? extra(input.directObservation) : undefined;
|
|
127
|
+
const temporalContext = input.temporalContext ? extra(input.temporalContext) : undefined;
|
|
128
|
+
const output = {
|
|
129
|
+
...input,
|
|
130
|
+
evidence,
|
|
131
|
+
...(rows ? { rows } : {}),
|
|
132
|
+
...(Array.isArray(input.observedSubjects)
|
|
133
|
+
? {
|
|
134
|
+
observedSubjects: subjects.filter((item) => record(item)?.identityBasis !== 'unresolved'),
|
|
135
|
+
}
|
|
136
|
+
: {}),
|
|
137
|
+
...(directObservation ? { directObservation } : {}),
|
|
138
|
+
...(temporalContext ? { temporalContext } : {}),
|
|
139
|
+
};
|
|
140
|
+
if (withheld > 0)
|
|
141
|
+
Object.assign(output, {
|
|
142
|
+
identityGrounding: {
|
|
143
|
+
withheldUnits: withheld,
|
|
144
|
+
instruction: 'Some visual attributions were withheld. A spoken name or unresolved identity does not establish a named visible actor or their action. Report the remaining observations, keep uncertain identities/actions unconfirmed, and never reconstruct withheld claims. Sampled observations do not prove every person or every event was captured.',
|
|
145
|
+
},
|
|
146
|
+
claimVerification: {
|
|
147
|
+
...record(input.claimVerification),
|
|
148
|
+
status: 'needs-corroboration',
|
|
149
|
+
directlyEstablished: false,
|
|
150
|
+
rule: 'Answer only from the remaining grounded evidence. A source-complete scan is not proof of a complete person/action inventory. Identity, appearance, and action each need their own source evidence.',
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
return output;
|
|
154
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export * from './ui.js';
|
|
|
9
9
|
export declare const TOOL_META: {
|
|
10
10
|
readonly id: "video-intelligence";
|
|
11
11
|
readonly name: "Video Intelligence";
|
|
12
|
-
readonly version: "0.3.
|
|
12
|
+
readonly version: "0.3.26";
|
|
13
13
|
};
|
|
14
14
|
export declare const TOOL_EXTENSION: {
|
|
15
15
|
id: "video-intelligence";
|
package/dist/index.js
CHANGED
|
@@ -11,11 +11,11 @@ export * from './ui.js';
|
|
|
11
11
|
export const TOOL_META = {
|
|
12
12
|
id: 'video-intelligence',
|
|
13
13
|
name: 'Video Intelligence',
|
|
14
|
-
version: '0.3.
|
|
14
|
+
version: '0.3.26',
|
|
15
15
|
};
|
|
16
16
|
/** Managed infrastructure stays an implementation detail of Larkup Cloud. */
|
|
17
17
|
const MANAGED_CLOUD_ENDPOINT = process.env.LARKUP_VIDEO_INTELLIGENCE_CLOUD_ENDPOINT ??
|
|
18
|
-
'https://
|
|
18
|
+
'https://1vcjmwx9ha.execute-api.eu-central-1.amazonaws.com';
|
|
19
19
|
export const TOOL_EXTENSION = {
|
|
20
20
|
id: TOOL_META.id,
|
|
21
21
|
apiVersion: '1',
|
|
@@ -17,15 +17,36 @@ export declare const VIDEO_INVESTIGATION_SKILLS: readonly [{
|
|
|
17
17
|
}, {
|
|
18
18
|
readonly id: "complete-pages";
|
|
19
19
|
readonly instruction: "For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer.";
|
|
20
|
+
}, {
|
|
21
|
+
readonly id: "speaker-attribution";
|
|
22
|
+
readonly instruction: "For questions and answers by person, preserve each question, its answer, asker, respondent and source timestamps. A diarization label distinguishes voices only inside its transcription chunk; it is not a person name or proof that labels match across chunks. Use source-grounded introductions or visible name labels to establish names. Keep unknown speakers explicitly unknown and unanswered questions unanswered.";
|
|
23
|
+
}, {
|
|
24
|
+
readonly id: "long-results";
|
|
25
|
+
readonly instruction: "Render complete inventories as the returned paginated table with download instead of rewriting a shortened list in prose. For creator workflows such as chapters, lecture notes, clips, quotes or grouped Q&A, keep timestamp provenance and disclose incomplete coverage. Use the corpus sandbox for transformations over mounted source files and larkup_table or larkup_document for complete outputs; never reconstruct the unseen remainder from a sample.";
|
|
20
26
|
}, {
|
|
21
27
|
readonly id: "preserve-language";
|
|
22
28
|
readonly instruction: "Answer in the returned sourceLanguage by default, including notes, speech, and lyrics; translate only when the user explicitly asks. Never default to English.";
|
|
29
|
+
}, {
|
|
30
|
+
readonly id: "answer-alternatives";
|
|
31
|
+
readonly instruction: "When the user supplies answer alternatives, preserve them in answerOptions for source verification. Compare every condition against the source. If several alternatives remain supported, give the best-supported answer with an explicit ambiguity note; never claim uniqueness or invent support for an alternative.";
|
|
23
32
|
}, {
|
|
24
33
|
readonly id: "verify-claims";
|
|
25
34
|
readonly instruction: "Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established.";
|
|
26
35
|
}, {
|
|
27
36
|
readonly id: "interpret-presence";
|
|
28
37
|
readonly instruction: "observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time.";
|
|
38
|
+
}, {
|
|
39
|
+
readonly id: "verify-local-detail";
|
|
40
|
+
readonly instruction: "For a visual attribute or brief change, establish the requested subject and time before answering. If the index is ambiguous, re-watch a bounded local range with adjacent frames; do not resolve colour, pattern, identity or a small object from a broad summary or world knowledge.";
|
|
41
|
+
}, {
|
|
42
|
+
readonly id: "verify-temporal-claim";
|
|
43
|
+
readonly instruction: "For order and counting, keep a timestamped ledger of the requested events and distinguish first occurrence, repetition, and later explanation. Use continuousSequence for a bounded transition when separated samples cannot establish what happened between them. Do not infer chronology merely from the order of retrieved records.";
|
|
44
|
+
}, {
|
|
45
|
+
readonly id: "verify-negative-claim";
|
|
46
|
+
readonly instruction: "Not retrieved does not mean absent. A negative or exclusion claim needs evidence covering the relevant source range and alternatives; disclose a sampling gap instead of treating it as proof that an event never occurred.";
|
|
47
|
+
}, {
|
|
48
|
+
readonly id: "match-answer-scope";
|
|
49
|
+
readonly instruction: "For a primary topic or overall purpose, synthesize the source navigation context and representative speech or visual evidence. Do not mistake a request for the overall topic for an exhaustive inventory. Preserve the distinction between spoken mentions, visible observations, and conclusions inferred across them.";
|
|
29
50
|
}, {
|
|
30
51
|
readonly id: "respond";
|
|
31
52
|
readonly instruction: "Answer as a viewer who remembers the material: lead with the answer itself, and when natural say \"I saw\" or \"I heard\" rather than describing a system. Do not say \"the video shows\", \"the analysis indicates\", or \"according to retrieved evidence\". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.";
|
|
@@ -24,10 +24,22 @@ export const VIDEO_INVESTIGATION_SKILLS = [
|
|
|
24
24
|
id: 'complete-pages',
|
|
25
25
|
instruction: 'For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer.',
|
|
26
26
|
},
|
|
27
|
+
{
|
|
28
|
+
id: 'speaker-attribution',
|
|
29
|
+
instruction: 'For questions and answers by person, preserve each question, its answer, asker, respondent and source timestamps. A diarization label distinguishes voices only inside its transcription chunk; it is not a person name or proof that labels match across chunks. Use source-grounded introductions or visible name labels to establish names. Keep unknown speakers explicitly unknown and unanswered questions unanswered.',
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
id: 'long-results',
|
|
33
|
+
instruction: 'Render complete inventories as the returned paginated table with download instead of rewriting a shortened list in prose. For creator workflows such as chapters, lecture notes, clips, quotes or grouped Q&A, keep timestamp provenance and disclose incomplete coverage. Use the corpus sandbox for transformations over mounted source files and larkup_table or larkup_document for complete outputs; never reconstruct the unseen remainder from a sample.',
|
|
34
|
+
},
|
|
27
35
|
{
|
|
28
36
|
id: 'preserve-language',
|
|
29
37
|
instruction: 'Answer in the returned sourceLanguage by default, including notes, speech, and lyrics; translate only when the user explicitly asks. Never default to English.',
|
|
30
38
|
},
|
|
39
|
+
{
|
|
40
|
+
id: 'answer-alternatives',
|
|
41
|
+
instruction: 'When the user supplies answer alternatives, preserve them in answerOptions for source verification. Compare every condition against the source. If several alternatives remain supported, give the best-supported answer with an explicit ambiguity note; never claim uniqueness or invent support for an alternative.',
|
|
42
|
+
},
|
|
31
43
|
{
|
|
32
44
|
id: 'verify-claims',
|
|
33
45
|
instruction: 'Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established.',
|
|
@@ -36,6 +48,22 @@ export const VIDEO_INVESTIGATION_SKILLS = [
|
|
|
36
48
|
id: 'interpret-presence',
|
|
37
49
|
instruction: 'observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time.',
|
|
38
50
|
},
|
|
51
|
+
{
|
|
52
|
+
id: 'verify-local-detail',
|
|
53
|
+
instruction: 'For a visual attribute or brief change, establish the requested subject and time before answering. If the index is ambiguous, re-watch a bounded local range with adjacent frames; do not resolve colour, pattern, identity or a small object from a broad summary or world knowledge.',
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: 'verify-temporal-claim',
|
|
57
|
+
instruction: 'For order and counting, keep a timestamped ledger of the requested events and distinguish first occurrence, repetition, and later explanation. Use continuousSequence for a bounded transition when separated samples cannot establish what happened between them. Do not infer chronology merely from the order of retrieved records.',
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: 'verify-negative-claim',
|
|
61
|
+
instruction: 'Not retrieved does not mean absent. A negative or exclusion claim needs evidence covering the relevant source range and alternatives; disclose a sampling gap instead of treating it as proof that an event never occurred.',
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: 'match-answer-scope',
|
|
65
|
+
instruction: 'For a primary topic or overall purpose, synthesize the source navigation context and representative speech or visual evidence. Do not mistake a request for the overall topic for an exhaustive inventory. Preserve the distinction between spoken mentions, visible observations, and conclusions inferred across them.',
|
|
66
|
+
},
|
|
39
67
|
{
|
|
40
68
|
id: 'respond',
|
|
41
69
|
instruction: 'Answer as a viewer who remembers the material: lead with the answer itself, and when natural say "I saw" or "I heard" rather than describing a system. Do not say "the video shows", "the analysis indicates", or "according to retrieved evidence". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@larkup/tool-video-intelligence",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.26",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Installable local and cloud video intelligence with evidence-first indexing.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -56,13 +56,13 @@
|
|
|
56
56
|
}
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@larkup/core": "0.8.
|
|
59
|
+
"@larkup/core": "0.8.7"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@types/node": "^26",
|
|
63
63
|
"typescript": "^7.0.2",
|
|
64
64
|
"vitest": "^5.0.0",
|
|
65
|
-
"@larkup/marketplace": "0.3.
|
|
65
|
+
"@larkup/marketplace": "0.3.17"
|
|
66
66
|
},
|
|
67
67
|
"publishConfig": {
|
|
68
68
|
"access": "public"
|
|
@@ -1389,6 +1389,8 @@ def _source_inventory_chunks(
|
|
|
1389
1389
|
item_start = round(float(item.get("startMs") or 0))
|
|
1390
1390
|
item_end = round(float(item.get("endMs") or item_start))
|
|
1391
1391
|
text = str(item.get("text") or "").strip()[:text_limit]
|
|
1392
|
+
if item.get("speaker") is not None:
|
|
1393
|
+
text = f"[Voice {item['speaker']}; {item.get('speakerScope') or 'chunk:0'}] {text}"
|
|
1392
1394
|
if text and item_start < end_ms and item_end >= start_ms:
|
|
1393
1395
|
selected.append(
|
|
1394
1396
|
{"startMs": item_start, "endMs": item_end, "text": text}
|
|
@@ -2649,7 +2651,9 @@ def _validated_plan(
|
|
|
2649
2651
|
frames = round(
|
|
2650
2652
|
bounded_number("framesPerClip", *bounds["frames"], fallback.frames_per_clip)
|
|
2651
2653
|
)
|
|
2652
|
-
|
|
2654
|
+
# Source speech is reusable evidence, not an optional visual-planner hint.
|
|
2655
|
+
# Explicit transcript reuse/skipping is handled by the pipeline brief.
|
|
2656
|
+
use_transcript = fallback.use_transcript
|
|
2653
2657
|
use_ocr = False if heavy_disabled else flag("useOcr", fallback.use_ocr)
|
|
2654
2658
|
use_object_detection = (
|
|
2655
2659
|
False
|
|
@@ -89,6 +89,8 @@ def _rebase_segments(
|
|
|
89
89
|
rebased: list[dict[str, Any]] = []
|
|
90
90
|
for segment in segments:
|
|
91
91
|
copy = {**segment}
|
|
92
|
+
if copy.get("speaker") is not None:
|
|
93
|
+
copy["speakerScope"] = f"chunk:{offset_ms}"
|
|
92
94
|
for key in ("startMs", "endMs"):
|
|
93
95
|
if isinstance(copy.get(key), (int, float)):
|
|
94
96
|
copy[key] = round(float(copy[key])) + offset_ms
|
|
@@ -115,6 +117,9 @@ def _timestamped_segment(
|
|
|
115
117
|
"startMs": round(float(item.get("start", 0)) * 1_000),
|
|
116
118
|
"endMs": round(float(item.get("end", 0)) * 1_000),
|
|
117
119
|
"text": str(item.get("transcript") or item.get("text") or "").strip(),
|
|
120
|
+
**({"speaker": str(item["speaker"]), "speakerScope": "chunk:0"}
|
|
121
|
+
if isinstance(item.get("speaker"), (str, int)) and not isinstance(item.get("speaker"), bool)
|
|
122
|
+
else {}),
|
|
118
123
|
"words": [
|
|
119
124
|
{
|
|
120
125
|
"startMs": round(float(word.get("start", 0)) * 1_000),
|
|
@@ -144,7 +149,7 @@ def _deepgram_segments(results: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
144
149
|
alternative = alternatives[0] if alternatives else {}
|
|
145
150
|
paragraphs = (alternative.get("paragraphs") or {}).get("paragraphs") or []
|
|
146
151
|
sentences = [
|
|
147
|
-
sentence
|
|
152
|
+
{**sentence, **({"speaker": paragraph["speaker"]} if paragraph.get("speaker") is not None else {})}
|
|
148
153
|
for paragraph in paragraphs
|
|
149
154
|
for sentence in paragraph.get("sentences") or []
|
|
150
155
|
if str(sentence.get("text") or "").strip()
|
|
@@ -184,6 +189,7 @@ def _deepgram_segments(results: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
184
189
|
word_start = float(word.get("start", 0))
|
|
185
190
|
if current and (
|
|
186
191
|
word_start - previous_end > 1.25 or word_start - group_start >= 15
|
|
192
|
+
or word.get("speaker") != current[-1].get("speaker")
|
|
187
193
|
):
|
|
188
194
|
groups.append(current)
|
|
189
195
|
current = []
|
|
@@ -197,6 +203,7 @@ def _deepgram_segments(results: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
197
203
|
return [
|
|
198
204
|
_timestamped_segment(
|
|
199
205
|
{
|
|
206
|
+
**({"speaker": group[0]["speaker"]} if group[0].get("speaker") is not None else {}),
|
|
200
207
|
"start": group[0].get("start", 0),
|
|
201
208
|
"end": group[-1].get("end", group[0].get("start", 0)),
|
|
202
209
|
"text": " ".join(
|
|
@@ -313,6 +320,7 @@ class DeepgramProvider(TranscriptionProvider):
|
|
|
313
320
|
("smart_format", "true"),
|
|
314
321
|
("punctuate", "true"),
|
|
315
322
|
("utterances", "true"),
|
|
323
|
+
("diarize", "true"),
|
|
316
324
|
]
|
|
317
325
|
if not automatic_language:
|
|
318
326
|
params.append(("language", language_hint))
|
|
@@ -406,6 +406,14 @@ def _build_prompt(
|
|
|
406
406
|
)
|
|
407
407
|
if questions:
|
|
408
408
|
prompt += " Questions to resolve: " + " | ".join(questions[:4])[:1600] + "."
|
|
409
|
+
prompt += (
|
|
410
|
+
" Resolve the exact subject specified by every qualifier in the question: its action, "
|
|
411
|
+
"position, appearance and source moment. When neighboring subjects share a role or "
|
|
412
|
+
"category, describe each separately and bind the requested property to the one performing "
|
|
413
|
+
"the specified action; do not merge their attributes into a group answer. For a singular "
|
|
414
|
+
"target, claimVerdict is direct only when that subject-to-property binding is visible. "
|
|
415
|
+
"If the target remains ambiguous, state which candidates have which properties and use partial."
|
|
416
|
+
)
|
|
409
417
|
if known_entities:
|
|
410
418
|
prompt += (
|
|
411
419
|
" Continuity candidates from earlier clips: "
|
|
@@ -1398,6 +1406,39 @@ class GeminiVisionClient(GatewayVisionClient):
|
|
|
1398
1406
|
reasoning_effort,
|
|
1399
1407
|
)
|
|
1400
1408
|
return {}
|
|
1409
|
+
for _ in range(2):
|
|
1410
|
+
if response.status_code != 400:
|
|
1411
|
+
break
|
|
1412
|
+
error_text = str(response.text).casefold()
|
|
1413
|
+
config_key = "generation_config" if use_interactions else "generationConfig"
|
|
1414
|
+
config = dict(payload[config_key])
|
|
1415
|
+
schema_rejected = "schema" in error_text and any(reason in error_text for reason in (
|
|
1416
|
+
"too many states", "schema is too complex", "schema complexity",
|
|
1417
|
+
))
|
|
1418
|
+
thinking_rejected = "thinking level" in error_text and "not supported" in error_text
|
|
1419
|
+
if schema_rejected and use_interactions and "schema" in payload["response_format"]:
|
|
1420
|
+
payload = {**payload, "response_format": {
|
|
1421
|
+
key: value for key, value in payload["response_format"].items() if key != "schema"
|
|
1422
|
+
}}
|
|
1423
|
+
elif schema_rejected and "responseSchema" in config:
|
|
1424
|
+
config.pop("responseSchema")
|
|
1425
|
+
payload = {**payload, config_key: config}
|
|
1426
|
+
elif thinking_rejected and ("thinking_level" if use_interactions else "thinkingConfig") in config:
|
|
1427
|
+
config.pop("thinking_level" if use_interactions else "thinkingConfig")
|
|
1428
|
+
payload = {**payload, config_key: config}
|
|
1429
|
+
else:
|
|
1430
|
+
break
|
|
1431
|
+
# Adapt only an explicitly rejected provider option, once per option.
|
|
1432
|
+
# The same images, JSON output, and local evidence validation remain.
|
|
1433
|
+
self.limiter.acquire()
|
|
1434
|
+
try:
|
|
1435
|
+
response = _post_with_retry(
|
|
1436
|
+
self._session(), request_url, headers, payload,
|
|
1437
|
+
attempts=1, timeout_secs=request_timeout,
|
|
1438
|
+
)
|
|
1439
|
+
except RuntimeError as error:
|
|
1440
|
+
self.last_error = str(error)[:500]
|
|
1441
|
+
return {}
|
|
1401
1442
|
if not response.ok:
|
|
1402
1443
|
self._record_http_error("Gemini", response)
|
|
1403
1444
|
return {}
|
package/tool.manifest.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"description": "Help your AI understand your videos, so you can ask questions and get answers from the right moments.",
|
|
8
8
|
"longDescription": "Turn videos into knowledge your AI can understand. It listens to what is said, reads what appears on screen, and helps you find the moments that matter.",
|
|
9
9
|
"category": "media",
|
|
10
|
-
"version": "0.3.
|
|
10
|
+
"version": "0.3.26",
|
|
11
11
|
"pricing": "free",
|
|
12
12
|
"emoji": "🎥",
|
|
13
13
|
"icon": "Film",
|