8000 refactor(harness): drop the startup prompt, dead tool state, and duplicate label helpers by geminixiang · Pull Request #201 · geminixiang/mikan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000 Diff view
15 changes: 15 additions & 0 deletions src/events/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,21 @@ function isValidIsoTimestampWithOffset(value: string): boolean {
);
}

const EVENT_RUN_ID_PREFIX = "event:";

export function eventRunId(filename: string): string {
return `${EVENT_RUN_ID_PREFIX}${filename.replace(/\.json$/i, "")}`;
}

export function isEventRunId(id: string): boolean {
return id.startsWith(EVENT_RUN_ID_PREFIX);
}

export function eventRunName(id: string): string | undefined {
if (!isEventRunId(id)) return undefined;
return id.slice(EVENT_RUN_ID_PREFIX.length).split(":")[0] || undefined;
}

export function parseEventPayload(content: string, filename: string): EventFilePayload {
const data: EventFileData = parseJsonSchemaValue(content, EventFileSchema, (detail, kind) =>
kind === "shape"
Expand Down
3 changes: 2 additions & 1 deletion src/events/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { reportUserFacingError } from "../observability/index.js";
import { inferConversationKind } from "../sessions/session-key.js";
import type { OfficeAddress } from "../types.js";
import {
eventRunId,
officeEventsDir,
parseEventPayload,
type EventRecord,
Expand Down Expand Up @@ -182,7 +183,7 @@ export class EventScheduler implements EventScheduleSink {
conversationKind: event.conversationKind,
user: event.userId ?? "EVENT",
text: buildEventPrompt(event),
ts: `event:${filename.replace(/\.json$/i, "")}`,
ts: eventRunId(filename),
}),
);
if (!enqueued) {
Expand Down
25 changes: 7 additions & 18 deletions src/harness/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
import { defineTool, type ToolRegistration } from "@earendil-works/pi-durable";
import { guardMcpToolResult } from "./mcp-result.js";
import { TOOL_SEARCH_TOOL_NAME as TOOL_SEARCH_TOOL } from "@earendil-works/pi-durable/tool-search";
import { LABEL_PARAMETER } from "./tools/host-fn-tool.js";
import { withLabelParameter, withoutLabel } from "./tools/host-fn-tool.js";
import { Type, type TSchema } from "typebox";

import { readStandardEnv } from "../env-manifest.js";
Expand Down Expand Up @@ -239,7 +239,12 @@ async function connectServer(
callers: exposure === "codemode" ? ["tools"] : undefined,
deferred: exposure === "deferred" ? true : undefined,
description: mcpTool.description ?? `${mcpTool.name} (MCP server "${name}")`,
parameters: ownsLabel ? mcpTool.inputSchema : withLabelParameter(mcpTool.inputSchema),
parameters: ownsLabel
? mcpTool.inputSchema
: withLabelParameter<McpInputSchema>(
{ ...mcpTool.inputSchema, type: "object" },
"required",
),
structuredOutputSchema: mcpResultSchema(mcpTool.outputSchema),
execute: async (params, api, context) => {
const result = await client.callTool(
Expand Down Expand Up @@ -269,22 +274,6 @@ function schemaProperties(schema: McpInputSchema): Record<string, unknown> {
return isRecord(schema.properties) ? schema.properties : {};
}

function withLabelParameter(schema: McpInputSchema): McpInputSchema {
const required = Array.isArray(schema.required) ? schema.required : [];
return {
...schema,
type: "object",
properties: { label: LABEL_PARAMETER, ...schemaProperties(schema) },
required: ["label", ...required],
};
}

function withoutLabel(params: unknown): Record<string, unknown> {
if (!isRecord(params)) return {};
const { label: _label, ...rest } = params;
return rest;
}

function mcpResultSchema(structuredContent: Record<string, unknown> | undefined): TSchema {
return Type.Object({
content: Type.Array(Type.Object({})),
Expand Down
48 changes: 15 additions & 33 deletions src/harness/presenter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
import { appendTriggerAttribution } from "./prompt.js";
import { START_TASK_TOOL, TASK_STATUS_TOOL } from "./tools/task.js";
import { JEV_BROWSER_TOOL } from "./tools/jev-browser.js";
import { toRunEvent, toolResultText } from "./run-events.js";
import { toRunEvent, toolLabel, toolResultText } from "./run-events.js";
import { REACT_TOOL } from "./tools/react.js";

import * as log from "../log.js";
Expand Down Expand Up @@ -72,7 +72,7 @@ function endOutstandingOperationSpans(runState: RunnerSessionState): void {
operationSpans.delete(runState);
}

function createRunStateDefaults(): RunnerSessionState {
export function createRunState(): RunnerSessionState {
return {
responder: null,
logCtx: null,
Expand Down Expand Up @@ -105,16 +105,12 @@ function createRunStateDefaults(): RunnerSessionState {
};
}

export function createRunState(): RunnerSessionState {
return createRunStateDefaults();
}

export function activateRunPresentation(
runState: RunnerSessionState,
context: RunPresentationContext,
): RunPresentation {
endOutstandingOperationSpans(runState);
Object.assign(runState, createRunStateDefaults(), {
Object.assign(runState, createRunState(), {
responder: context.responder,
logCtx: {
conversationId: context.sessionConversation,
Expand Down Expand Up @@ -161,10 +157,6 @@ export function getFinalAssistantText(session: MikanAgentSession): string {
return contentText(lastAssistant?.content ?? []);
}

export function isEventTriggerAttribution(triggerAttribution: string | undefined): boolean {
return triggerAttribution?.startsWith("[event:") === true;
}

function formatToolProgress(runState: RunnerSessionState): string {
const lines = Array.from(runState.toolProgress.values()).map((item) => {
const marker = item.status === "running" ? "•" : item.status === "error" ? "✗" : "✓";
Expand Down Expand Up @@ -432,11 +424,6 @@ type LifecycleEvent = Extract<
{ type: "compaction_start" | "compaction_end" | "auto_retry_start" | "budget_exceeded" }
>;

function toolLabel(args: unknown, toolName: string): string {
const label = isRecord(args) && typeof args.label === "string" ? args.label.trim() : "";
return label || toolName;
}

function runningTools(runState: RunnerSessionState): ToolTiming[] {
const now = Date.now();
return [...runState.pendingTools.values()]
Expand Down Expand Up @@ -795,17 +782,21 @@ function presentThinking(thinking: string, context: FrontProjectionContext): voi
);
}

function presentFinalText(text: string, context: FrontProjectionContext): void {
log.logResponse(context.logCtx, text);
}

function presentAssistantMessage(
event: RunEventOf<"assistant_message">,
context: FrontProjectionContext,
): void {
for (const thinking of event.thinking) presentThinking(thinking, context);
if (!event.text.trim() || event.callsTools || context.runState.finalResponseHandledByTool) return;
presentFinalText(event.text, context);
log.logResponse(context.logCtx, event.text);
}

function presentNotice(notice: string, errorContext: string, context: FrontProjectionContext) {
context.runState.notice = notice;
context.queue.enqueue(
() => replaceResponseWithToolProgress(context.responder, context.runState),
errorContext,
);
}

function presentRunEvent(event: RunEvent, context: FrontProjectionContext): void {
Expand All @@ -823,20 +814,11 @@ function presentRunEvent(event: RunEvent, context: FrontProjectionContext): void
presentAssistantMessage(event, context);
return;
case "compaction_started":
context.runState.notice = "_Compacting context..._";
context.queue.enqueue(
() => replaceResponseWithToolProgress(context.responder, context.runState),
"compaction start",
);
presentNotice("_Compacting context..._", "compaction start", context);
return;
case "retry_started": {
context.runState.notice = `_Retrying (${event.attempt}/${event.maxAttempts})..._`;
context.queue.enqueue(
() => replaceResponseWithToolProgress(context.responder, context.runState),
"retry",
);
case "retry_started":
presentNotice(`_Retrying (${event.attempt}/${event.maxAttempts})..._`, "retry", context);
return;
}
case "budget_exceeded": {
const text = formatBudgetStop({
reason: event.reason,
Expand Down
5 changes: 3 additions & 2 deletions src/harness/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { BuildSystemPromptOptions, ScratchListing } from "./types.js";
import { pinDirectoryNoFollow, readTextFileNoFollowIfExists } from "../file-guards.js";
import type { PinnedDirectory } from "../file-guards.js";
import * as log from "../log.js";
import { eventRunName } from "../events/index.js";

const IMAGE_MIME_TYPES: Record<string, string> = {
jpg: "image/jpeg",
Expand Down Expand Up @@ -178,8 +179,8 @@ function buildEnvDescription(sandboxType: SandboxConfig["type"], workspaceRoot:
export function resolveTriggerAttribution(
message: Pick<ConversationMessage, "id" | "text" | "userName">,
): string | undefined {
const eventIdMatch = message.id.match(/^event:([^:]+)/);
if (eventIdMatch) return `[event: ${eventIdMatch[1]}]`;
const eventName = eventRunName(message.id);
if (eventName !== undefined) return `[event: ${eventName}]`;
if (message.userName) return `@${message.userName}`;
return undefined;
}
Expand Down
12 changes: 7 additions & 5 deletions src/harness/run-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { JEV_TOOL } from "./tools/jev.js";
import { JEV_BROWSER_TOOL } from "./tools/jev-browser.js";
import type { OfficeAddress } from "../types.js";
import * as log from "../log.js";
import { errorMessage } from "../unknown-values.js";
import { errorMessage, isRecord } from "../unknown-values.js";
import type { HarnessEvent, RunEvent, RunEventListener } from "./types.js";

const TOOL_CALL_PART_TYPES = new Set(["tool_use", "toolCall", "tool-call"]);
export function toolLabel(args: unknown, toolName: string): string {
const label = isRecord(args) && typeof args.label === "string" ? args.label.trim() : "";
return label || toolName;
}

function toolDisplayLabel(toolName: string, args: unknown): string {
const label = (args as { label?: unknown } | undefined)?.label;
const text = typeof label === "string" ? label.trim() || toolName : toolName;
const text = toolLabel(args, toolName);
if ((toolName === JEV_TOOL || toolName === JEV_BROWSER_TOOL) && text !== toolName) {
return `${toolName} · ${text}`;
}
Expand Down Expand Up @@ -44,7 +46,7 @@ function assistantMessageParts(message: Extract<AssistantMessageEvent, { role: "
for (const part of message.content) {
if (part.type === "thinking") thinking.push(part.thinking);
else if (part.type === "text") text.push(part.text);
if (TOOL_CALL_PART_TYPES.has((part as { type?: string }).type ?? "")) callsTools = true;
else if (part.type === "toolCall") callsTools = true;
}
return { thinking, text: text.join("\n"), callsTools };
}
Expand Down
Loading
Loading
0