@introspection-ai/recipes 0.58.0 → 0.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents.d.ts +23 -0
- package/dist/agents.d.ts.map +1 -1
- package/dist/agents.js +37 -3
- package/dist/agents.js.map +1 -1
- package/dist/batch/files.d.ts +5 -0
- package/dist/batch/files.d.ts.map +1 -1
- package/dist/batch/files.js +39 -0
- package/dist/batch/files.js.map +1 -1
- package/dist/batch/index.d.ts +31 -7
- package/dist/batch/index.d.ts.map +1 -1
- package/dist/batch/index.js +58 -27
- package/dist/batch/index.js.map +1 -1
- package/dist/batch/lines.d.ts +51 -9
- package/dist/batch/lines.d.ts.map +1 -1
- package/dist/batch/lines.js +86 -30
- package/dist/batch/lines.js.map +1 -1
- package/dist/batch/runner.d.ts +39 -5
- package/dist/batch/runner.d.ts.map +1 -1
- package/dist/batch/runner.js +427 -52
- package/dist/batch/runner.js.map +1 -1
- package/dist/child/agent-completions.d.ts +10 -0
- package/dist/child/agent-completions.d.ts.map +1 -1
- package/dist/child/agent-completions.js +17 -1
- package/dist/child/agent-completions.js.map +1 -1
- package/dist/child/agent-store.d.ts +9 -0
- package/dist/child/agent-store.d.ts.map +1 -1
- package/dist/child/agent-store.js.map +1 -1
- package/dist/compaction.d.ts +11 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +27 -0
- package/dist/compaction.js.map +1 -0
- package/dist/issues/arguments.d.ts +51 -1
- package/dist/issues/arguments.d.ts.map +1 -1
- package/dist/issues/arguments.generated.d.ts.map +1 -1
- package/dist/issues/arguments.generated.js +97 -0
- package/dist/issues/arguments.generated.js.map +1 -1
- package/dist/issues/module.d.ts.map +1 -1
- package/dist/issues/module.js +8 -1
- package/dist/issues/module.js.map +1 -1
- package/dist/issues/tool.d.ts.map +1 -1
- package/dist/issues/tool.js +127 -4
- package/dist/issues/tool.js.map +1 -1
- package/dist/issues/types.d.ts +40 -1
- package/dist/issues/types.d.ts.map +1 -1
- package/dist/issues/types.js +8 -1
- package/dist/issues/types.js.map +1 -1
- package/dist/judges/classifier.d.ts +8 -0
- package/dist/judges/classifier.d.ts.map +1 -1
- package/dist/judges/classifier.js +17 -0
- package/dist/judges/classifier.js.map +1 -1
- package/dist/judges/cli-main.d.ts.map +1 -1
- package/dist/judges/cli-main.js +3 -1
- package/dist/judges/cli-main.js.map +1 -1
- package/dist/judges/definition.d.ts +7 -0
- package/dist/judges/definition.d.ts.map +1 -1
- package/dist/judges/definition.js +5 -0
- package/dist/judges/definition.js.map +1 -1
- package/dist/judges/index.d.ts +1 -1
- package/dist/judges/index.d.ts.map +1 -1
- package/dist/judges/index.js +1 -1
- package/dist/judges/index.js.map +1 -1
- package/dist/judges/run.d.ts +7 -0
- package/dist/judges/run.d.ts.map +1 -1
- package/dist/judges/run.js +45 -8
- package/dist/judges/run.js.map +1 -1
- package/dist/judges/trajectory.d.ts +2 -11
- package/dist/judges/trajectory.d.ts.map +1 -1
- package/dist/judges/trajectory.js +1 -54
- package/dist/judges/trajectory.js.map +1 -1
- package/dist/model-binding.d.ts +2 -0
- package/dist/model-binding.d.ts.map +1 -1
- package/dist/model-binding.js +11 -0
- package/dist/model-binding.js.map +1 -1
- package/dist/pi-extension.d.ts.map +1 -1
- package/dist/pi-extension.js +158 -7
- package/dist/pi-extension.js.map +1 -1
- package/dist/prompts/budget.d.ts +28 -0
- package/dist/prompts/budget.d.ts.map +1 -0
- package/dist/prompts/budget.js +31 -0
- package/dist/prompts/budget.js.map +1 -0
- package/dist/prompts/builder.d.ts +32 -0
- package/dist/prompts/builder.d.ts.map +1 -0
- package/dist/prompts/builder.js +22 -0
- package/dist/prompts/builder.js.map +1 -0
- package/dist/prompts/builders/conversation-synthesis.d.ts +106 -0
- package/dist/prompts/builders/conversation-synthesis.d.ts.map +1 -0
- package/dist/prompts/builders/conversation-synthesis.js +495 -0
- package/dist/prompts/builders/conversation-synthesis.js.map +1 -0
- package/dist/prompts/builders/trajectory.d.ts +14 -0
- package/dist/prompts/builders/trajectory.d.ts.map +1 -0
- package/dist/prompts/builders/trajectory.js +66 -0
- package/dist/prompts/builders/trajectory.js.map +1 -0
- package/dist/prompts/fit.d.ts +7 -0
- package/dist/prompts/fit.d.ts.map +1 -0
- package/dist/prompts/fit.js +15 -0
- package/dist/prompts/fit.js.map +1 -0
- package/dist/prompts/index.d.ts +8 -0
- package/dist/prompts/index.d.ts.map +1 -0
- package/dist/prompts/index.js +8 -0
- package/dist/prompts/index.js.map +1 -0
- package/dist/prompts/registry.d.ts +8 -0
- package/dist/prompts/registry.d.ts.map +1 -0
- package/dist/prompts/registry.js +15 -0
- package/dist/prompts/registry.js.map +1 -0
- package/dist/prompts/spec.d.ts +16 -0
- package/dist/prompts/spec.d.ts.map +1 -0
- package/dist/prompts/spec.js +12 -0
- package/dist/prompts/spec.js.map +1 -0
- package/dist/prompts/template.d.ts +12 -0
- package/dist/prompts/template.d.ts.map +1 -0
- package/dist/prompts/template.js +31 -0
- package/dist/prompts/template.js.map +1 -0
- package/dist/prompts/text.d.ts +5 -0
- package/dist/prompts/text.d.ts.map +1 -0
- package/dist/prompts/text.js +13 -0
- package/dist/prompts/text.js.map +1 -0
- package/dist/recipe/agent.d.ts +11 -1
- package/dist/recipe/agent.d.ts.map +1 -1
- package/dist/recipe/agent.js +76 -1
- package/dist/recipe/agent.js.map +1 -1
- package/dist/recipe/manifest.generated.d.ts +1 -1
- package/dist/recipe/manifest.generated.js +1 -1
- package/dist/recipe/session.d.ts +5 -0
- package/dist/recipe/session.d.ts.map +1 -1
- package/dist/recipe/session.js +82 -4
- package/dist/recipe/session.js.map +1 -1
- package/dist/run-controller.d.ts.map +1 -1
- package/dist/run-controller.js +4 -0
- package/dist/run-controller.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +49 -1
- package/dist/session.js.map +1 -1
- package/dist/skill-progress.d.ts +24 -3
- package/dist/skill-progress.d.ts.map +1 -1
- package/dist/skill-progress.js +45 -14
- package/dist/skill-progress.js.map +1 -1
- package/docs/agent-composition.md +3 -2
- package/docs/issues/README.md +34 -12
- package/docs/pi-extension.md +1 -1
- package/docs/providers.md +12 -3
- package/docs/recipe-format.md +71 -3
- package/docs/recipe-judges.md +32 -4
- package/package.json +9 -5
- package/skills/issues/SKILL.md +28 -10
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Whatever a builder accepts to change how it builds; each builder documents its keys. */
|
|
2
|
+
export type BuilderOptions = Record<string, unknown>;
|
|
3
|
+
/** What a builder made from one input. */
|
|
4
|
+
export interface BuiltPrompt<State = undefined> {
|
|
5
|
+
prompt: string;
|
|
6
|
+
/** What it cut, such as `middle_cut` when the prompt was over its budget. */
|
|
7
|
+
applied: string[];
|
|
8
|
+
/** Identity of what was read, taken before any cut. */
|
|
9
|
+
digest?: string;
|
|
10
|
+
/** What the caller needs back, such as where the next pass resumes. */
|
|
11
|
+
state?: State;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A named, versioned function from one raw input to a prompt that fits
|
|
15
|
+
* `maxTokens`. Its version is bumped whenever the same input
|
|
16
|
+
* and options render differently.
|
|
17
|
+
*/
|
|
18
|
+
export interface PromptBuilder<Input, State = undefined> {
|
|
19
|
+
name: string;
|
|
20
|
+
version: number;
|
|
21
|
+
build(input: Input, maxTokens: number, options?: BuilderOptions): BuiltPrompt<State>;
|
|
22
|
+
}
|
|
23
|
+
/** `name@version`, as recipes and results name a builder. */
|
|
24
|
+
export declare function builderId(builder: PromptBuilder<unknown, unknown>): string;
|
|
25
|
+
/** A prompt within `maxTokens`, at 3 characters a token: cut in the middle when it is over. */
|
|
26
|
+
export declare function withinBudget(prompt: string, maxTokens: number, applied?: string[]): {
|
|
27
|
+
prompt: string;
|
|
28
|
+
applied: string[];
|
|
29
|
+
};
|
|
30
|
+
/** A number option, or `fallback` when it is absent or not a number. */
|
|
31
|
+
export declare function numberOption(options: BuilderOptions | undefined, key: string, fallback: number): number;
|
|
32
|
+
//# sourceMappingURL=builder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../src/prompts/builder.ts"],"names":[],"mappings":"AAGA,2FAA2F;AAC3F,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAErD,0CAA0C;AAC1C,MAAM,WAAW,WAAW,CAAC,KAAK,GAAG,SAAS;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,6EAA6E;IAC7E,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,uDAAuD;IACvD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uEAAuE;IACvE,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,SAAS;IACrD,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CACH,KAAK,EAAE,KAAK,EACZ,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,KAAK,CAAC,CAAC;CACvB;AAED,6DAA6D;AAC7D,wBAAgB,SAAS,CAAC,OAAO,EAAE,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,MAAM,CAE1E;AAED,+FAA+F;AAC/F,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,MAAM,EAAO,GACrB;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAQvC;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAC1B,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,GACf,MAAM,CAGR"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CHARS_PER_TOKEN } from "./budget.js";
|
|
2
|
+
import { middleCut } from "./fit.js";
|
|
3
|
+
/** `name@version`, as recipes and results name a builder. */
|
|
4
|
+
export function builderId(builder) {
|
|
5
|
+
return `${builder.name}@${builder.version}`;
|
|
6
|
+
}
|
|
7
|
+
/** A prompt within `maxTokens`, at 3 characters a token: cut in the middle when it is over. */
|
|
8
|
+
export function withinBudget(prompt, maxTokens, applied = []) {
|
|
9
|
+
const maxChars = maxTokens * CHARS_PER_TOKEN;
|
|
10
|
+
return prompt.length > maxChars
|
|
11
|
+
? {
|
|
12
|
+
prompt: middleCut(prompt, maxChars),
|
|
13
|
+
applied: [...applied, "middle_cut"],
|
|
14
|
+
}
|
|
15
|
+
: { prompt, applied };
|
|
16
|
+
}
|
|
17
|
+
/** A number option, or `fallback` when it is absent or not a number. */
|
|
18
|
+
export function numberOption(options, key, fallback) {
|
|
19
|
+
const value = options?.[key];
|
|
20
|
+
return typeof value === "number" ? value : fallback;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=builder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../src/prompts/builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AA+BrC,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CAAC,OAAwC;IAChE,OAAO,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;AAC9C,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,YAAY,CAC1B,MAAc,EACd,SAAiB,EACjB,OAAO,GAAa,EAAE;IAEtB,MAAM,QAAQ,GAAG,SAAS,GAAG,eAAe,CAAC;IAC7C,OAAO,MAAM,CAAC,MAAM,GAAG,QAAQ;QAC7B,CAAC,CAAC;YACE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC;YACnC,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC;SACpC;QACH,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAC1B,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,YAAY,CAC1B,OAAmC,EACnC,GAAW,EACX,QAAgB;IAEhB,MAAM,KAAK,GAAG,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;IAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;AACtD,CAAC"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type PromptBuilder } from "../builder.js";
|
|
2
|
+
/**
|
|
3
|
+
* `conversation_synthesis@1`: one conversation, from the turns past its resume
|
|
4
|
+
* cursor, as the case observation synthesis reads, with the plan its next
|
|
5
|
+
* segment resumes from. Each call's window is the processor's, read as
|
|
6
|
+
* recorded: a message is shown once per window it appears in, never matched
|
|
7
|
+
* against earlier content, so a message that repeats earlier text is kept.
|
|
8
|
+
* Calls are read per agent lane (agent id, else agent name, else root), as the
|
|
9
|
+
* processor scopes them: a lane's first window records the history it
|
|
10
|
+
* inherited, so a subagent or branch lane contributes only the task its first
|
|
11
|
+
* window ends with, then its own turns.
|
|
12
|
+
*/
|
|
13
|
+
/** A message part as the conversation API returns it, discriminated by `type`. */
|
|
14
|
+
export interface ConversationPart {
|
|
15
|
+
type: string;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
export interface ConversationMessage {
|
|
19
|
+
role: string;
|
|
20
|
+
parts: ConversationPart[];
|
|
21
|
+
response_id?: string | null;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
/** One model call: the messages new to its input window and what it answered. */
|
|
25
|
+
export interface ConversationModelCall {
|
|
26
|
+
span_id: string;
|
|
27
|
+
response_id?: string | null;
|
|
28
|
+
timestamp?: string | null;
|
|
29
|
+
/** Unix nanoseconds; a string or bigint keeps the precision a JSON number loses. */
|
|
30
|
+
timestamp_ns?: string | number | bigint | null;
|
|
31
|
+
input_new_messages: ConversationMessage[];
|
|
32
|
+
input_message_count?: number;
|
|
33
|
+
output_messages: ConversationMessage[];
|
|
34
|
+
/** The agent the call belongs to, which decides its lane. */
|
|
35
|
+
agent_id?: string | null;
|
|
36
|
+
agent_name?: string | null;
|
|
37
|
+
}
|
|
38
|
+
/** Where the previous segment stopped. */
|
|
39
|
+
export interface ResumeState {
|
|
40
|
+
watermark: string;
|
|
41
|
+
cursor?: string | null;
|
|
42
|
+
segment: number;
|
|
43
|
+
/** The conversation's own lane, the one its first call ran in. */
|
|
44
|
+
root_lane?: string;
|
|
45
|
+
/** Lanes that have begun, whose next window is their own turns rather than inherited history. */
|
|
46
|
+
lanes?: string[];
|
|
47
|
+
/** The root lane's last input size, which a compaction is measured against. */
|
|
48
|
+
last_input_count?: number;
|
|
49
|
+
completed_at?: string | null;
|
|
50
|
+
}
|
|
51
|
+
export interface PriorObservation {
|
|
52
|
+
lens: string;
|
|
53
|
+
label?: string | null;
|
|
54
|
+
summary?: string | null;
|
|
55
|
+
}
|
|
56
|
+
export interface ConversationSynthesisInput {
|
|
57
|
+
conversation_id: string;
|
|
58
|
+
completed_at: string;
|
|
59
|
+
model_calls: ConversationModelCall[];
|
|
60
|
+
watermark?: ResumeState | null;
|
|
61
|
+
prior_observations?: PriorObservation[];
|
|
62
|
+
prior_resolution?: {
|
|
63
|
+
id: string;
|
|
64
|
+
} | null;
|
|
65
|
+
span_count?: number;
|
|
66
|
+
error_count?: number;
|
|
67
|
+
duration_ms?: number;
|
|
68
|
+
service_name?: string | null;
|
|
69
|
+
agent_name?: string | null;
|
|
70
|
+
model?: string | null;
|
|
71
|
+
last_error_message?: string | null;
|
|
72
|
+
}
|
|
73
|
+
export interface SegmentPlan {
|
|
74
|
+
conversation_id: string;
|
|
75
|
+
completed_at: string;
|
|
76
|
+
digest: string;
|
|
77
|
+
segment_start: string;
|
|
78
|
+
segment: number;
|
|
79
|
+
watermark_next: ResumeState;
|
|
80
|
+
prior_resolution?: {
|
|
81
|
+
id: string;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** Why a conversation has no segment to ask this run. */
|
|
85
|
+
export interface SegmentSkip {
|
|
86
|
+
drafts: readonly [];
|
|
87
|
+
model: "";
|
|
88
|
+
hashes: Record<string, never>;
|
|
89
|
+
segment: number;
|
|
90
|
+
watermark_next?: ResumeState;
|
|
91
|
+
skipped?: string;
|
|
92
|
+
}
|
|
93
|
+
export type ConversationSynthesisState = {
|
|
94
|
+
plan: SegmentPlan;
|
|
95
|
+
} | {
|
|
96
|
+
outcome: SegmentSkip;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* One conversation, from the turns past its resume cursor, as the case
|
|
100
|
+
* observation synthesis reads, with the plan its next segment resumes from.
|
|
101
|
+
* Messages are cut at 6,000 characters, the transcript at 300k tokens (the
|
|
102
|
+
* first 10 messages, then from the tail), and tool output between the ends
|
|
103
|
+
* keeps its head and tail, as synthesis always has.
|
|
104
|
+
*/
|
|
105
|
+
export declare const conversationSynthesis: PromptBuilder<ConversationSynthesisInput, ConversationSynthesisState>;
|
|
106
|
+
//# sourceMappingURL=conversation-synthesis.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-synthesis.d.ts","sourceRoot":"","sources":["../../../src/prompts/builders/conversation-synthesis.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { withinBudget } from "../builder.js";
|
|
3
|
+
import { CHARS_PER_TOKEN } from "../budget.js";
|
|
4
|
+
import { prefix, suffix } from "../text.js";
|
|
5
|
+
const MESSAGE_MAX_CHARS = 6_000;
|
|
6
|
+
const TRANSCRIPT_MAX_TOKENS = 300_000;
|
|
7
|
+
const TRANSCRIPT_HEAD_MESSAGES = 10;
|
|
8
|
+
const SLIM_HEAD_CHARS = 1_500;
|
|
9
|
+
const SLIM_TAIL_CHARS = 500;
|
|
10
|
+
const SLIM_PROTECTED_TAIL = 8;
|
|
11
|
+
const DIAGNOSTIC_EVENT_LIMIT = 120;
|
|
12
|
+
const DIAGNOSTIC_EVENT_TEXT_LIMIT = 2_000;
|
|
13
|
+
const SUMMARY = /\b(summary|summarized|previous context|conversation so far|compact|compaction|continue from|continuation|prior context|earlier conversation)\b/i;
|
|
14
|
+
const MEDIA_PARTS = new Set([
|
|
15
|
+
"image-url",
|
|
16
|
+
"audio-url",
|
|
17
|
+
"video-url",
|
|
18
|
+
"document-url",
|
|
19
|
+
"binary",
|
|
20
|
+
"blob",
|
|
21
|
+
"uri",
|
|
22
|
+
"file",
|
|
23
|
+
"image",
|
|
24
|
+
"input_image",
|
|
25
|
+
"image_url",
|
|
26
|
+
"input_file",
|
|
27
|
+
"attachment",
|
|
28
|
+
]);
|
|
29
|
+
const IMAGE_PARTS = new Set(["image", "input_image", "image_url"]);
|
|
30
|
+
const FILE_PARTS = new Set(["file", "input_file", "attachment"]);
|
|
31
|
+
const GENERIC_CONTENT_KEYS = [
|
|
32
|
+
"content",
|
|
33
|
+
"text",
|
|
34
|
+
"summary",
|
|
35
|
+
"response",
|
|
36
|
+
"result",
|
|
37
|
+
"arguments",
|
|
38
|
+
"image_url",
|
|
39
|
+
"url",
|
|
40
|
+
"file",
|
|
41
|
+
"metadata",
|
|
42
|
+
];
|
|
43
|
+
const isMap = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
44
|
+
const present = (value) => value !== null &&
|
|
45
|
+
value !== undefined &&
|
|
46
|
+
value !== "" &&
|
|
47
|
+
!(Array.isArray(value) && value.length === 0);
|
|
48
|
+
/** JSON with every object's keys sorted: the form a fingerprint hashes. */
|
|
49
|
+
function canonicalJson(value) {
|
|
50
|
+
return JSON.stringify(value, (_key, item) => isMap(item)
|
|
51
|
+
? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
|
|
52
|
+
: item);
|
|
53
|
+
}
|
|
54
|
+
/** A value as compact JSON, an object without its empty fields. */
|
|
55
|
+
const compact = (value) => canonicalJson(isMap(value)
|
|
56
|
+
? Object.fromEntries(Object.entries(value).filter(([, item]) => present(item)))
|
|
57
|
+
: value);
|
|
58
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
59
|
+
const squash = (text) => text.replace(/\s+/g, " ").trim();
|
|
60
|
+
/** `text` cut to `max` units, with a marker saying how much was cut. */
|
|
61
|
+
const clip = (text, max, marker) => text.length <= max
|
|
62
|
+
? text
|
|
63
|
+
: `${prefix(text, max)}${marker(text.length - max)}`;
|
|
64
|
+
const squeeze = (text) => text.length <= SLIM_HEAD_CHARS + SLIM_TAIL_CHARS + 200
|
|
65
|
+
? text
|
|
66
|
+
: `${prefix(text, SLIM_HEAD_CHARS)} […] ${suffix(text, SLIM_TAIL_CHARS)}`;
|
|
67
|
+
const escapeXml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
68
|
+
const attr = (text) => `"${escapeXml(text).replace(/"/g, """)}"`;
|
|
69
|
+
const string = (value) => (typeof value === "string" ? value : "");
|
|
70
|
+
function partText(part) {
|
|
71
|
+
switch (part.type) {
|
|
72
|
+
case "text":
|
|
73
|
+
return string(part.content);
|
|
74
|
+
case "compaction":
|
|
75
|
+
return string(part.content) || "[compaction]";
|
|
76
|
+
case "thinking":
|
|
77
|
+
case "reasoning":
|
|
78
|
+
return `[${part.type}] ${string(part.content)}`.trimEnd();
|
|
79
|
+
case "tool_call":
|
|
80
|
+
case "tool_call_response": {
|
|
81
|
+
const label = [part.name, part.id].filter(Boolean).join(" ");
|
|
82
|
+
const payload = part.type === "tool_call" ? part.arguments : part.response;
|
|
83
|
+
return `[${label ? `${part.type} ${label}` : part.type}] ${compact(payload ?? part)}`;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (MEDIA_PARTS.has(part.type))
|
|
87
|
+
return `[${part.type} provided]`;
|
|
88
|
+
const key = GENERIC_CONTENT_KEYS.find((name) => part[name] != null);
|
|
89
|
+
const content = key === undefined ? part : part[key];
|
|
90
|
+
return `[${part.type}] ${typeof content === "string" ? content : compact(content)}`;
|
|
91
|
+
}
|
|
92
|
+
const excerpt = (value) => clip(typeof value === "string" ? value : compact(value), DIAGNOSTIC_EVENT_TEXT_LIMIT, (cut) => `... [truncated ${cut} chars]`);
|
|
93
|
+
function toolStatus(result) {
|
|
94
|
+
if (!isMap(result))
|
|
95
|
+
return undefined;
|
|
96
|
+
const key = [
|
|
97
|
+
"status",
|
|
98
|
+
"status_code",
|
|
99
|
+
"exit_code",
|
|
100
|
+
"returncode",
|
|
101
|
+
"error",
|
|
102
|
+
"exception",
|
|
103
|
+
].find((name) => present(result[name]));
|
|
104
|
+
return key === undefined ? undefined : `${key}=${String(result[key])}`;
|
|
105
|
+
}
|
|
106
|
+
/** The tool calls, results, reasoning and attachments a message carries. */
|
|
107
|
+
function diagnosticEvents(message, ref) {
|
|
108
|
+
return message.parts.flatMap((part) => {
|
|
109
|
+
const name = typeof part.name === "string" ? { tool_name: part.name } : {};
|
|
110
|
+
switch (part.type) {
|
|
111
|
+
case "tool_call":
|
|
112
|
+
return [
|
|
113
|
+
{
|
|
114
|
+
message_ref: ref,
|
|
115
|
+
kind: "tool_call",
|
|
116
|
+
...name,
|
|
117
|
+
input: excerpt(part.arguments ?? {}),
|
|
118
|
+
},
|
|
119
|
+
];
|
|
120
|
+
case "tool_call_response": {
|
|
121
|
+
const status = toolStatus(part.response);
|
|
122
|
+
return [
|
|
123
|
+
{
|
|
124
|
+
message_ref: ref,
|
|
125
|
+
kind: "tool_response",
|
|
126
|
+
...name,
|
|
127
|
+
...(status ? { status } : {}),
|
|
128
|
+
output: excerpt(part.response ?? part),
|
|
129
|
+
},
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
case "thinking":
|
|
133
|
+
case "reasoning": {
|
|
134
|
+
const content = excerpt(string(part.content));
|
|
135
|
+
return [
|
|
136
|
+
{
|
|
137
|
+
message_ref: ref,
|
|
138
|
+
kind: part.type,
|
|
139
|
+
...(content ? { content } : {}),
|
|
140
|
+
},
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (FILE_PARTS.has(part.type))
|
|
145
|
+
return [{ message_ref: ref, kind: "file_provided" }];
|
|
146
|
+
if (IMAGE_PARTS.has(part.type))
|
|
147
|
+
return [{ message_ref: ref, kind: "image_provided" }];
|
|
148
|
+
return [];
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** What dedupes a message: its role and parts, the empty fields of each part left out. */
|
|
152
|
+
const fingerprint = (message) => sha256(canonicalJson({
|
|
153
|
+
role: message.role,
|
|
154
|
+
parts: message.parts.map((part) => Object.fromEntries(Object.entries(part).filter(([, item]) => item != null))),
|
|
155
|
+
})).slice(0, 24);
|
|
156
|
+
const messageContent = (message) => squash(message.parts.map(partText).join("\n"));
|
|
157
|
+
const isSummary = (message) => message.parts.some((part) => part.type === "compaction") ||
|
|
158
|
+
SUMMARY.test(messageContent(message));
|
|
159
|
+
/**
|
|
160
|
+
* Whether a call follows a compaction: an explicit compaction part, or a sharp
|
|
161
|
+
* drop in its input size with a summary-like message (or almost nothing) left.
|
|
162
|
+
*/
|
|
163
|
+
function followsCompaction(previous, current, window) {
|
|
164
|
+
if (window.some((message) => message.parts.some((part) => part.type === "compaction"))) {
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
if (previous < 3 || current === 0 || window.length === 0)
|
|
168
|
+
return false;
|
|
169
|
+
const sharpDrop = current === 1 || current <= Math.max(2, Math.floor(previous / 4));
|
|
170
|
+
return sharpDrop && (current <= 5 || window.some(isSummary));
|
|
171
|
+
}
|
|
172
|
+
const estimateChars = (value) => JSON.stringify(value).length;
|
|
173
|
+
const estimateTokens = (value) => Math.max(1, Math.floor(estimateChars(value) / CHARS_PER_TOKEN));
|
|
174
|
+
/** An ISO-8601 instant in Unix nanoseconds, its fraction kept to the nanosecond. */
|
|
175
|
+
function nanos(iso) {
|
|
176
|
+
const fraction = /\.(\d+)/.exec(iso)?.[1] ?? "";
|
|
177
|
+
const seconds = Date.parse(iso.replace(/\.\d+/, ""));
|
|
178
|
+
return (BigInt(seconds) * 1000000n + BigInt(fraction.padEnd(9, "0").slice(0, 9)));
|
|
179
|
+
}
|
|
180
|
+
const turnOf = (call) => ({
|
|
181
|
+
call,
|
|
182
|
+
ns: call.timestamp_ns != null
|
|
183
|
+
? BigInt(call.timestamp_ns)
|
|
184
|
+
: call.timestamp
|
|
185
|
+
? nanos(call.timestamp)
|
|
186
|
+
: undefined,
|
|
187
|
+
});
|
|
188
|
+
/**
|
|
189
|
+
* Where a resume state stopped: its cursor's instant and span, the keyset
|
|
190
|
+
* order the conversations API pages in, else its watermark's instant alone.
|
|
191
|
+
*/
|
|
192
|
+
function resumePoint(state) {
|
|
193
|
+
if (!state)
|
|
194
|
+
return undefined;
|
|
195
|
+
if (state.cursor) {
|
|
196
|
+
const token = JSON.parse(Buffer.from(state.cursor, "base64url").toString("utf8"));
|
|
197
|
+
if (token.v) {
|
|
198
|
+
const ns = /^\d+$/.test(token.v) ? BigInt(token.v) : nanos(token.v);
|
|
199
|
+
return token.i ? { ns, spanId: token.i } : { ns };
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return { ns: nanos(state.watermark) };
|
|
203
|
+
}
|
|
204
|
+
/** Whether a call comes after the resume point: a later instant, or the same one with a later span. */
|
|
205
|
+
const isAfter = (turn, point) => turn.ns === undefined ||
|
|
206
|
+
turn.ns > point.ns ||
|
|
207
|
+
(turn.ns === point.ns &&
|
|
208
|
+
point.spanId !== undefined &&
|
|
209
|
+
turn.call.span_id > point.spanId);
|
|
210
|
+
/** The keyset cursor the conversations API pages with, at one call. */
|
|
211
|
+
const encodeCursor = (spanId, ns) => Buffer.from(JSON.stringify({ i: spanId, s: "created_at", d: "asc", v: ns.toString() })).toString("base64url");
|
|
212
|
+
/** A call's lane, as the processor scopes it: agent id, else agent name, else root. */
|
|
213
|
+
const laneOf = (call) => call.agent_id
|
|
214
|
+
? `id:${call.agent_id}`
|
|
215
|
+
: call.agent_name
|
|
216
|
+
? `name:${call.agent_name}`
|
|
217
|
+
: "root";
|
|
218
|
+
/** The deduplicated messages of the turns past the resume point, with what they carried. */
|
|
219
|
+
function read(input) {
|
|
220
|
+
const resume = input.watermark ?? undefined;
|
|
221
|
+
const point = resumePoint(resume);
|
|
222
|
+
const all = input.model_calls.map(turnOf);
|
|
223
|
+
const turns = point === undefined ? all : all.filter((turn) => isAfter(turn, point));
|
|
224
|
+
const rootLane = resume?.root_lane ?? (all[0] ? laneOf(all[0].call) : undefined);
|
|
225
|
+
const lanes = new Set(resume?.lanes ?? []);
|
|
226
|
+
const seenSummaries = new Set();
|
|
227
|
+
const messages = [];
|
|
228
|
+
const events = [];
|
|
229
|
+
let compactions = 0;
|
|
230
|
+
// Each lane's input grows on its own, so a compaction is measured within it.
|
|
231
|
+
const previousCounts = new Map();
|
|
232
|
+
if (point !== undefined && rootLane !== undefined) {
|
|
233
|
+
previousCounts.set(rootLane, resume?.last_input_count ?? 0);
|
|
234
|
+
}
|
|
235
|
+
const append = (message, kind, turn, lane, compactionRef) => {
|
|
236
|
+
const content = messageContent(message);
|
|
237
|
+
const shown = clip(content, MESSAGE_MAX_CHARS, (cut) => `... [message truncated ${cut} chars]`);
|
|
238
|
+
const responseId = kind === "output"
|
|
239
|
+
? message.response_id || turn.call.response_id
|
|
240
|
+
: undefined;
|
|
241
|
+
const ref = `m${messages.length + 1}`;
|
|
242
|
+
messages.push({
|
|
243
|
+
ref,
|
|
244
|
+
role: message.role,
|
|
245
|
+
content: shown,
|
|
246
|
+
...(shown !== content ? { truncated: true } : {}),
|
|
247
|
+
part_types: [...new Set(message.parts.map((part) => part.type))],
|
|
248
|
+
source: {
|
|
249
|
+
kind,
|
|
250
|
+
span_id: turn.call.span_id,
|
|
251
|
+
...(turn.call.timestamp ? { timestamp: turn.call.timestamp } : {}),
|
|
252
|
+
message_hash: fingerprint(message),
|
|
253
|
+
...(responseId ? { response_id: responseId } : {}),
|
|
254
|
+
},
|
|
255
|
+
...(compactionRef ? { compaction_ref: compactionRef } : {}),
|
|
256
|
+
...(lane !== rootLane ? { lane: lane.replace(/^(id|name):/, "") } : {}),
|
|
257
|
+
});
|
|
258
|
+
events.push(...diagnosticEvents(message, ref).slice(0, Math.max(0, DIAGNOSTIC_EVENT_LIMIT - events.length)));
|
|
259
|
+
};
|
|
260
|
+
for (const turn of turns) {
|
|
261
|
+
const lane = laneOf(turn.call);
|
|
262
|
+
let window = turn.call.input_new_messages;
|
|
263
|
+
// A lane's first window records the history it inherited; a subagent or
|
|
264
|
+
// branch lane brings only the task that window ends with.
|
|
265
|
+
if (!lanes.has(lane)) {
|
|
266
|
+
if (lane !== rootLane)
|
|
267
|
+
window = window.slice(-1);
|
|
268
|
+
lanes.add(lane);
|
|
269
|
+
}
|
|
270
|
+
const count = turn.call.input_message_count ?? 0;
|
|
271
|
+
let summaries = new Set();
|
|
272
|
+
let compactionRef;
|
|
273
|
+
if (followsCompaction(previousCounts.get(lane) ?? 0, count, window)) {
|
|
274
|
+
let found = window.filter(isSummary);
|
|
275
|
+
if (found.length === 0 && window.length === 1)
|
|
276
|
+
found = [...window];
|
|
277
|
+
const hashes = found.map(fingerprint);
|
|
278
|
+
// A summary already recorded is the same compaction seen again.
|
|
279
|
+
if (hashes.length === 0 ||
|
|
280
|
+
!hashes.every((hash) => seenSummaries.has(hash))) {
|
|
281
|
+
hashes.forEach((hash) => seenSummaries.add(hash));
|
|
282
|
+
compactions += 1;
|
|
283
|
+
compactionRef = `c${compactions}`;
|
|
284
|
+
summaries = new Set(found);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
for (const message of window) {
|
|
288
|
+
append(message, "input", turn, lane, summaries.has(message) ? compactionRef : undefined);
|
|
289
|
+
}
|
|
290
|
+
for (const message of turn.call.output_messages) {
|
|
291
|
+
append(message, "output", turn, lane);
|
|
292
|
+
}
|
|
293
|
+
if (count)
|
|
294
|
+
previousCounts.set(lane, count);
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
messages,
|
|
298
|
+
events,
|
|
299
|
+
compactions,
|
|
300
|
+
turnsSkipped: all.length - turns.length,
|
|
301
|
+
turns,
|
|
302
|
+
...(rootLane !== undefined ? { rootLane } : {}),
|
|
303
|
+
lanes: [...lanes],
|
|
304
|
+
rootInputCount: (rootLane !== undefined ? previousCounts.get(rootLane) : undefined) ?? 0,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/** Keep the opening messages, then fill from the tail backwards, within `maxTokens`. */
|
|
308
|
+
function capTranscript(messages) {
|
|
309
|
+
if (estimateTokens(messages) <= TRANSCRIPT_MAX_TOKENS)
|
|
310
|
+
return messages;
|
|
311
|
+
const maxChars = TRANSCRIPT_MAX_TOKENS * CHARS_PER_TOKEN;
|
|
312
|
+
const kept = new Map();
|
|
313
|
+
let used = 2;
|
|
314
|
+
const add = (message, force) => {
|
|
315
|
+
if (kept.has(message.ref) || used >= maxChars)
|
|
316
|
+
return;
|
|
317
|
+
const size = estimateChars(message);
|
|
318
|
+
if (used + size <= maxChars) {
|
|
319
|
+
kept.set(message.ref, message);
|
|
320
|
+
used += size;
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (!force && kept.size > 0)
|
|
324
|
+
return;
|
|
325
|
+
const room = maxChars - used - estimateChars({ ...message, content: "" }) - 200;
|
|
326
|
+
if (room <= 100)
|
|
327
|
+
return;
|
|
328
|
+
const cut = {
|
|
329
|
+
...message,
|
|
330
|
+
content: clip(message.content, room, (n) => `... [truncated ${n} chars]`),
|
|
331
|
+
truncated: true,
|
|
332
|
+
};
|
|
333
|
+
kept.set(message.ref, cut);
|
|
334
|
+
used += estimateChars(cut);
|
|
335
|
+
};
|
|
336
|
+
messages
|
|
337
|
+
.slice(0, TRANSCRIPT_HEAD_MESSAGES)
|
|
338
|
+
.forEach((message) => add(message, true));
|
|
339
|
+
[...messages].reverse().forEach((message) => add(message, kept.size === 0));
|
|
340
|
+
return messages.flatMap((message) => kept.get(message.ref) ?? []);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Head-and-tail: the first user and assistant messages and the last few stay
|
|
344
|
+
* whole; tool output between them keeps its head and tail, and an event whose
|
|
345
|
+
* content the transcript already shows is dropped.
|
|
346
|
+
*/
|
|
347
|
+
function slim(messages, events) {
|
|
348
|
+
const kept = new Set(messages.map((message) => message.ref));
|
|
349
|
+
const whole = new Set(messages.slice(-SLIM_PROTECTED_TAIL).map((message) => message.ref));
|
|
350
|
+
for (const role of ["user", "assistant"]) {
|
|
351
|
+
const first = messages.find((message) => message.role === role);
|
|
352
|
+
if (first)
|
|
353
|
+
whole.add(first.ref);
|
|
354
|
+
}
|
|
355
|
+
const transcript = messages.map((message) => message.content).join("\n");
|
|
356
|
+
return {
|
|
357
|
+
messages: messages.map((message) => message.role === "tool" && !whole.has(message.ref)
|
|
358
|
+
? { ...message, content: squeeze(message.content) }
|
|
359
|
+
: message),
|
|
360
|
+
events: events
|
|
361
|
+
.filter((event) => kept.has(event.message_ref))
|
|
362
|
+
.filter((event) => {
|
|
363
|
+
const shown = event.content ||
|
|
364
|
+
(event.kind === "tool_response" ? event.output : event.input);
|
|
365
|
+
return (whole.has(event.message_ref) || !shown || !transcript.includes(shown));
|
|
366
|
+
})
|
|
367
|
+
.map((event, index) => ({
|
|
368
|
+
ref: `d${index + 1}`,
|
|
369
|
+
...event,
|
|
370
|
+
...(event.kind === "tool_response" &&
|
|
371
|
+
event.output &&
|
|
372
|
+
!whole.has(event.message_ref)
|
|
373
|
+
? { output: squeeze(event.output) }
|
|
374
|
+
: {}),
|
|
375
|
+
})),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function render(input, conversation, messages, events, capped) {
|
|
379
|
+
const lines = ["<conversation_case>"];
|
|
380
|
+
lines.push(` <conversation_id>${escapeXml(input.conversation_id)}</conversation_id>`);
|
|
381
|
+
const metadata = [
|
|
382
|
+
["service_name", input.service_name],
|
|
383
|
+
["agent_name", input.agent_name],
|
|
384
|
+
["model", input.model],
|
|
385
|
+
["span_count", input.span_count ?? 0],
|
|
386
|
+
["error_count", input.error_count ?? 0],
|
|
387
|
+
["duration_ms", input.duration_ms ?? 0],
|
|
388
|
+
];
|
|
389
|
+
lines.push(" <metadata>");
|
|
390
|
+
for (const [key, value] of metadata) {
|
|
391
|
+
if (value != null && value !== "")
|
|
392
|
+
lines.push(` <${key}>${escapeXml(String(value))}</${key}>`);
|
|
393
|
+
}
|
|
394
|
+
if (input.last_error_message) {
|
|
395
|
+
lines.push(` <last_error>${escapeXml(input.last_error_message)}</last_error>`);
|
|
396
|
+
}
|
|
397
|
+
lines.push(" </metadata>");
|
|
398
|
+
const prior = input.prior_observations ?? [];
|
|
399
|
+
if (prior.length > 0) {
|
|
400
|
+
lines.push(" <previous_observations>");
|
|
401
|
+
for (const row of prior) {
|
|
402
|
+
lines.push(` <observation lens=${attr(row.lens)} label=${attr(row.label || "observation")}>${escapeXml((row.summary ?? "").trim())}</observation>`);
|
|
403
|
+
}
|
|
404
|
+
lines.push(" </previous_observations>");
|
|
405
|
+
}
|
|
406
|
+
if (input.watermark) {
|
|
407
|
+
lines.push(` <continuation turns_skipped=${attr(String(conversation.turnsSkipped))}>Only new turns are included.</continuation>`);
|
|
408
|
+
}
|
|
409
|
+
if (conversation.compactions > 0) {
|
|
410
|
+
lines.push(` <context_compactions count=${attr(String(conversation.compactions))}>Earlier turns were summarized.</context_compactions>`);
|
|
411
|
+
}
|
|
412
|
+
lines.push(" <transcript>");
|
|
413
|
+
for (const message of messages) {
|
|
414
|
+
lines.push(` <message ref=${attr(message.ref)} role=${attr(message.role || "unknown")}${message.lane ? ` lane=${attr(message.lane)}` : ""}>${escapeXml(message.content.trim())}</message>`);
|
|
415
|
+
}
|
|
416
|
+
lines.push(" </transcript>");
|
|
417
|
+
if (events.length > 0) {
|
|
418
|
+
lines.push(" <diagnostic_events>");
|
|
419
|
+
for (const event of events) {
|
|
420
|
+
lines.push(` <event ref=${attr(event.ref ?? "?")} kind=${attr(event.kind)}>${escapeXml(event.content || JSON.stringify(event))}</event>`);
|
|
421
|
+
}
|
|
422
|
+
lines.push(" </diagnostic_events>");
|
|
423
|
+
}
|
|
424
|
+
if (capped)
|
|
425
|
+
lines.push(" <transcript_capped>Middle sections may be missing.</transcript_capped>");
|
|
426
|
+
lines.push("</conversation_case>");
|
|
427
|
+
return lines.join("\n");
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* One conversation, from the turns past its resume cursor, as the case
|
|
431
|
+
* observation synthesis reads, with the plan its next segment resumes from.
|
|
432
|
+
* Messages are cut at 6,000 characters, the transcript at 300k tokens (the
|
|
433
|
+
* first 10 messages, then from the tail), and tool output between the ends
|
|
434
|
+
* keeps its head and tail, as synthesis always has.
|
|
435
|
+
*/
|
|
436
|
+
export const conversationSynthesis = {
|
|
437
|
+
name: "conversation_synthesis",
|
|
438
|
+
version: 1,
|
|
439
|
+
build(input, maxTokens) {
|
|
440
|
+
const resume = input.watermark ?? undefined;
|
|
441
|
+
const conversation = read(input);
|
|
442
|
+
const last = conversation.turns
|
|
443
|
+
.filter((turn) => turn.ns !== undefined)
|
|
444
|
+
.reduce((latest, turn) => latest === undefined ||
|
|
445
|
+
turn.ns > latest.ns ||
|
|
446
|
+
(turn.ns === latest.ns && turn.call.span_id > latest.call.span_id)
|
|
447
|
+
? turn
|
|
448
|
+
: latest, undefined);
|
|
449
|
+
const segment = (number) => ({
|
|
450
|
+
watermark: last?.call.timestamp ?? input.completed_at,
|
|
451
|
+
...(last ? { cursor: encodeCursor(last.call.span_id, last.ns) } : {}),
|
|
452
|
+
segment: number,
|
|
453
|
+
...(conversation.rootLane !== undefined
|
|
454
|
+
? { root_lane: conversation.rootLane }
|
|
455
|
+
: {}),
|
|
456
|
+
lanes: conversation.lanes,
|
|
457
|
+
last_input_count: conversation.rootInputCount,
|
|
458
|
+
completed_at: input.completed_at,
|
|
459
|
+
});
|
|
460
|
+
const priorSegment = resume?.segment ?? 0;
|
|
461
|
+
const skip = { drafts: [], model: "", hashes: {} };
|
|
462
|
+
if (conversation.messages.length === 0) {
|
|
463
|
+
const outcome = last === undefined
|
|
464
|
+
? { ...skip, segment: 0, skipped: "no_new_content" }
|
|
465
|
+
: {
|
|
466
|
+
...skip,
|
|
467
|
+
segment: priorSegment,
|
|
468
|
+
watermark_next: segment(priorSegment),
|
|
469
|
+
};
|
|
470
|
+
return { prompt: "", applied: [], state: { outcome } };
|
|
471
|
+
}
|
|
472
|
+
const kept = capTranscript(conversation.messages);
|
|
473
|
+
const capped = kept.length < conversation.messages.length;
|
|
474
|
+
const digest = sha256(kept.map((message) => message.source.message_hash).join("\n"));
|
|
475
|
+
const slimmed = slim(kept, conversation.events);
|
|
476
|
+
const point = resumePoint(resume);
|
|
477
|
+
const plan = {
|
|
478
|
+
conversation_id: input.conversation_id,
|
|
479
|
+
completed_at: input.completed_at,
|
|
480
|
+
digest,
|
|
481
|
+
segment_start: point === undefined ? "" : point.ns.toString(),
|
|
482
|
+
segment: priorSegment + 1,
|
|
483
|
+
watermark_next: segment(priorSegment + 1),
|
|
484
|
+
...(input.prior_resolution
|
|
485
|
+
? { prior_resolution: input.prior_resolution }
|
|
486
|
+
: {}),
|
|
487
|
+
};
|
|
488
|
+
return {
|
|
489
|
+
...withinBudget(render(input, conversation, slimmed.messages, slimmed.events, capped), maxTokens, capped ? ["cap_transcript"] : []),
|
|
490
|
+
digest,
|
|
491
|
+
state: { plan },
|
|
492
|
+
};
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
//# sourceMappingURL=conversation-synthesis.js.map
|