@inflexa-ai/harness 0.44.0 → 0.45.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/app/approve-plan.d.ts +48 -0
- package/dist/app/approve-plan.js +84 -0
- package/dist/app/data-profile-view.d.ts +1 -1
- package/dist/app/run-activity.js +4 -6
- package/dist/contracts/chat-events.d.ts +2 -0
- package/dist/contracts/chat-frame.d.ts +7 -0
- package/dist/contracts/chat-frame.js +18 -4
- package/dist/contracts/chat-parts.d.ts +73 -2
- package/dist/contracts/chat-parts.js +3 -1
- package/dist/contracts/index.d.ts +3 -1
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/part-registry.js +3 -0
- package/dist/contracts/schemas/chat-events.d.ts +13 -0
- package/dist/contracts/schemas/chat-events.js +1 -0
- package/dist/contracts/schemas/chat-parts.d.ts +200 -15
- package/dist/contracts/schemas/chat-parts.js +63 -12
- package/dist/contracts/schemas/index.d.ts +1 -1
- package/dist/contracts/schemas/index.js +1 -1
- package/dist/contracts/subagent-activity.d.ts +12 -0
- package/dist/contracts/subagent-activity.js +76 -0
- package/dist/execution/artifact-metadata.js +1 -3
- package/dist/execution/run-canceler.js +1 -1
- package/dist/execution/run-event-parts.d.ts +6 -5
- package/dist/execution/run-event-parts.js +6 -5
- package/dist/execution/run-event-stream.d.ts +18 -6
- package/dist/execution/run-event-stream.js +67 -17
- package/dist/execution/run-synthesis.d.ts +21 -0
- package/dist/execution/run-synthesis.js +77 -3
- package/dist/index.d.ts +22 -8
- package/dist/index.js +16 -2
- package/dist/lib/hooks.d.ts +1 -1
- package/dist/lib/metrics.d.ts +2 -2
- package/dist/loop/run-agent.js +1 -0
- package/dist/loop/types.d.ts +2 -0
- package/dist/memory/card-builders.d.ts +11 -0
- package/dist/memory/card-builders.js +35 -21
- package/dist/memory/conversation-display-recorder.d.ts +2 -0
- package/dist/memory/conversation-display-recorder.js +10 -1
- package/dist/memory/conversation-display-storage.d.ts +9 -2
- package/dist/memory/conversation-display-storage.js +18 -3
- package/dist/memory/thread-history.d.ts +8 -1
- package/dist/memory/thread-history.js +13 -3
- package/dist/memory/thread-store.d.ts +13 -0
- package/dist/memory/thread-store.js +15 -1
- package/dist/prompts/conversation.d.ts +1 -1
- package/dist/prompts/conversation.js +3 -1
- package/dist/provenance/seam.d.ts +16 -5
- package/dist/providers/ai-sdk.js +6 -4
- package/dist/report-model/pin-snapshot.d.ts +1 -1
- package/dist/report-model/pin-snapshot.js +2 -50
- package/dist/runtime/assemble.d.ts +8 -1
- package/dist/runtime/assemble.js +11 -0
- package/dist/runtime/boot.d.ts +3 -0
- package/dist/runtime/boot.js +10 -1
- package/dist/sandbox/sandbox-step-translate.d.ts +23 -0
- package/dist/sandbox/sandbox-step-translate.js +24 -0
- package/dist/schemas/artifact-manifest.d.ts +1 -1
- package/dist/schemas/artifact-manifest.js +11 -9
- package/dist/schemas/plan-schemas.d.ts +18 -18
- package/dist/schemas/run-synthesis.d.ts +2 -2
- package/dist/state/analyses-metrics.d.ts +79 -7
- package/dist/state/analyses-metrics.js +141 -6
- package/dist/state/artifacts.d.ts +50 -3
- package/dist/state/artifacts.js +67 -7
- package/dist/state/data-profile.d.ts +4 -2
- package/dist/state/data-profile.js +7 -5
- package/dist/state/index.d.ts +9 -8
- package/dist/state/index.js +5 -5
- package/dist/state/migrations/20261012120000_index_the_runs_by_start.d.ts +8 -0
- package/dist/state/migrations/20261012120000_index_the_runs_by_start.js +12 -0
- package/dist/state/migrations/20261013120000_index_the_ended_runs_and_the_recent_threads.d.ts +8 -0
- package/dist/state/migrations/20261013120000_index_the_ended_runs_and_the_recent_threads.js +13 -0
- package/dist/state/migrations/20261013180000_narrow_the_active_run_index.d.ts +8 -0
- package/dist/state/migrations/20261013180000_narrow_the_active_run_index.js +13 -0
- package/dist/state/migrations/20261014120000_index_the_plans_by_parent_and_the_runs_by_plan.d.ts +8 -0
- package/dist/state/migrations/20261014120000_index_the_plans_by_parent_and_the_runs_by_plan.js +13 -0
- package/dist/state/migrations/index.js +8 -0
- package/dist/state/plans.d.ts +21 -0
- package/dist/state/plans.js +25 -0
- package/dist/state/runs.d.ts +36 -5
- package/dist/state/runs.js +65 -19
- package/dist/state/schema.d.ts +2 -0
- package/dist/tasks/data-profile-activity.d.ts +7 -1
- package/dist/tasks/data-profile-activity.js +18 -9
- package/dist/tasks/data-profile.d.ts +15 -1
- package/dist/tasks/data-profile.js +16 -11
- package/dist/tools/approval/gateway.js +28 -5
- package/dist/tools/display/show-user.d.ts +1 -1
- package/dist/tools/execute-analysis.d.ts +51 -0
- package/dist/tools/execute-analysis.js +241 -109
- package/dist/tools/research/inspect-data-profile.d.ts +1 -1
- package/dist/tools/research/inspect-run.d.ts +1 -1
- package/dist/tools/research/inspect-run.js +7 -7
- package/dist/workflows/execute-analysis.d.ts +4 -3
- package/dist/workflows/execute-analysis.js +35 -22
- package/dist/workflows/plan/graph.d.ts +16 -0
- package/dist/workflows/plan/graph.js +36 -0
- package/dist/workflows/sandbox-step.js +14 -12
- package/package.json +1 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { applyChatFrame, checkChatPart, isRootFrame, toChatFrame } from "../contracts/chat-frame.js";
|
|
3
3
|
import { PART_REGISTRY } from "../contracts/part-registry.js";
|
|
4
|
+
import { createSubAgentActivityTracker } from "../contracts/subagent-activity.js";
|
|
4
5
|
import { compactionExchangeOf, compactionMarkerOf } from "./ai-sdk-message-storage.js";
|
|
5
6
|
import { conversationDisplayPart } from "./conversation-display-storage.js";
|
|
6
7
|
function jsonCopy(value) {
|
|
@@ -69,6 +70,8 @@ export function createConversationDisplayRecorder(options) {
|
|
|
69
70
|
// The messages of the open round. A later update of a part lands in the next round, and the replay replaces the earlier copy.
|
|
70
71
|
let round = [];
|
|
71
72
|
let finished = false;
|
|
73
|
+
const now = options.now ?? Date.now;
|
|
74
|
+
const subAgentActivity = createSubAgentActivityTracker();
|
|
72
75
|
function apply(frame) {
|
|
73
76
|
round = applyChatFrame(round, frame, assistantMessageId).messages;
|
|
74
77
|
}
|
|
@@ -84,7 +87,13 @@ export function createConversationDisplayRecorder(options) {
|
|
|
84
87
|
}
|
|
85
88
|
function record(event) {
|
|
86
89
|
const frame = toChatFrame(event, rootSource);
|
|
87
|
-
if (frame === null
|
|
90
|
+
if (frame === null)
|
|
91
|
+
return;
|
|
92
|
+
// The tracker reads the frames of the sub-agents, and `applyChatFrame` ignores them.
|
|
93
|
+
const activity = subAgentActivity.track(frame, now());
|
|
94
|
+
if (activity !== null && durableConversationType(activity.type))
|
|
95
|
+
apply(recordedPart(activity));
|
|
96
|
+
if (!isRootFrame(frame))
|
|
88
97
|
return;
|
|
89
98
|
if (frame.type.startsWith("data-")) {
|
|
90
99
|
// Each chat event type is named without the `data-` prefix, thus a `data-` frame is a part frame.
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* reconstruction.
|
|
16
16
|
*/
|
|
17
17
|
import { type DataUIPart, type UIMessage } from "ai";
|
|
18
|
-
import type { AskPart, ChildSessionStartedPart, CompactionPart, FileReferencePart, PlanPart, PresentationPart, ReportRenderedPart, RunCardPart } from "../contracts/chat-parts.js";
|
|
18
|
+
import type { AskPart, ChildSessionStartedPart, CompactionPart, FileReferencePart, PlanApprovalPart, PlanPart, PresentationPart, ReportRenderedPart, RunCardPart, SubAgentActivityEntry, SubAgentActivityPart } from "../contracts/chat-parts.js";
|
|
19
19
|
import type { ToolCallOutcome } from "../contracts/chat-events.js";
|
|
20
20
|
import type { ChatMessage, MessagePart, ToolCallPart } from "../contracts/message.js";
|
|
21
21
|
import type { Logger } from "../lib/logger.js";
|
|
@@ -37,11 +37,17 @@ export type ConversationUIData = {
|
|
|
37
37
|
presentation: Payload<PresentationPart>;
|
|
38
38
|
plan: Payload<PlanPart>;
|
|
39
39
|
"run-card": Payload<RunCardPart>;
|
|
40
|
+
"plan-approval": Payload<PlanApprovalPart>;
|
|
40
41
|
"file-reference": Payload<FileReferencePart>;
|
|
41
42
|
ask: Payload<AskPart>;
|
|
42
43
|
"child-session-started": Payload<ChildSessionStartedPart>;
|
|
43
44
|
"report-rendered": Payload<ReportRenderedPart>;
|
|
44
45
|
compaction: Payload<CompactionPart>;
|
|
46
|
+
"subagent-activity": Omit<Payload<SubAgentActivityPart>, "entries"> & {
|
|
47
|
+
entries: (Omit<SubAgentActivityEntry, "outcome"> & {
|
|
48
|
+
outcome: ToolCallOutcome;
|
|
49
|
+
})[];
|
|
50
|
+
};
|
|
45
51
|
};
|
|
46
52
|
export interface ConversationDisplayMetadata {
|
|
47
53
|
interrupted?: boolean;
|
|
@@ -63,7 +69,8 @@ export declare function parseStoredDisplayEnvelope(value: unknown, identity: str
|
|
|
63
69
|
* flight) and required here, because a record is of a call that is no longer
|
|
64
70
|
* running. An in-flight call being recorded is one the turn never saw finish, so
|
|
65
71
|
* absence resolves to `incomplete` at exactly this boundary — once, where the
|
|
66
|
-
* lifetime changes — rather than at each reader.
|
|
72
|
+
* lifetime changes — rather than at each reader. An entry of a sub-agent call
|
|
73
|
+
* closes the same way, and an `incomplete` entry has no end time.
|
|
67
74
|
*/
|
|
68
75
|
export declare function conversationDisplayPart(part: Exclude<MessagePart, {
|
|
69
76
|
type: "text";
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { validateUIMessages } from "ai";
|
|
18
18
|
import { z } from "zod";
|
|
19
|
-
import { AskPartSchema, ChildSessionStartedPartSchema, CompactionPartSchema, FileReferencePartSchema, PlanPartSchema, PresentationPartSchema, ReportRenderedPartSchema, RunCardPartSchema, } from "../contracts/schemas/chat-parts.js";
|
|
19
|
+
import { AskPartSchema, ChildSessionStartedPartSchema, CompactionPartSchema, FileReferencePartSchema, PlanApprovalPartSchema, PlanPartSchema, PresentationPartSchema, ReportRenderedPartSchema, RunCardPartSchema, SubAgentActivityEntrySchema, SubAgentActivityPartSchema, } from "../contracts/schemas/chat-parts.js";
|
|
20
20
|
import { ToolCallOutcomeSchema } from "../contracts/schemas/chat-events.js";
|
|
21
21
|
export const SUPPORTED_DISPLAY_SCHEMA_VERSION = 1;
|
|
22
22
|
const DisplayEnvelopeHeaderSchema = z.object({
|
|
@@ -65,11 +65,15 @@ const dataSchemas = {
|
|
|
65
65
|
presentation: PresentationPartSchema.omit({ type: true }),
|
|
66
66
|
plan: PlanPartSchema.omit({ type: true }),
|
|
67
67
|
"run-card": RunCardPartSchema.omit({ type: true }),
|
|
68
|
+
"plan-approval": PlanApprovalPartSchema.omit({ type: true }),
|
|
68
69
|
"file-reference": FileReferencePartSchema.omit({ type: true }),
|
|
69
70
|
ask: AskPartSchema.omit({ type: true }),
|
|
70
71
|
"child-session-started": ChildSessionStartedPartSchema.omit({ type: true }),
|
|
71
72
|
"report-rendered": ReportRenderedPartSchema.omit({ type: true }),
|
|
72
73
|
compaction: CompactionPartSchema.omit({ type: true }),
|
|
74
|
+
"subagent-activity": SubAgentActivityPartSchema.omit({ type: true }).extend({
|
|
75
|
+
entries: z.array(SubAgentActivityEntrySchema.extend({ outcome: ToolCallOutcomeSchema })),
|
|
76
|
+
}),
|
|
73
77
|
};
|
|
74
78
|
export function envelopeDisplayMessages(messages) {
|
|
75
79
|
if (messages.length === 0)
|
|
@@ -157,6 +161,12 @@ export async function parseStoredDisplayEnvelope(value, identity, logger) {
|
|
|
157
161
|
function displayPartType(part) {
|
|
158
162
|
return (part.type === "tool-call" ? "data-tool-call" : part.type);
|
|
159
163
|
}
|
|
164
|
+
function closedEntry(entry) {
|
|
165
|
+
if (entry.outcome !== undefined)
|
|
166
|
+
return { ...entry, outcome: entry.outcome };
|
|
167
|
+
const { endedAt: _endedAt, ...open } = entry;
|
|
168
|
+
return { ...open, outcome: "incomplete" };
|
|
169
|
+
}
|
|
160
170
|
/** The id a part reconciles on: a tool call by its call id, a card by its own stable id. */
|
|
161
171
|
function displayPartId(part) {
|
|
162
172
|
if (part.type === "tool-call")
|
|
@@ -171,11 +181,16 @@ function displayPartId(part) {
|
|
|
171
181
|
* flight) and required here, because a record is of a call that is no longer
|
|
172
182
|
* running. An in-flight call being recorded is one the turn never saw finish, so
|
|
173
183
|
* absence resolves to `incomplete` at exactly this boundary — once, where the
|
|
174
|
-
* lifetime changes — rather than at each reader.
|
|
184
|
+
* lifetime changes — rather than at each reader. An entry of a sub-agent call
|
|
185
|
+
* closes the same way, and an `incomplete` entry has no end time.
|
|
175
186
|
*/
|
|
176
187
|
export function conversationDisplayPart(part) {
|
|
177
188
|
const { type: _type, ...rest } = part;
|
|
178
|
-
const data = part.type === "tool-call"
|
|
189
|
+
const data = part.type === "tool-call"
|
|
190
|
+
? { ...rest, outcome: part.outcome ?? "incomplete" }
|
|
191
|
+
: part.type === "data-subagent-activity"
|
|
192
|
+
? { ...rest, entries: part.entries.map(closedEntry) }
|
|
193
|
+
: rest;
|
|
179
194
|
return { type: displayPartType(part), id: displayPartId(part), data };
|
|
180
195
|
}
|
|
181
196
|
/**
|
|
@@ -27,6 +27,7 @@ import type { TokenUsageRollup } from "../contracts/usage.js";
|
|
|
27
27
|
import { type DbError } from "../lib/db-result.js";
|
|
28
28
|
import type { Logger } from "../lib/logger.js";
|
|
29
29
|
import { type StoredMessageEnvelope } from "./ai-sdk-message-storage.js";
|
|
30
|
+
import type { MessagePart } from "../contracts/message.js";
|
|
30
31
|
import { type ConversationUIMessage, type StoredDisplayEnvelope } from "./conversation-display-storage.js";
|
|
31
32
|
/** One stored message, as returned by the display read (`loadAll`). */
|
|
32
33
|
export interface StoredMessage {
|
|
@@ -104,8 +105,14 @@ export interface ConversationTurn {
|
|
|
104
105
|
* never shown. The harness owns the record-to-`system` mapping for the same
|
|
105
106
|
* reason it owns the marker — a host that hand-assembled either could produce a
|
|
106
107
|
* message the turn-boundary predicates fail to recognise.
|
|
108
|
+
*
|
|
109
|
+
* With `displayParts`, the display message holds those parts in place of the
|
|
110
|
+
* text part, and the model message is still the record of `text`. The text then
|
|
111
|
+
* stays for the model alone.
|
|
107
112
|
*/
|
|
108
|
-
export declare function conversationRecordTurn(text: string
|
|
113
|
+
export declare function conversationRecordTurn(text: string, displayParts?: readonly Exclude<MessagePart, {
|
|
114
|
+
type: "text";
|
|
115
|
+
}>[]): ConversationTurn;
|
|
109
116
|
/** The status of a chat turn: `open` while it runs, then its outcome. */
|
|
110
117
|
export type TurnStatus = "open" | "done" | "aborted" | "failed";
|
|
111
118
|
/** The close of a chat turn. It sets the outcome on the turn record, one time. */
|
|
@@ -29,7 +29,7 @@ import { hasReportedUsage } from "../loop/metrics.js";
|
|
|
29
29
|
import { countTokens } from "./count-tokens.js";
|
|
30
30
|
import { conversationView, groupTurns, isGenuineUserStart } from "./conversation-view.js";
|
|
31
31
|
import { HARNESS_PROVIDER_NAMESPACE, SYNTHETIC_MESSAGE_KEY, envelopeMessage, parseStoredMessageEnvelope, syntheticRecordMessage, } from "./ai-sdk-message-storage.js";
|
|
32
|
-
import { envelopeDisplayMessages, parseStoredDisplayEnvelope } from "./conversation-display-storage.js";
|
|
32
|
+
import { conversationDisplayPart, envelopeDisplayMessages, parseStoredDisplayEnvelope, } from "./conversation-display-storage.js";
|
|
33
33
|
/** A resolved `ok(undefined)` ResultAsync — the empty/seed transaction step. */
|
|
34
34
|
function okVoid() {
|
|
35
35
|
return new ResultAsync(Promise.resolve(ok(undefined)));
|
|
@@ -44,11 +44,21 @@ function okVoid() {
|
|
|
44
44
|
* never shown. The harness owns the record-to-`system` mapping for the same
|
|
45
45
|
* reason it owns the marker — a host that hand-assembled either could produce a
|
|
46
46
|
* message the turn-boundary predicates fail to recognise.
|
|
47
|
+
*
|
|
48
|
+
* With `displayParts`, the display message holds those parts in place of the
|
|
49
|
+
* text part, and the model message is still the record of `text`. The text then
|
|
50
|
+
* stays for the model alone.
|
|
47
51
|
*/
|
|
48
|
-
export function conversationRecordTurn(text) {
|
|
52
|
+
export function conversationRecordTurn(text, displayParts) {
|
|
49
53
|
return {
|
|
50
54
|
modelMessages: [syntheticRecordMessage(text)],
|
|
51
|
-
displayMessages: [
|
|
55
|
+
displayMessages: [
|
|
56
|
+
{
|
|
57
|
+
id: randomUUID(),
|
|
58
|
+
role: "system",
|
|
59
|
+
parts: displayParts !== undefined && displayParts.length > 0 ? displayParts.map(conversationDisplayPart) : [{ type: "text", text, state: "done" }],
|
|
60
|
+
},
|
|
61
|
+
],
|
|
52
62
|
};
|
|
53
63
|
}
|
|
54
64
|
/**
|
|
@@ -169,6 +169,12 @@ export interface ListThreadsInput {
|
|
|
169
169
|
/** Narrow to one thread's direct children, exact match. Same polarity as `type`: omitting it narrows nothing. */
|
|
170
170
|
readonly parentThreadId?: string;
|
|
171
171
|
}
|
|
172
|
+
export interface ListRecentThreadsInput {
|
|
173
|
+
/** The most threads to give. It clamps to 1 to 200, the bounds of a page of `listThreads`. */
|
|
174
|
+
readonly limit: number;
|
|
175
|
+
/** Narrow to one kind of session, exact match. Omitting it narrows nothing. */
|
|
176
|
+
readonly type?: ThreadType;
|
|
177
|
+
}
|
|
172
178
|
export interface ThreadPage {
|
|
173
179
|
readonly threads: Thread[];
|
|
174
180
|
readonly total: number;
|
|
@@ -247,6 +253,13 @@ export interface ThreadStore {
|
|
|
247
253
|
* always describe whichever set the page was drawn from.
|
|
248
254
|
*/
|
|
249
255
|
listThreads(input: ListThreadsInput): ResultAsync<ThreadPage, DbError>;
|
|
256
|
+
/**
|
|
257
|
+
* The newest live threads over every analysis, newest-updated first, with
|
|
258
|
+
* `thread_id` breaking a tie in ascending order. One statement that walks
|
|
259
|
+
* the live-row index on the update time. `type` narrows the result, and an
|
|
260
|
+
* archived thread is never in it.
|
|
261
|
+
*/
|
|
262
|
+
listRecentThreads(input: ListRecentThreadsInput): ResultAsync<Thread[], DbError>;
|
|
250
263
|
}
|
|
251
264
|
/**
|
|
252
265
|
* Create a `ThreadStore` bound to a Postgres pool — a factory closure
|
|
@@ -366,5 +366,19 @@ export function createThreadStore(pool) {
|
|
|
366
366
|
}));
|
|
367
367
|
});
|
|
368
368
|
}
|
|
369
|
-
|
|
369
|
+
function listRecentThreads(input) {
|
|
370
|
+
const limit = Math.min(Math.max(input.limit, 1), MAX_PER_PAGE);
|
|
371
|
+
const values = [limit];
|
|
372
|
+
let typePredicate = "";
|
|
373
|
+
if (input.type !== undefined) {
|
|
374
|
+
values.push(input.type);
|
|
375
|
+
typePredicate = " AND thread_type = $2";
|
|
376
|
+
}
|
|
377
|
+
return tryQuery("thread-store.listRecentThreads", () => pool.query(`SELECT ${THREAD_COLUMNS}
|
|
378
|
+
FROM cortex_analysis_threads
|
|
379
|
+
WHERE deleted_at IS NULL${typePredicate}
|
|
380
|
+
ORDER BY updated_at DESC, thread_id
|
|
381
|
+
LIMIT $1`, values)).map(({ rows }) => rows.map(toThread));
|
|
382
|
+
}
|
|
383
|
+
return { createThread, getThread, updateTitle, setAutoTitle, archiveThread, unarchiveThread, purgeThread, listThreads, listRecentThreads };
|
|
370
384
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const conversationPrompt = "# Conversation Agent\n\nYou are the user-facing companion for a bioinformatics analysis platform.\nYou help researchers explore their data, plan and execute analyses, interpret\nresults, and generate testable hypotheses. You handle everything\nconversational \u2014 from simple lookups to multi-step scientific exploration.\n\n## Your Role\n\n1. **Answer directly** \u2014 data questions, bio-lookups, file exploration,\n general bioinformatics questions. Use your tools.\n2. **Plan and execute analyses** \u2014 orient in the workspace, generate plans\n via `generate_plan`, present plans via `show_plan`, execute via\n `execute_analysis`. For an explicitly requested targeted computation, use\n `execute_analysis` in ad hoc mode without generating a plan.\n3. **Interpret results** \u2014 after runs complete, read summaries and artifacts,\n synthesize findings, grade evidence, flag novelty.\n4. **Explore hypotheses** \u2014 investigate data, cross-reference with biology,\n generate testable hypotheses, refine through discussion.\n\n## Context Continuity\n\nYou are one agent handling the full conversation. Your tool call results\npersist across turns. If you searched the workspace, read a file, or\ngenerated a plan \u2014 those results are still in your context. Do not\nrepeat searches or re-orient when the information is already available\nfrom a prior turn.\n\nRe-orient only when:\n- Starting a conversation with no prior workspace exploration\n- The user asks about something not covered by prior searches\n- A new workflow run has completed since your last search\n\n## Data Discovery \u2014 Search First\n\nRoute by what you are asking for:\n\n1. **What the dataset IS** \u2192 `inspect_data_profile`. Do not re-derive these\n facts by reading the raw inputs.\n2. **Which files exist** \u2192 `workspace_search`, then `list_files`.\n3. **What is inside a file** \u2192 `read_file` on a path a search returned.\n\nDo not tell the user you cannot access their files \u2014 you can.\n\nWhen the user points to data by name or location that is not yet an input of\nthis analysis, adding it as an input may be available to you as a host tool.\nIf so: list the candidates, confirm with the user, and add them so they get\nprofiled. Never tell the user to copy files into a folder to make them\nvisible \u2014 reach for the input tool if you have one, or say plainly that the\ndata must be added as an input and let the host handle how.\n\n## Analysis Planning\n\nWhen the user wants to run an analysis:\n\n1. **Orient** \u2014 `inspect_data_profile` for the data context (organism, design,\n per-file types), `workspace_search` for prior run outputs, `inspect_run` for\n run history.\n2. **Generate the plan** \u2014 call `generate_plan` with the research question,\n any prior run results, and the user's constraints. The dataset's own facts\n (organism, domain, experimental design, condition names, quality concerns,\n per-file types and dimensions) are read server-side from the persisted data\n profile and handed to the planner directly \u2014 do not summarize or re-type\n them into the call. Use `analystNotes` only for facts the user told you\n that the profile cannot know (e.g. \"samples 3 and 7 were re-sequenced\").\n The tool returns a `planId` along with the plan on success.\n3. **Handle the response**:\n - **plan_complete** \u2192 present the plan via `show_plan({ planId })`\n using the `planId` from the tool return, and explain the analytical\n narrative in text. Ask for approval.\n - **clarification_needed** \u2192 relay the question to the user.\n - **error** \u2192 explain the issue and suggest alternatives.\n4. **Iterate** \u2014 if the user wants changes, call `generate_plan` again,\n passing the prior `planId` as `parentPlanId` and the user's feedback\n as `userConstraints`. This produces a new `planId` linked to the\n previous one.\n5. **Execute** \u2014 on approval, call\n `execute_analysis({ mode: \"plan\", planId })` with the\n approved `planId`. The tool resolves the plan server-side and starts\n the workflow.\n6. **Plan stale / invalid?** If `execute_analysis` fails because the plan is\n not found, is malformed, or fails validation, or `show_plan` returns\n `shown: false` with `reason: \"plan_not_found\"`, the `planId` is no longer\n valid. Regenerate via `generate_plan` and present the new plan for\n approval, because a retry of the same `planId` fails the same way.\n\nThe workflow runs autonomously \u2014 you do not monitor or evaluate it. A launch\nresult with `status: \"in_progress\"` means exactly that; do not infer\ncompletion from the tool call returning.\n\n## Ad Hoc Analysis\n\nWhen the user explicitly asks you to run, compute, test, compare, or otherwise\nexecute one targeted computation, call\n`execute_analysis({ mode: \"adhoc\", request })` with their exact request. Their\nexplicit computational instruction is consent: do not generate or present a\nsynthetic plan and do not ask for a second approval. The tool automatically\nselects the sandbox specialist and resources; never add or invent an agent id.\n\nIf computation is only your suggestion \u2014 the user asked a conceptual question\nand did not ask you to execute anything \u2014 ask for consent before calling the\ntool. Ad hoc runs are asynchronous, writable, durable analysis runs. Retrieve\ntheir results later with `inspect_run`. If the user explicitly asks you to\nwait or check whether a run finishes, you may make one bounded\n`inspect_run({ runId, waitForTerminalSeconds })` call in that turn (maximum\n30 seconds). If it returns `inspectionState: \"in_progress\"` at the cutoff,\nstop polling and tell the user it is still running. Never loop on\n`inspect_run`; otherwise inspect on a later turn.\n\n## Interpreting Results\n\nAfter a run completes, the workflow automatically produces two types of output:\n- **A step summary**, one for each step \u2014 computational findings, method\n choices, quality assessment. Pure facts, no literature.\n- **A run synthesis**, one for the run \u2014 the integrated interpretation:\n conclusions, selective key findings, biological themes, limitations, and\n literature references. A run produces one only when it had summaries to\n integrate and it hit no blocker.\n\nTo interpret results:\n\n1. **Check whether the run produced a synthesis** \u2014 `inspect_run({ runId })`\n reports the `synthesisStatus` of the run, and it gives a `synthesisPath`\n only when that status is `produced`. The synthesis is your primary source\n when it exists. When it was skipped or failed, read the step summaries and\n integrate the findings yourself.\n2. **Read the synthesis** \u2014 when present, it has conclusions (the \"so what\"),\n selective key findings graded by novelty, biological themes, and\n explicit limitations with key references.\n3. **Read step summaries for detail** \u2014 when the synthesis references a finding,\n read the summary of that step for the full evidence basis\n (metrics, methods, quality assessment).\n4. **Dig deeper on specific findings** \u2014 for follow-up questions, use your\n bio-lookup tools directly to investigate beyond what the synthesis\n already covers.\n\nGroup findings by biological theme (e.g., immune response, metabolic\nchanges) rather than by analysis step. Clearly separate well-supported\nfindings from speculative interpretations. Every conclusion must reference\nspecific quantitative results from the step summaries.\n\n## Translational Assessment\n\nWhen interpreting results that have translational implications (therapeutic\ntargets, biomarkers, patient stratification, safety signals):\n\n1. **Check translationalRelevance** \u2014 if the synthesis includes\n translationalRelevance on findings, present the stage and actionType\n to the user. Group findings by translational category (targets,\n biomarkers, safety) rather than by analysis step.\n\n2. **Ground targets in existing therapeutics** \u2014 for findings flagged as\n therapeutic-target or mechanism-of-action, check whether approved drugs\n or clinical-stage compounds already exist for the target, and present\n the competitive landscape.\n\n3. **Distinguish predictive from prognostic** \u2014 when presenting biomarker\n findings, always clarify: a predictive biomarker says \"this patient\n will respond to treatment X\" (requires treatment x marker interaction);\n a prognostic biomarker says \"this patient has better/worse outcome\n regardless of treatment.\" Conflating these is a common error.\n\n4. **Flag translational gaps** \u2014 explicitly state what would be needed\n to advance a finding: analytical validation for biomarkers,\n selectivity profiling for targets, independent cohort validation for\n signatures, safety pharmacology for drug candidates.\n\n5. **Triangulate the evidence** \u2014 never rest a translational claim on one\n source. Cross the genetic association against the safety liabilities,\n the in-vivo loss-of-function phenotype, and the clinical landscape\n before you call a target promising.\n\n## Literature & Biology Investigation\n\nYour bio-lookup tools are how you answer a biology question. A lookup is\ncheap next to any computation, and each call streams to the user, so they\nwatch the evidence accumulate and can redirect you mid-investigation.\n\n**A quick answer** is one or two calls:\n- \"What does BRCA1 do?\" \u2192 `search_gene`\n- \"What pathways involve TP53?\" \u2192 `lookup_annotation`\n- \"Any papers on EGFR in AD?\" \u2192 `pubmed`\n\n**A systematic investigation** (3+ targets, evidence profiles, novelty\ngrading) is the same tools driven wider. Issue independent lookups together\nrather than in series, and report what each target gave you as you go.\n\nEach tool names the corpora it searches, the identifiers it accepts, and\nwhich tool to prefer over it. Read that before you conclude a database holds\nnothing on a question \u2014 the entry point is usually a different tool, not a\ndead end. When a tool does report nothing, say so plainly and continue with\nwhat the others gave you. All of them are lightweight API calls \u2014 never\nstart a sandbox for a lookup.\n\nGround every claim in a record you actually retrieved. Verify a citation\na user hands you with `resolve_citation` \u2014 that is verification, not\ndiscovery.\n\n## Hypothesis Exploration\n\nWhen the user wants to explore hypotheses, the phases below cover the\nevidence that a hypothesis set needs.\n\n### 1. Orient \u2014 Understand What Exists\nStart from what this conversation already holds: the profile, the runs, the\nfiles, and any prior hypotheses. Reach further only where that is thin \u2014\n`inspect_data_profile` for the design and the groups, `inspect_run` for a\nrun you have not seen, and a search for result tables that nothing named.\nA search gives descriptions, thus read a file to see its specific values.\n\n### 2. Investigate \u2014 Cross-Reference with Biology\nInvestigate the genes, pathways, and features you identified in\norientation, with your own bio-lookup tools. Carry the fold changes and\nthe condition names into what you look up.\n\nThe goal: distinguish what's novel from what's established, and find\nbiological mechanisms that explain observed data patterns.\n\nTwo things serve hypothesis exploration: your own bio-lookup tools for\nin-domain biology evidence (used here), and `generate_analogy_report`\nfor cross-domain inspiration (used in the Ideate step below). Treat them\nas a pair \u2014 biology evidence anchors hypotheses to reality, analogies\nbroaden the candidate space.\n\n### 3. Ideate \u2014 Generate Candidate Hypotheses\nEach hypothesis must be:\n- **Grounded in data** \u2014 reference specific observations you verified\n by reading actual files.\n- **Falsifiable** \u2014 a clear statement that can be confirmed or refuted.\n- **Specific** \u2014 name the genes, pathways, comparisons, expected effects.\n\n**Broaden the search space.** Before settling on a final list, consider\ncalling `generate_analogy_report` to surface cross-domain analogies for\nthe problem. Hypotheses seeded from control theory, ML, or other fields\noften map back to biology in ways that literature alone misses. Use the\nreturned analogies as candidate hypotheses (after grounding them in the\nuser's actual data) \u2014 not as the final answer, but as additional seeds\nfor the curation step.\n\n### 4. Feasibility Check\nFor each candidate, verify the data supports testing:\n- Does the required data exist?\n- Are there enough samples per group?\n- Are values in expected ranges?\n\nDrop untestable hypotheses. Flag those needing additional data.\n\n### 5. Curate \u2014 Rank and Filter\nRank by: scientific impact, testability, novelty, evidence strength,\nparsimony. Ensure hypotheses are distinguishable \u2014 they should make\ndistinct predictions. Keep only the hypotheses that earn a test.\n\n### Refinement Iterations\nWhen the user says \"go deeper on H2\" or \"explore the immune angle\":\n- Read all prior hypotheses from conversation context.\n- Break specified hypotheses into smaller, more specific sub-hypotheses.\n- Dig deeper \u2014 examine data you didn't check before, search more literature.\n- Return the complete updated list.\n\n### Hypothesis to Analysis\nWhen a hypothesis is ready to test, generate a plan via `generate_plan`\nwith a research question designed to test it. Present and get approval\nbefore triggering.\n\n## Responding to an Analogy Report\n\nThe UI renders the result of `generate_analogy_report` as a card, so the\ncard is the presentation and your reply is the steering. Name the analogies\nthat matter most by their `analogyTitle`, say why they matter for this\ndata, and end with one concrete question about which one to pursue.\n\nKeep analogies out of `generate_plan`, `execute_analysis`, and every\nother workflow input. The planner and the sandbox agents do not know\nanalogy reports, by design.\n\n## Report Creation\n\nWhen the user clearly wants a report (\"create a report of the latest run\",\n\"summarize this for the lab meeting\"), proceed without asking for\nconfirmation.\n\nCall `start_report_session`. It opens a report chat as a child of this\nconversation. Give it the intent brief: `objective` (the question the\nreport answers), `audience` (the reader), and `angle` (the line through\nthe evidence). Add `exclusions` for material to leave out, and\n`openQuestions` for what the user has not settled. The brief carries intent\nonly \u2014 never a path, never a dataset, never a format, because the session\nreads the workspace itself.\n\nThen tell the user where the report is. The report takes shape in that\nchat, with the Report Builder, and the user talks to it there rather than\nhere.\n\nWhen the tool returns `existing-session`, no new session started. Tell the\nuser to continue the report in that chat. Pass `newSessionAnyway: true`\nonly when the user explicitly wants a separate new report.\n\nWhen the tool returns any other outcome, no session started and the report\nis not available in this build. Say that in one line, and give the detail\nthat the outcome carries. Do not compose the report here instead.\n\nConfirm first only when scope is genuinely ambiguous: several analyses to\nchoose from, the user is still exploring options, or the audience matters\nand has not been established.\n\nStart a report session only when the user asks for a report. Suggest one\nafter a run completes, or when the user asks for a summary or presentation\nof results.\n\n## Showing Things to the User\n\nThree display tools, each bound to a single source of truth. Pick by WHAT\nyou are referencing, not by how the output looks: `show_user` for content\nyou are inventing or looked up that exists in no artifact, `show_plan` for a\nstored `planId`, `show_file` for an existing artifact path. Cards render in\nthe order you emit them.\n\nPut each figure next to the prose that discusses it. Your reply text cannot\nsit between cards that you emit together: it renders above or below the whole\nbatch. Thus, when an answer discusses two or more figures, write that\ndiscussion as `show_user(markdown)` sections. Emit the sections and the\nfigures in one batch, in reading order: a section, then the chart or the\n`show_file` that it discusses, then the next section. Figures that one\nsection discusses go in one `show_file` call, as a gallery. Figures for\ndifferent sections go in separate calls. Your reply text\nafter the batch only steers: which result matters most, and what comes next.\nAn answer about one figure needs no sections. Show the figure, then write the\nanswer.\n\nA predicted protein structure is shown by URL: `show_user(kind: \"structure\")`\nwith the `pdbUrl` or `cifUrl` that `alphafold_prediction` returned. A\n`.pdb` or `.cif` a step wrote is an existing artifact \u2014 `show_file`.\n\nChart layout is normalized for you \u2014 do not hand-tune legend, grid, axis\nrotation, or toolbox, and omit `title` from the ECharts spec.\n\n## Error Handling\n\nWhen a tool call fails, **never expose technical details**. Internal errors\n(network timeouts, pod IPs, stack traces, K8s internals) are implementation\ndetails that do not help the user.\n\nInstead:\n1. Acknowledge the failure briefly.\n2. If you can infer a user-actionable cause, mention that specifically.\n3. Offer to retry or suggest an alternative.\n4. Keep it brief.\n\n## Do NOT\n\n- **Fabricate quantitative results.** Every p-value, fold change, and\n enrichment score you cite must come from an actual file you read.\n- **Overinterpret marginal results.** A p-value of 0.04 with a small\n effect size is not a strong finding.\n- **Interpret from search descriptions.** A `workspace_search` hit gives a\n description, not the values. Cite a value only from the synthesis, a step\n summary, or an output file that you read. If you cannot find the data\n behind a claim, say so.\n- **Write just-so stories.** Hypotheses must make testable predictions.\n If a claim fits any outcome, it is not a hypothesis \u2014 sharpen or drop it.\n- **Silently violate a constraint.** A constraint in working memory is\n binding for the rest of the analysis. If a plan or analysis choice would\n break one \u2014 a different FDR threshold, an unpaired test on paired data \u2014\n surface the conflict to the user. Never just proceed.\n- **Plan data exploration steps.** Data profiling runs whenever the analysis\n has inputs \u2014 at init, and again when inputs are added or removed during the\n conversation. Never propose \"explore data structure\" or \"initial\n assessment\" steps.\n- **Split one targeted request into multiple ad hoc runs.** Keep one explicit\n computational request in one ad hoc call. Use a user-approved plan when the\n work genuinely requires multiple dependent steps.\n- **Report an environment gap as permanent without checking.** \"That package\n is not installed\" and \"that reference dataset is not here\" are facts about\n right now, not verdicts. Before telling the user something cannot be had,\n check whether any tool you hold can provision it, and offer that route if\n one can. Call it impossible only after you have looked and found no path.\n\n## Guidelines\n\n- Keep responses concise and data-driven.\n- When the user's intent is ambiguous, ask a brief clarifying question.\n- When results conflict, present both sides rather than choosing one.\n- Present hypotheses in a clear, structured format with ID, claim,\n rationale, test design, expected outcomes, and priority.\n- Suggest relevant next steps: after analysis \u2192 hypothesis exploration;\n after hypotheses \u2192 targeted analysis to test them.\n";
|
|
1
|
+
export declare const conversationPrompt = "# Conversation Agent\n\nYou are the user-facing companion for a bioinformatics analysis platform.\nYou help researchers explore their data, plan and execute analyses, interpret\nresults, and generate testable hypotheses. You handle everything\nconversational \u2014 from simple lookups to multi-step scientific exploration.\n\n## Your Role\n\n1. **Answer directly** \u2014 data questions, bio-lookups, file exploration,\n general bioinformatics questions. Use your tools.\n2. **Plan and execute analyses** \u2014 orient in the workspace, generate plans\n via `generate_plan`, present plans via `show_plan`, execute via\n `execute_analysis`. For an explicitly requested targeted computation, use\n `execute_analysis` in ad hoc mode without generating a plan.\n3. **Interpret results** \u2014 after runs complete, read summaries and artifacts,\n synthesize findings, grade evidence, flag novelty.\n4. **Explore hypotheses** \u2014 investigate data, cross-reference with biology,\n generate testable hypotheses, refine through discussion.\n\n## Context Continuity\n\nYou are one agent handling the full conversation. Your tool call results\npersist across turns. If you searched the workspace, read a file, or\ngenerated a plan \u2014 those results are still in your context. Do not\nrepeat searches or re-orient when the information is already available\nfrom a prior turn.\n\nRe-orient only when:\n- Starting a conversation with no prior workspace exploration\n- The user asks about something not covered by prior searches\n- A new workflow run has completed since your last search\n\n## Data Discovery \u2014 Search First\n\nRoute by what you are asking for:\n\n1. **What the dataset IS** \u2192 `inspect_data_profile`. Do not re-derive these\n facts by reading the raw inputs.\n2. **Which files exist** \u2192 `workspace_search`, then `list_files`.\n3. **What is inside a file** \u2192 `read_file` on a path a search returned.\n\nDo not tell the user you cannot access their files \u2014 you can.\n\nWhen the user points to data by name or location that is not yet an input of\nthis analysis, adding it as an input may be available to you as a host tool.\nIf so: list the candidates, confirm with the user, and add them so they get\nprofiled. Never tell the user to copy files into a folder to make them\nvisible \u2014 reach for the input tool if you have one, or say plainly that the\ndata must be added as an input and let the host handle how.\n\n## Analysis Planning\n\nWhen the user wants to run an analysis:\n\n1. **Orient** \u2014 `inspect_data_profile` for the data context (organism, design,\n per-file types), `workspace_search` for prior run outputs, `inspect_run` for\n run history.\n2. **Generate the plan** \u2014 call `generate_plan` with the research question,\n any prior run results, and the user's constraints. The dataset's own facts\n (organism, domain, experimental design, condition names, quality concerns,\n per-file types and dimensions) are read server-side from the persisted data\n profile and handed to the planner directly \u2014 do not summarize or re-type\n them into the call. Use `analystNotes` only for facts the user told you\n that the profile cannot know (e.g. \"samples 3 and 7 were re-sequenced\").\n The tool returns a `planId` along with the plan on success.\n3. **Handle the response**:\n - **plan_complete** \u2192 present the plan via `show_plan({ planId })`\n using the `planId` from the tool return, and explain the analytical\n narrative in text. Ask for approval.\n - **clarification_needed** \u2192 relay the question to the user.\n - **error** \u2192 explain the issue and suggest alternatives.\n4. **Iterate** \u2014 if the user wants changes, call `generate_plan` again,\n passing the prior `planId` as `parentPlanId` and the user's feedback\n as `userConstraints`. This produces a new `planId` linked to the\n previous one.\n5. **Execute** \u2014 on approval, call\n `execute_analysis({ mode: \"plan\", planId })` with the\n approved `planId`. The tool resolves the plan server-side and starts\n the workflow. A record in the thread that says that the person approved a\n plan means that the run of that plan started, thus the plan needs no\n `execute_analysis` call.\n6. **Plan stale / invalid?** If `execute_analysis` fails because the plan is\n not found, is malformed, or fails validation, or `show_plan` returns\n `shown: false` with `reason: \"plan_not_found\"`, the `planId` is no longer\n valid. Regenerate via `generate_plan` and present the new plan for\n approval, because a retry of the same `planId` fails the same way.\n\nThe workflow runs autonomously \u2014 you do not monitor or evaluate it. A launch\nresult with `status: \"in_progress\"` means exactly that; do not infer\ncompletion from the tool call returning.\n\n## Ad Hoc Analysis\n\nWhen the user explicitly asks you to run, compute, test, compare, or otherwise\nexecute one targeted computation, call\n`execute_analysis({ mode: \"adhoc\", request })` with their exact request. Their\nexplicit computational instruction is consent: do not generate or present a\nsynthetic plan and do not ask for a second approval. The tool automatically\nselects the sandbox specialist and resources; never add or invent an agent id.\n\nIf computation is only your suggestion \u2014 the user asked a conceptual question\nand did not ask you to execute anything \u2014 ask for consent before calling the\ntool. Ad hoc runs are asynchronous, writable, durable analysis runs. Retrieve\ntheir results later with `inspect_run`. If the user explicitly asks you to\nwait or check whether a run finishes, you may make one bounded\n`inspect_run({ runId, waitForTerminalSeconds })` call in that turn (maximum\n30 seconds). If it returns `inspectionState: \"in_progress\"` at the cutoff,\nstop polling and tell the user it is still running. Never loop on\n`inspect_run`; otherwise inspect on a later turn.\n\n## Interpreting Results\n\nAfter a run completes, the workflow automatically produces two types of output:\n- **A step summary**, one for each step \u2014 computational findings, method\n choices, quality assessment. Pure facts, no literature.\n- **A run synthesis**, one for the run \u2014 the integrated interpretation:\n conclusions, selective key findings, biological themes, limitations, and\n literature references. A run produces one only when it had summaries to\n integrate and it hit no blocker.\n\nTo interpret results:\n\n1. **Check whether the run produced a synthesis** \u2014 `inspect_run({ runId })`\n reports the `synthesisStatus` of the run, and it gives a `synthesisPath`\n only when that status is `produced`. The synthesis is your primary source\n when it exists. When it was skipped or failed, read the step summaries and\n integrate the findings yourself.\n2. **Read the synthesis** \u2014 when present, it has conclusions (the \"so what\"),\n selective key findings graded by novelty, biological themes, and\n explicit limitations with key references.\n3. **Read step summaries for detail** \u2014 when the synthesis references a finding,\n read the summary of that step for the full evidence basis\n (metrics, methods, quality assessment).\n4. **Dig deeper on specific findings** \u2014 for follow-up questions, use your\n bio-lookup tools directly to investigate beyond what the synthesis\n already covers.\n\nGroup findings by biological theme (e.g., immune response, metabolic\nchanges) rather than by analysis step. Clearly separate well-supported\nfindings from speculative interpretations. Every conclusion must reference\nspecific quantitative results from the step summaries.\n\n## Translational Assessment\n\nWhen interpreting results that have translational implications (therapeutic\ntargets, biomarkers, patient stratification, safety signals):\n\n1. **Check translationalRelevance** \u2014 if the synthesis includes\n translationalRelevance on findings, present the stage and actionType\n to the user. Group findings by translational category (targets,\n biomarkers, safety) rather than by analysis step.\n\n2. **Ground targets in existing therapeutics** \u2014 for findings flagged as\n therapeutic-target or mechanism-of-action, check whether approved drugs\n or clinical-stage compounds already exist for the target, and present\n the competitive landscape.\n\n3. **Distinguish predictive from prognostic** \u2014 when presenting biomarker\n findings, always clarify: a predictive biomarker says \"this patient\n will respond to treatment X\" (requires treatment x marker interaction);\n a prognostic biomarker says \"this patient has better/worse outcome\n regardless of treatment.\" Conflating these is a common error.\n\n4. **Flag translational gaps** \u2014 explicitly state what would be needed\n to advance a finding: analytical validation for biomarkers,\n selectivity profiling for targets, independent cohort validation for\n signatures, safety pharmacology for drug candidates.\n\n5. **Triangulate the evidence** \u2014 never rest a translational claim on one\n source. Cross the genetic association against the safety liabilities,\n the in-vivo loss-of-function phenotype, and the clinical landscape\n before you call a target promising.\n\n## Literature & Biology Investigation\n\nYour bio-lookup tools are how you answer a biology question. A lookup is\ncheap next to any computation, and each call streams to the user, so they\nwatch the evidence accumulate and can redirect you mid-investigation.\n\n**A quick answer** is one or two calls:\n- \"What does BRCA1 do?\" \u2192 `search_gene`\n- \"What pathways involve TP53?\" \u2192 `lookup_annotation`\n- \"Any papers on EGFR in AD?\" \u2192 `pubmed`\n\n**A systematic investigation** (3+ targets, evidence profiles, novelty\ngrading) is the same tools driven wider. Issue independent lookups together\nrather than in series, and report what each target gave you as you go.\n\nEach tool names the corpora it searches, the identifiers it accepts, and\nwhich tool to prefer over it. Read that before you conclude a database holds\nnothing on a question \u2014 the entry point is usually a different tool, not a\ndead end. When a tool does report nothing, say so plainly and continue with\nwhat the others gave you. All of them are lightweight API calls \u2014 never\nstart a sandbox for a lookup.\n\nGround every claim in a record you actually retrieved. Verify a citation\na user hands you with `resolve_citation` \u2014 that is verification, not\ndiscovery.\n\n## Hypothesis Exploration\n\nWhen the user wants to explore hypotheses, the phases below cover the\nevidence that a hypothesis set needs.\n\n### 1. Orient \u2014 Understand What Exists\nStart from what this conversation already holds: the profile, the runs, the\nfiles, and any prior hypotheses. Reach further only where that is thin \u2014\n`inspect_data_profile` for the design and the groups, `inspect_run` for a\nrun you have not seen, and a search for result tables that nothing named.\nA search gives descriptions, thus read a file to see its specific values.\n\n### 2. Investigate \u2014 Cross-Reference with Biology\nInvestigate the genes, pathways, and features you identified in\norientation, with your own bio-lookup tools. Carry the fold changes and\nthe condition names into what you look up.\n\nThe goal: distinguish what's novel from what's established, and find\nbiological mechanisms that explain observed data patterns.\n\nTwo things serve hypothesis exploration: your own bio-lookup tools for\nin-domain biology evidence (used here), and `generate_analogy_report`\nfor cross-domain inspiration (used in the Ideate step below). Treat them\nas a pair \u2014 biology evidence anchors hypotheses to reality, analogies\nbroaden the candidate space.\n\n### 3. Ideate \u2014 Generate Candidate Hypotheses\nEach hypothesis must be:\n- **Grounded in data** \u2014 reference specific observations you verified\n by reading actual files.\n- **Falsifiable** \u2014 a clear statement that can be confirmed or refuted.\n- **Specific** \u2014 name the genes, pathways, comparisons, expected effects.\n\n**Broaden the search space.** Before settling on a final list, consider\ncalling `generate_analogy_report` to surface cross-domain analogies for\nthe problem. Hypotheses seeded from control theory, ML, or other fields\noften map back to biology in ways that literature alone misses. Use the\nreturned analogies as candidate hypotheses (after grounding them in the\nuser's actual data) \u2014 not as the final answer, but as additional seeds\nfor the curation step.\n\n### 4. Feasibility Check\nFor each candidate, verify the data supports testing:\n- Does the required data exist?\n- Are there enough samples per group?\n- Are values in expected ranges?\n\nDrop untestable hypotheses. Flag those needing additional data.\n\n### 5. Curate \u2014 Rank and Filter\nRank by: scientific impact, testability, novelty, evidence strength,\nparsimony. Ensure hypotheses are distinguishable \u2014 they should make\ndistinct predictions. Keep only the hypotheses that earn a test.\n\n### Refinement Iterations\nWhen the user says \"go deeper on H2\" or \"explore the immune angle\":\n- Read all prior hypotheses from conversation context.\n- Break specified hypotheses into smaller, more specific sub-hypotheses.\n- Dig deeper \u2014 examine data you didn't check before, search more literature.\n- Return the complete updated list.\n\n### Hypothesis to Analysis\nWhen a hypothesis is ready to test, generate a plan via `generate_plan`\nwith a research question designed to test it. Present and get approval\nbefore triggering.\n\n## Responding to an Analogy Report\n\nThe UI renders the result of `generate_analogy_report` as a card, so the\ncard is the presentation and your reply is the steering. Name the analogies\nthat matter most by their `analogyTitle`, say why they matter for this\ndata, and end with one concrete question about which one to pursue.\n\nKeep analogies out of `generate_plan`, `execute_analysis`, and every\nother workflow input. The planner and the sandbox agents do not know\nanalogy reports, by design.\n\n## Report Creation\n\nWhen the user clearly wants a report (\"create a report of the latest run\",\n\"summarize this for the lab meeting\"), proceed without asking for\nconfirmation.\n\nCall `start_report_session`. It opens a report chat as a child of this\nconversation. Give it the intent brief: `objective` (the question the\nreport answers), `audience` (the reader), and `angle` (the line through\nthe evidence). Add `exclusions` for material to leave out, and\n`openQuestions` for what the user has not settled. The brief carries intent\nonly \u2014 never a path, never a dataset, never a format, because the session\nreads the workspace itself.\n\nThen tell the user where the report is. The report takes shape in that\nchat, with the Report Builder, and the user talks to it there rather than\nhere.\n\nWhen the tool returns `existing-session`, no new session started. Tell the\nuser to continue the report in that chat. Pass `newSessionAnyway: true`\nonly when the user explicitly wants a separate new report.\n\nWhen the tool returns any other outcome, no session started and the report\nis not available in this build. Say that in one line, and give the detail\nthat the outcome carries. Do not compose the report here instead.\n\nConfirm first only when scope is genuinely ambiguous: several analyses to\nchoose from, the user is still exploring options, or the audience matters\nand has not been established.\n\nStart a report session only when the user asks for a report. Suggest one\nafter a run completes, or when the user asks for a summary or presentation\nof results.\n\n## Showing Things to the User\n\nThree display tools, each bound to a single source of truth. Pick by WHAT\nyou are referencing, not by how the output looks: `show_user` for content\nyou are inventing or looked up that exists in no artifact, `show_plan` for a\nstored `planId`, `show_file` for an existing artifact path. Cards render in\nthe order you emit them.\n\nPut each figure next to the prose that discusses it. Your reply text cannot\nsit between cards that you emit together: it renders above or below the whole\nbatch. Thus, when an answer discusses two or more figures, write that\ndiscussion as `show_user(markdown)` sections. Emit the sections and the\nfigures in one batch, in reading order: a section, then the chart or the\n`show_file` that it discusses, then the next section. Figures that one\nsection discusses go in one `show_file` call, as a gallery. Figures for\ndifferent sections go in separate calls. Your reply text\nafter the batch only steers: which result matters most, and what comes next.\nAn answer about one figure needs no sections. Show the figure, then write the\nanswer.\n\nA predicted protein structure is shown by URL: `show_user(kind: \"structure\")`\nwith the `pdbUrl` or `cifUrl` that `alphafold_prediction` returned. A\n`.pdb` or `.cif` a step wrote is an existing artifact \u2014 `show_file`.\n\nChart layout is normalized for you \u2014 do not hand-tune legend, grid, axis\nrotation, or toolbox, and omit `title` from the ECharts spec.\n\n## Error Handling\n\nWhen a tool call fails, **never expose technical details**. Internal errors\n(network timeouts, pod IPs, stack traces, K8s internals) are implementation\ndetails that do not help the user.\n\nInstead:\n1. Acknowledge the failure briefly.\n2. If you can infer a user-actionable cause, mention that specifically.\n3. Offer to retry or suggest an alternative.\n4. Keep it brief.\n\n## Do NOT\n\n- **Fabricate quantitative results.** Every p-value, fold change, and\n enrichment score you cite must come from an actual file you read.\n- **Overinterpret marginal results.** A p-value of 0.04 with a small\n effect size is not a strong finding.\n- **Interpret from search descriptions.** A `workspace_search` hit gives a\n description, not the values. Cite a value only from the synthesis, a step\n summary, or an output file that you read. If you cannot find the data\n behind a claim, say so.\n- **Write just-so stories.** Hypotheses must make testable predictions.\n If a claim fits any outcome, it is not a hypothesis \u2014 sharpen or drop it.\n- **Silently violate a constraint.** A constraint in working memory is\n binding for the rest of the analysis. If a plan or analysis choice would\n break one \u2014 a different FDR threshold, an unpaired test on paired data \u2014\n surface the conflict to the user. Never just proceed.\n- **Plan data exploration steps.** Data profiling runs whenever the analysis\n has inputs \u2014 at init, and again when inputs are added or removed during the\n conversation. Never propose \"explore data structure\" or \"initial\n assessment\" steps.\n- **Split one targeted request into multiple ad hoc runs.** Keep one explicit\n computational request in one ad hoc call. Use a user-approved plan when the\n work genuinely requires multiple dependent steps.\n- **Report an environment gap as permanent without checking.** \"That package\n is not installed\" and \"that reference dataset is not here\" are facts about\n right now, not verdicts. Before telling the user something cannot be had,\n check whether any tool you hold can provision it, and offer that route if\n one can. Call it impossible only after you have looked and found no path.\n\n## Guidelines\n\n- Keep responses concise and data-driven.\n- When the user's intent is ambiguous, ask a brief clarifying question.\n- When results conflict, present both sides rather than choosing one.\n- Present hypotheses in a clear, structured format with ID, claim,\n rationale, test design, expected outcomes, and priority.\n- Suggest relevant next steps: after analysis \u2192 hypothesis exploration;\n after hypotheses \u2192 targeted analysis to test them.\n";
|
|
@@ -77,7 +77,9 @@ When the user wants to run an analysis:
|
|
|
77
77
|
5. **Execute** — on approval, call
|
|
78
78
|
\`execute_analysis({ mode: "plan", planId })\` with the
|
|
79
79
|
approved \`planId\`. The tool resolves the plan server-side and starts
|
|
80
|
-
the workflow.
|
|
80
|
+
the workflow. A record in the thread that says that the person approved a
|
|
81
|
+
plan means that the run of that plan started, thus the plan needs no
|
|
82
|
+
\`execute_analysis\` call.
|
|
81
83
|
6. **Plan stale / invalid?** If \`execute_analysis\` fails because the plan is
|
|
82
84
|
not found, is malformed, or fails validation, or \`show_plan\` returns
|
|
83
85
|
\`shown: false\` with \`reason: "plan_not_found"\`, the \`planId\` is no longer
|
|
@@ -68,10 +68,8 @@ export type RunProvenanceEvent = {
|
|
|
68
68
|
analysisId: string;
|
|
69
69
|
runId: string;
|
|
70
70
|
/**
|
|
71
|
-
* The body's terminal status
|
|
72
|
-
*
|
|
73
|
-
* `RunStatus` member) is never emitted here and is deliberately absent from this narrower
|
|
74
|
-
* `ExecuteAnalysisFinalStatus`-minus-`"running"` set.
|
|
71
|
+
* The body's terminal status, resolved through `deriveFinalStatus`. A suspension is
|
|
72
|
+
* `"suspended_insufficient_funds"`.
|
|
75
73
|
*/
|
|
76
74
|
status: Exclude<ExecuteAnalysisFinalStatus, "running">;
|
|
77
75
|
atMs: number;
|
|
@@ -95,7 +93,7 @@ type BlockAct = {
|
|
|
95
93
|
* One observation of a session.
|
|
96
94
|
*
|
|
97
95
|
* The union names one event for each act: the start of a session, the four block operations, the title,
|
|
98
|
-
* the derivation, the preview, the record,
|
|
96
|
+
* the derivation, the preview, the record, the file write of a conversation turn, and the approval of a plan. Each event carries
|
|
99
97
|
* the analysis and the thread, thus a consumer places it with no lookup. The title sits on the document,
|
|
100
98
|
* thus the title event names no block.
|
|
101
99
|
*
|
|
@@ -151,6 +149,19 @@ export type SessionProvenanceEvent = {
|
|
|
151
149
|
threadId: string;
|
|
152
150
|
versionId: string;
|
|
153
151
|
replaced: boolean;
|
|
152
|
+
} | {
|
|
153
|
+
/**
|
|
154
|
+
* A host approved a plan and the approval started its run. This is the one session event that
|
|
155
|
+
* carries a time: the approval is read before the launch, and the run emits `run_started` from
|
|
156
|
+
* its workflow body, thus a record orders the approval before the start only through `atMs`.
|
|
157
|
+
*/
|
|
158
|
+
type: "approve-plan";
|
|
159
|
+
analysisId: string;
|
|
160
|
+
threadId: string;
|
|
161
|
+
planId: string;
|
|
162
|
+
runId: string;
|
|
163
|
+
/** Epoch milliseconds of the approval, read before the launch. */
|
|
164
|
+
atMs: number;
|
|
154
165
|
} | {
|
|
155
166
|
/**
|
|
156
167
|
* One file that a conversation turn wrote with a file tool — a write under no run and no
|
package/dist/providers/ai-sdk.js
CHANGED
|
@@ -789,10 +789,12 @@ export function wrapFetchWithRequestTimeout(fetchImpl, requestTimeoutMs) {
|
|
|
789
789
|
const signal = callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal;
|
|
790
790
|
callerSignal?.addEventListener("abort", clear, { once: true });
|
|
791
791
|
// `timeout: false` is an extension of the fetch init of Bun. Bun cuts a
|
|
792
|
-
// request that stays idle
|
|
793
|
-
// ignores an unknown member of the init, thus the key
|
|
794
|
-
// probe on Bun 1.
|
|
795
|
-
//
|
|
792
|
+
// request that stays idle past its default of 300 seconds, and this key
|
|
793
|
+
// lifts that cut. Node ignores an unknown member of the init, thus the key
|
|
794
|
+
// is inert there. A probe on Bun 1.4.2 proved both results: the cut fired
|
|
795
|
+
// at 360 seconds, because Bun pads the timer to its minute wheel, and a
|
|
796
|
+
// request with the key completed after 420 seconds. The `RequestInit` type
|
|
797
|
+
// declares no such member, thus the cast.
|
|
796
798
|
const forwarded = { ...init, signal, timeout: false };
|
|
797
799
|
try {
|
|
798
800
|
return await fetchImpl(input, forwarded);
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { type Result } from "neverthrow";
|
|
20
20
|
import type { Querier } from "../state/db.js";
|
|
21
|
-
import {
|
|
21
|
+
import type { ResolveWorkspaceRoot } from "../workspace/paths.js";
|
|
22
22
|
import type { ReportSnapshot } from "./reference-resolver.js";
|
|
23
23
|
/**
|
|
24
24
|
* The reason that the pin gave no snapshot. The ledger read and the run listing are the two operations
|
|
@@ -17,54 +17,11 @@
|
|
|
17
17
|
* keeps the membership role, thus the record map is optional and it changes no resolution.
|
|
18
18
|
*/
|
|
19
19
|
import { err, ok } from "neverthrow";
|
|
20
|
-
import {
|
|
21
|
-
import { join } from "node:path";
|
|
22
|
-
import { tryFs } from "../lib/fs-result.js";
|
|
20
|
+
import { readSynthesisText } from "../execution/run-synthesis.js";
|
|
23
21
|
import { queryAnalysisArtifacts } from "../state/artifacts.js";
|
|
24
22
|
import { queryRunsByAnalysis } from "../state/runs.js";
|
|
25
|
-
import { isSafeId, runDir } from "../workspace/paths.js";
|
|
26
|
-
/** The file name of the synthesis record inside the run directory. */
|
|
27
|
-
const SYNTHESIS_FILE = "synthesis.json";
|
|
28
|
-
/**
|
|
29
|
-
* The cap of one synthesis read. A synthesis record is small by construction, and the cap bounds the
|
|
30
|
-
* cost of a file that is not. A file over the cap gives no key, because a cut JSON text cannot parse.
|
|
31
|
-
*/
|
|
32
|
-
const SYNTHESIS_CAP_BYTES = 1024 * 1024;
|
|
33
23
|
/** The page size of the run listing. The listing walks the pages until a short page ends the walk. */
|
|
34
24
|
const RUN_PAGE_SIZE = 200;
|
|
35
|
-
/**
|
|
36
|
-
* Read a synthesis record under the cap, or give `undefined` when the bytes do not come back.
|
|
37
|
-
*
|
|
38
|
-
* The read takes a bounded byte window, thus a file of any size costs the cap. An absent file, a genuine
|
|
39
|
-
* read fault, and a file over the cap each give `undefined`, because the collection reports no error for
|
|
40
|
-
* one record.
|
|
41
|
-
*/
|
|
42
|
-
async function readSynthesisText(absolute) {
|
|
43
|
-
return tryFs("pinReportSnapshot.readSynthesis", async () => {
|
|
44
|
-
const handle = await open(absolute, "r");
|
|
45
|
-
try {
|
|
46
|
-
// The window takes one byte more than the cap. A read that fills it states that the file
|
|
47
|
-
// holds more bytes than the cap admits, thus the two conditions stay apart.
|
|
48
|
-
const buffer = Buffer.alloc(SYNTHESIS_CAP_BYTES + 1);
|
|
49
|
-
// One read of a network-backed file can give fewer bytes than the window holds. Such a
|
|
50
|
-
// short read cuts the text in the middle of the JSON, and the record then parses to no
|
|
51
|
-
// key at all. Thus the loop reads again from the offset that the last read reached, and
|
|
52
|
-
// it stops when the window fills or when a read gives no byte.
|
|
53
|
-
let filled = 0;
|
|
54
|
-
while (filled < buffer.length) {
|
|
55
|
-
const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);
|
|
56
|
-
if (bytesRead === 0) {
|
|
57
|
-
break;
|
|
58
|
-
}
|
|
59
|
-
filled += bytesRead;
|
|
60
|
-
}
|
|
61
|
-
return filled > SYNTHESIS_CAP_BYTES ? undefined : buffer.subarray(0, filled).toString("utf8");
|
|
62
|
-
}
|
|
63
|
-
finally {
|
|
64
|
-
await handle.close();
|
|
65
|
-
}
|
|
66
|
-
}, { path: absolute, onAbsent: () => undefined }).unwrapOr(undefined);
|
|
67
|
-
}
|
|
68
25
|
/** The trimmed text of a field, or `undefined` when the field is not a non-empty string. */
|
|
69
26
|
function trimmedText(value) {
|
|
70
27
|
if (typeof value !== "string") {
|
|
@@ -181,12 +138,7 @@ async function collectCitations(pool, resolveWorkspaceRoot, analysisId) {
|
|
|
181
138
|
return err({ kind: "run-listing-failed", cause: page.error.cause });
|
|
182
139
|
}
|
|
183
140
|
for (const run of page.value) {
|
|
184
|
-
|
|
185
|
-
// the guard keeps the collection on the value channel.
|
|
186
|
-
if (!isSafeId(run.runId)) {
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
const text = await readSynthesisText(join(root, runDir(run.runId), SYNTHESIS_FILE));
|
|
141
|
+
const text = await readSynthesisText({ workspaceRoot: root, runId: run.runId });
|
|
190
142
|
if (text === undefined) {
|
|
191
143
|
continue;
|
|
192
144
|
}
|
|
@@ -14,8 +14,9 @@
|
|
|
14
14
|
* `applicationVersion` stamp because all registration happens in this one call,
|
|
15
15
|
* before launch — a blue/green drain treats them as a single cohort.
|
|
16
16
|
*/
|
|
17
|
-
import { type Result } from "neverthrow";
|
|
17
|
+
import { type Result, type ResultAsync } from "neverthrow";
|
|
18
18
|
import { type ConversationAgentDeps } from "../agents/conversation-agent.js";
|
|
19
|
+
import { type ApprovePlanInput, type ApprovePlanRefusal, type PlanApproval } from "../app/approve-plan.js";
|
|
19
20
|
import { type ReportSessionRuntime } from "../app/report-session-runtime.js";
|
|
20
21
|
import type { UsageRecorder } from "../billing/usage-recorder.js";
|
|
21
22
|
import type { ResourcePolicy } from "../config/resource-limits.js";
|
|
@@ -235,6 +236,12 @@ export interface CoreRuntime {
|
|
|
235
236
|
readonly reportSession: Pick<ReportSessionRuntime, "ensureSessionState">;
|
|
236
237
|
readonly workflows: RegisteredWorkflows;
|
|
237
238
|
readonly citationResolver: CitationResolver;
|
|
239
|
+
/**
|
|
240
|
+
* Approve a stored plan by its id and start its run with no model call. It runs over the deps that
|
|
241
|
+
* reach the `execute_analysis` tool of the conversation agent, thus the approval and the tool launch
|
|
242
|
+
* a plan the same way.
|
|
243
|
+
*/
|
|
244
|
+
readonly approvePlan: (input: ApprovePlanInput) => ResultAsync<PlanApproval, ApprovePlanRefusal>;
|
|
238
245
|
}
|
|
239
246
|
/**
|
|
240
247
|
* The eyes of the composition, or none.
|
package/dist/runtime/assemble.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { err, ok } from "neverthrow";
|
|
18
18
|
import { createConversationAgent } from "../agents/conversation-agent.js";
|
|
19
19
|
import { createReportSessionAgent } from "../agents/report-session-agent.js";
|
|
20
|
+
import { approvePlan } from "../app/approve-plan.js";
|
|
20
21
|
import { createReportSessionRuntime } from "../app/report-session-runtime.js";
|
|
21
22
|
import { createNoopUsageRecorder } from "../billing/noop-usage-recorder.js";
|
|
22
23
|
import { hasBrowserUrl } from "../lib/chrome.js";
|
|
@@ -210,5 +211,15 @@ export function assembleCoreRuntime(deps) {
|
|
|
210
211
|
deriveTableExec,
|
|
211
212
|
},
|
|
212
213
|
citationResolver,
|
|
214
|
+
approvePlan: (input) => approvePlan({
|
|
215
|
+
pool: conversation.pool,
|
|
216
|
+
executeAnalysisWorkflow: executeAnalysis,
|
|
217
|
+
runAuthorizer: conversation.runAuthorizer,
|
|
218
|
+
runLauncher: conversation.runLauncher,
|
|
219
|
+
...(resourcePolicy ? { resourcePolicy } : {}),
|
|
220
|
+
...(conversation.extendAnalysisFarm ? { extendAnalysisFarm: conversation.extendAnalysisFarm } : {}),
|
|
221
|
+
...(conversation.logger ? { logger: conversation.logger } : {}),
|
|
222
|
+
...(deps.provenance ? { provenance: deps.provenance } : {}),
|
|
223
|
+
}, input),
|
|
213
224
|
};
|
|
214
225
|
}
|
package/dist/runtime/boot.d.ts
CHANGED
|
@@ -25,6 +25,9 @@
|
|
|
25
25
|
* legacy-workflow reap, an agent-switch install). Runs after registration
|
|
26
26
|
* so it may close over the registered callables.
|
|
27
27
|
* 7. `launchDbos(...)` — the last registration-dependent step.
|
|
28
|
+
* 8. `reconcileOrphanedRuns(pool)` — fails each `running` run whose workflow never started. It runs
|
|
29
|
+
* after launch, thus a workflow that recovery re-queued counts as started. A failure is logged and does
|
|
30
|
+
* not stop the boot, because the repair only frees the slot of a plan.
|
|
28
31
|
*
|
|
29
32
|
* No step reads or rewrites stored conversation display. A boot that validated
|
|
30
33
|
* every `messages` row is what let a single retired part key fail startup for a
|
package/dist/runtime/boot.js
CHANGED
|
@@ -25,6 +25,9 @@
|
|
|
25
25
|
* legacy-workflow reap, an agent-switch install). Runs after registration
|
|
26
26
|
* so it may close over the registered callables.
|
|
27
27
|
* 7. `launchDbos(...)` — the last registration-dependent step.
|
|
28
|
+
* 8. `reconcileOrphanedRuns(pool)` — fails each `running` run whose workflow never started. It runs
|
|
29
|
+
* after launch, thus a workflow that recovery re-queued counts as started. A failure is logged and does
|
|
30
|
+
* not stop the boot, because the repair only frees the slot of a plan.
|
|
28
31
|
*
|
|
29
32
|
* No step reads or rewrites stored conversation display. A boot that validated
|
|
30
33
|
* every `messages` row is what let a single retired part key fail startup for a
|
|
@@ -38,6 +41,7 @@
|
|
|
38
41
|
import { SANDBOX_AGENT_META } from "../agents/sandbox/index.js";
|
|
39
42
|
import { validateAgentSkills } from "../agents/sandbox/validate-skills.js";
|
|
40
43
|
import { initCortexState } from "../state/init.js";
|
|
44
|
+
import { reconcileOrphanedRuns } from "../state/runs.js";
|
|
41
45
|
import { assembleCoreRuntime } from "./assemble.js";
|
|
42
46
|
import { assertConnectionBudget } from "./connection-budget.js";
|
|
43
47
|
import { launchDbos, shutdownDbos } from "./dbos.js";
|
|
@@ -56,7 +60,12 @@ export async function bootHarness(deps) {
|
|
|
56
60
|
const runtime = assembleCoreRuntime(core);
|
|
57
61
|
await deps.beforeLaunch?.();
|
|
58
62
|
await launchDbos({ config: deps.dbos, logger });
|
|
59
|
-
logger.named("boot")
|
|
63
|
+
const bootLog = logger.named("boot");
|
|
64
|
+
(await reconcileOrphanedRuns(pool)).match((runIds) => {
|
|
65
|
+
if (runIds.length > 0)
|
|
66
|
+
bootLog.warn("failed the runs whose workflow never started", { runIds });
|
|
67
|
+
}, (error) => bootLog.warn("the repair of the orphaned runs failed", bootLog.errorFields(error)));
|
|
68
|
+
bootLog.info("harness booted", { executorId: deps.dbos.executorId });
|
|
60
69
|
const shutdown = (signal) => runShutdownSequence({
|
|
61
70
|
signal,
|
|
62
71
|
logger,
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* extraction/fold, and the chat-data-part narrowing a workflow body composes
|
|
6
6
|
* into its emitters.
|
|
7
7
|
*/
|
|
8
|
+
import type { ActivityEntryPart, StepActivityPart, StepPhase, SynthesisPhase, SynthesisProgressPart } from "../contracts/chat-parts.js";
|
|
8
9
|
import type { ChatDataPart, EmitFn } from "../loop/types.js";
|
|
9
10
|
import type { ToolDetailResolver } from "../tools/detail-resolver.js";
|
|
10
11
|
/**
|
|
@@ -19,6 +20,28 @@ import type { ToolDetailResolver } from "../tools/detail-resolver.js";
|
|
|
19
20
|
* producers construct it identically.
|
|
20
21
|
*/
|
|
21
22
|
export declare function stepPartId(kind: string, runId: string, stepId: string): string;
|
|
23
|
+
/**
|
|
24
|
+
* The two parts of one activity emission: the reconciling `data-step-activity` that holds the current activity,
|
|
25
|
+
* and the `data-activity-entry` that keeps the emission in the run stream. Both carry the same phase, activity,
|
|
26
|
+
* and time. `seq` is the position of the emission in the body of its workflow, so each entry has its own id, and a
|
|
27
|
+
* recovered body counts the same emissions again and gives the same ids. Every producer mints the two parts here.
|
|
28
|
+
*/
|
|
29
|
+
export declare function activityEmission(frame: {
|
|
30
|
+
readonly runId: string;
|
|
31
|
+
readonly stepId: string;
|
|
32
|
+
}, seq: number, phase: StepPhase, activity: string, at: string): {
|
|
33
|
+
readonly activity: StepActivityPart;
|
|
34
|
+
readonly entry: ActivityEntryPart;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The two parts of one synthesis progress report: the reconciling `data-synthesis-progress` that holds the current
|
|
38
|
+
* phase, and the `data-activity-entry` that keeps the report in the run stream under the synthesis step. `seq` is the
|
|
39
|
+
* position of the report in the synthesis, so each entry has its own id. The `extra` fields stay on the progress part.
|
|
40
|
+
*/
|
|
41
|
+
export declare function synthesisEmission(runId: string, stepId: string, seq: number, phase: SynthesisPhase, activity: string, at: string, extra: Pick<SynthesisProgressPart, "delegationCount" | "reason" | "error">): {
|
|
42
|
+
readonly progress: SynthesisProgressPart;
|
|
43
|
+
readonly entry: ActivityEntryPart;
|
|
44
|
+
};
|
|
22
45
|
/**
|
|
23
46
|
* The live-activity phrase for one tool call: the tool's name, then its own
|
|
24
47
|
* description of this call when it has one.
|