feat(iteration): implement sdk v1 miniapp runtime loop

This commit is contained in:
2026-08-05 18:30:29 +08:00
parent 486280bec0
commit d2a2fd0aff
37 changed files with 2135 additions and 60 deletions
+530 -18
View File
@@ -10,6 +10,8 @@ import {
type ConversationItem,
type Envelope,
type JsonObject,
type ToolCallRequest,
type MiniAppToolInvoke,
} from "@/runtime/protocol/lineup-v1";
import { CoreAppRegistry, type AppScope } from "@/runtime/app-management/app-registry";
import {
@@ -44,6 +46,11 @@ import type { ToolCallRecord } from "@/runtime/coordination/tool-call-state";
import { AppLifecycleManager, type AppWorkspaceSnapshot } from "@/runtime/app-management/app-lifecycle-manager";
import { AppOrchestrator } from "@/runtime/coordination/app-orchestrator";
import { ToolRouter } from "@/runtime/coordination/tool-router";
import { AgentInteractionService, type StandardInteractionRecord } from "@/runtime/coordination/agent-interaction-service";
import type { StandardInteractionRequest } from "@/runtime/coordination/standard-interaction-contract";
import type { LineUpMiniAppSDK, MiniAppToolFailure, MiniAppToolProgress } from "@/runtime/app-management/miniapp-sdk";
import { MiniAppToolStateMachine, type MiniAppToolCallRecord } from "@/runtime/coordination/miniapp-tool-state";
import { validateMiniAppToolSchema } from "@/runtime/coordination/miniapp-tool-schema";
export type RuntimeSession = {
api: string;
@@ -78,6 +85,8 @@ const CONTROL_ECHO_TYPES = new Set([
"lineup.v1.ui.event",
"lineup.v1.client.inventory",
"lineup.v1.app.result",
"lineup.v1.app.session.opened",
"lineup.v1.app.session.closed",
]);
/**
@@ -93,6 +102,8 @@ export class LineUpRuntime {
private readonly store: ConversationStore;
private readonly kernel = new InteractionKernel();
private readonly interactionService = new AgentInteractionService();
private readonly miniappTools = new MiniAppToolStateMachine();
private readonly listeners = new Set<(event: RuntimeAppEvent) => void>();
private readonly chatStateListeners = new Set<(view: ChatViewModel) => void>();
private readonly chatMessageListeners = new Set<(message: AgentChatMessage) => void>();
@@ -103,6 +114,8 @@ export class LineUpRuntime {
private readonly prepareIncoming: (item: ConversationItem) => ConversationItem | undefined;
private readonly orchestrator: AppOrchestrator;
private readonly toolRouter: ToolRouter;
/** SDK v1 inventory revision advertised by this Runtime instance. */
private readonly inventoryRevision = "catalog-1";
private transport: TransportAdapter | undefined;
private session: RuntimeSession = {
@@ -144,11 +157,73 @@ export class LineUpRuntime {
return this.kernel.snapshot();
}
public standardInteractions(): readonly StandardInteractionRecord[] {
return this.interactionService.list();
}
public miniAppToolCalls(): readonly MiniAppToolCallRecord[] {
return this.miniappTools.list();
}
/** Binds an ordinary MiniApp Tool to its Runtime instance before delivery. */
public bindToolCallToInstance(callID: string, instanceID: string): boolean {
const instance = this.lifecycle.instances.get(instanceID);
const call = this.kernel.snapshot().tool_calls.find(candidate => candidate.call_id === callID);
if (!instance || !call || ["notice", "choice", "confirm", "input"].includes(call.request.tool)) return false;
const records = this.kernel.snapshot().tool_calls.map(candidate => candidate.call_id === callID ? { ...candidate, app_scope: instance.app_scope, instance_id: instanceID } : candidate);
this.store.replaceToolCalls(records);
this.kernel.restoreToolCalls(records, this.now());
return true;
}
public workspaceSnapshot(): AppWorkspaceSnapshot { return this.lifecycle.snapshot(); }
/** Runtime-only lifecycle entry point used when a mounted App reports completion. */
public closeAppInstance(instanceID: string, error?: string): void {
if (!this.session.active) return;
const currentInstance = this.lifecycle.instances.get(instanceID);
if (!currentInstance || currentInstance.state === "stopped" || currentInstance.state === "failed") return;
const closeReason = error ? "app_failed" : "app_closed";
for (const call of this.miniappTools.list()) {
if (call.instance_id !== instanceID || !["received", "routing", "waiting_for_app", "running"].includes(call.status)) continue;
const transition = this.miniappTools.cancel(call.call_id, instanceID, "app_closed", this.now());
if (transition.disposition !== "accepted") continue;
void this.queueProtocolAction("tool-cancel", "lineup.v1.miniapp.tool.cancel", {
call_id: call.call_id,
app_scope: call.app_scope,
reason: "app_closed",
cancel_id: `miniapp-close:${instanceID}:${call.call_id}`,
});
}
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
if (currentInstance.app_session_id) {
const pendingInteractions = this.interactionService.list()
.filter(interaction => interaction.app_session_id === currentInstance.app_session_id && (interaction.status === "pending" || interaction.status === "presented"))
.map(interaction => interaction.call_id);
void this.queueProtocolAction("app-result", "lineup.v1.app.session.closed", {
app_scope: currentInstance.app_scope,
instance_id: currentInstance.instance_id,
app_session_id: currentInstance.app_session_id,
pending_interaction_call_ids: pendingInteractions,
reason: closeReason,
});
}
for (const call of this.kernel.snapshot().tool_calls) {
if (call.instance_id !== instanceID || call.status !== "pending") continue;
const transition = this.kernel.cancelToolCall(call.call_id, closeReason, this.now());
if (transition.disposition !== "accepted") continue;
void this.queueProtocolAction("tool-cancel", "lineup.v1.tool.cancel", {
call_id: call.call_id,
reason: closeReason,
cancel_id: `app-close:${instanceID}:${call.call_id}`,
});
}
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
if (currentInstance.app_scope !== "chat") {
// Surface teardown is a local Runtime → Host event. It is deliberately
// separate from App lifecycle and does not become an Agent message.
this.emit({ type: "surface-request", app_scope: currentInstance.app_scope, instance_id: instanceID, event: "close", data: {} });
}
this.orchestrator.close(instanceID, this.now(), error);
this.persistWorkspace();
runtimeLog("app.lifecycle", { action: error ? "failed" : "closed", instance_id: instanceID });
@@ -213,8 +288,8 @@ export class LineUpRuntime {
const app = this.apps.get(appScope);
const instance = this.lifecycle.instances.get(instanceID);
const conversationID = this.requireConversationID();
if (!app || app.kind !== "extension" || !app.enabled || !instance || instance.app_scope !== appScope || instance.conversation_id !== conversationID) {
throw new Error("Extension App SDK is unavailable for this instance.");
if (!app || app.kind !== "bundled" || !app.enabled || !instance || instance.app_scope !== appScope || instance.conversation_id !== conversationID) {
throw new Error("Bundled MiniApp SDK is unavailable for this instance.");
}
return {
app_scope: appScope, instance_id: instanceID, conversation_id: conversationID,
@@ -225,6 +300,89 @@ export class LineUpRuntime {
};
}
/** The restricted SDK injected into a bundled MiniApp instance. */
public openBundledMiniApp(appScope: AppScope, instanceID: string): LineUpMiniAppSDK {
const app = this.apps.get(appScope);
const instance = this.lifecycle.instances.get(instanceID);
const conversationID = this.requireConversationID();
if (!app || app.kind !== "bundled" || !app.enabled || !instance || instance.app_scope !== appScope || instance.conversation_id !== conversationID) {
throw new Error("Bundled MiniApp SDK is unavailable for this instance.");
}
const context = (): LineUpMiniAppSDK["context"] => {
const current = this.lifecycle.instances.get(instanceID);
if (!current || current.state === "stopped" || current.state === "failed" || current.state === "stopping") throw new Error("MiniApp instance is no longer running.");
return {
app_scope: appScope,
instance_id: instanceID,
conversation_id: conversationID,
app_version: app.manifest.version,
state: current.state === "starting" ? "starting" : current.state,
};
};
const scopedMessages = (afterMessageID?: string): readonly ScopedConversationItem[] => this.listAppMessages(appScope, afterMessageID, instanceID);
return {
get context() { return context(); },
inbox: {
list: afterMessageID => scopedMessages(afterMessageID),
subscribe: listener => {
const unsubscribe = this.onEvent(event => {
if (event.type !== "agent-message" || event.message.scope.app_scope !== appScope) return;
listener(event.message);
});
for (const message of scopedMessages()) listener(message);
return unsubscribe;
},
acknowledge: messageID => this.store.acknowledgeAppInbox(appScope, messageID, instanceID),
},
tools: {
subscribe: listener => {
const existing = this.miniappTools.list().filter(call => call.instance_id === instanceID && call.status === "waiting_for_app");
for (const call of existing) {
this.claimMiniAppTool(call.call_id, instanceID);
const claimed = this.miniappTools.get(call.call_id);
if (claimed) listener(claimed);
}
return this.onEvent(event => {
if (event.type !== "state") return;
for (const call of this.miniappTools.list()) if (call.instance_id === instanceID && call.status === "waiting_for_app") {
this.claimMiniAppTool(call.call_id, instanceID);
const claimed = this.miniappTools.get(call.call_id);
if (claimed) listener(claimed);
}
});
},
get: callID => this.miniappTools.get(callID)?.instance_id === instanceID ? this.miniappTools.get(callID) : undefined,
reportProgress: (callID, progress) => this.reportMiniAppToolProgress(instanceID, callID, progress),
complete: (callID, result) => this.completeMiniAppTool(instanceID, callID, result),
fail: (callID, failure: MiniAppToolFailure) => this.failMiniAppTool(instanceID, callID, failure),
cancel: (callID, reason = "app_cancelled") => this.cancelMiniAppTool(instanceID, callID, reason),
},
lifecycle: {
requestForeground: async () => {
if (!this.session.active) return { disposition: "rejected", code: "inactive" };
this.lifecycle.foreground(instanceID, this.now()); this.persistWorkspace(); this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
return { disposition: "accepted" };
},
requestBackground: async () => {
if (!this.session.active) return { disposition: "rejected", code: "inactive" };
this.lifecycle.background(instanceID, this.now()); this.persistWorkspace(); this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
return { disposition: "accepted" };
},
requestClose: async reason => {
if (!this.session.active) return { disposition: "rejected", code: "inactive" };
this.closeAppInstance(instanceID, reason); return { disposition: "accepted" };
},
},
surfaces: {
request: async (event, data) => this.requestBundledSurface(appScope, instanceID, event, data),
},
capabilities: {
request: (name, reason, input = {}) => this.queueProtocolAction("app-result", "lineup.v1.app.call", { instance_id: instanceID, app_scope: appScope, capability: name, reason, arguments: input, expires_at: new Date(Date.parse(this.now()) + 15 * 60 * 1000).toISOString() }),
},
workspace: () => this.workspaceSnapshot(),
};
}
/** @deprecated Use openApp("chat") so App selection remains registry-driven. */
public openChatApp(): ChatRuntimeSDK {
return this.openApp("chat");
@@ -247,15 +405,24 @@ export class LineUpRuntime {
};
const snapshot = this.store.open(this.requireConversationID());
this.lifecycle.restore(snapshot.app_workspace);
this.miniappTools.restore(snapshot.miniapp_tool_calls, this.now());
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
this.interactionService.restore(snapshot.standard_interactions.filter(record => record.agent_id === this.session.agent_uid && record.conversation_id === this.requireConversationID()), this.now());
this.store.replaceStandardInteractions(this.interactionService.list());
// Standard input drafts are UI-only and deliberately do not survive a Runtime restart.
for (const interaction of this.interactionService.list()) {
if (interaction.kind === "input" && (interaction.status === "pending" || interaction.status === "presented")) this.store.clearToolDraft(interaction.call_id);
}
this.kernel.restoreToolCalls(snapshot.tool_calls, this.now());
this.kernel.restoreTasks(snapshot.tasks);
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
this.store.replaceTasks(this.kernel.snapshot().tasks);
this.session.last_seq = snapshot.cursor;
if (!this.lifecycle.instances.activeFor("chat", this.requireConversationID())) {
this.orchestrator.launch("chat", this.requireConversationID(), this.now());
const launched = this.orchestrator.launch("chat", this.requireConversationID(), this.now());
this.persistWorkspace();
runtimeLog("app.lifecycle", { action: "started", app_scope: "chat" });
if (launched.disposition === "foreground") this.queueAppSessionOpened(launched.instance);
}
runtimeLog("session.restored", { restored_instances: this.lifecycle.instances.list(this.requireConversationID()).length, foreground: this.lifecycle.focus.foreground() ?? "none" });
this.emitState();
@@ -338,6 +505,19 @@ export class LineUpRuntime {
}
public submitToolCall(callID: string, result: JsonObject): boolean {
const interaction = this.interactionService.list().find(record => record.call_id === callID && (record.status === "pending" || record.status === "presented"));
if (interaction) {
const kernelTransition = this.kernel.submitToolCall(callID, this.now(), result);
if (kernelTransition.disposition !== "accepted") return false;
const transition = this.interactionService.submit(interaction.interaction_id, result, this.now());
if (transition.disposition !== "accepted") return false;
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
this.store.replaceStandardInteractions(this.interactionService.list());
this.store.clearToolDraft(callID);
void this.queueProtocolAction("tool-result", "lineup.v1.tool.result", { call_id: callID, status: "completed", result });
this.emitState();
return true;
}
const transition = this.kernel.submitToolCall(callID, this.now(), result);
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
if (transition.disposition !== "accepted") return false;
@@ -348,6 +528,19 @@ export class LineUpRuntime {
}
public cancelToolCall(callID: string, reason: string): boolean {
const interaction = this.interactionService.list().find(record => record.call_id === callID && (record.status === "pending" || record.status === "presented"));
if (interaction) {
const kernelTransition = this.kernel.cancelToolCall(callID, reason, this.now());
if (kernelTransition.disposition !== "accepted") return false;
const transition = this.interactionService.dismiss({ call_id: callID, agent_id: this.session.agent_uid, conversation_id: this.requireConversationID() }, this.now());
if (transition.disposition !== "accepted") return false;
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
this.store.replaceStandardInteractions(this.interactionService.list());
this.store.clearToolDraft(callID);
void this.queueProtocolAction("tool-cancel", "lineup.v1.tool.cancel", { call_id: callID, reason });
this.emitState();
return true;
}
const transition = this.kernel.cancelToolCall(callID, reason, this.now());
this.store.replaceToolCalls(this.kernel.snapshot().tool_calls);
if (transition.disposition !== "accepted") return false;
@@ -385,6 +578,78 @@ export class LineUpRuntime {
return this.store.acknowledgeAppInbox("chat", messageID);
}
public claimMiniAppTool(callID: string, instanceID: string): boolean {
const transition = this.miniappTools.start(callID, instanceID, this.now());
if (transition.disposition !== "accepted") return false;
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
this.emit({ type: "state", snapshot: this.kernel.snapshot() });
return true;
}
public reportMiniAppToolProgress(instanceID: string, callID: string, progress: MiniAppToolProgress): Promise<CommandReceipt> {
if (!validProgress(progress)) return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
const transition = this.miniappTools.progress(callID, instanceID, this.now());
if (transition.disposition !== "accepted") return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
return this.queueProtocolAction("app-result", "lineup.v1.miniapp.tool.progress", {
call_id: callID,
app_scope: transition.record.app_scope,
instance_id: instanceID,
progress,
});
}
public completeMiniAppTool(instanceID: string, callID: string, result: JsonObject): Promise<CommandReceipt> {
const current = this.miniappTools.get(callID);
if (!current || current.instance_id !== instanceID) return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
const app = this.apps.get(current.app_scope);
const definition = app?.manifest.tools.find(tool => tool.name === current.tool_id);
if (!app || !definition || !validateMiniAppToolSchema(result, definition.output_schema)) return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
const transition = this.miniappTools.submit(callID, instanceID, result, this.now());
if (transition.disposition !== "accepted") return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
return this.queueProtocolAction("tool-result", "lineup.v1.miniapp.tool.result", {
call_id: callID,
app_scope: current.app_scope,
instance_id: instanceID,
status: "completed",
result,
result_id: `miniapp-result:${callID}`,
});
}
public failMiniAppTool(instanceID: string, callID: string, failure: MiniAppToolFailure): Promise<CommandReceipt> {
const current = this.miniappTools.get(callID);
if (!current || current.instance_id !== instanceID) return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
const transition = this.miniappTools.fail(callID, instanceID, failure.code ?? "app_failed", this.now());
if (transition.disposition !== "accepted") return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
return this.queueProtocolAction("tool-result", "lineup.v1.miniapp.tool.result", {
call_id: callID,
app_scope: current.app_scope,
instance_id: instanceID,
status: "failed",
error: failure.message,
...(failure.code ? { error_code: failure.code } : {}),
result_id: `miniapp-result:${callID}`,
});
}
public cancelMiniAppTool(instanceID: string, callID: string, reason: string): Promise<CommandReceipt> {
const current = this.miniappTools.get(callID);
if (!current || current.instance_id !== instanceID) return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
const transition = this.miniappTools.cancel(callID, instanceID, "runtime_cancelled", this.now());
if (transition.disposition !== "accepted") return Promise.resolve({ disposition: "rejected", code: "invalid_action" });
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
return this.queueProtocolAction("tool-cancel", "lineup.v1.miniapp.tool.cancel", {
call_id: callID,
app_scope: current.app_scope,
instance_id: instanceID,
reason,
cancel_id: `miniapp-cancel:${callID}`,
});
}
/** Runtime-owned durable protocol result path for non-Chat host modules. */
public async queueProtocolAction(
kind: Exclude<OutboxEntry["kind"], "text">,
@@ -392,7 +657,9 @@ export class LineUpRuntime {
payload: JsonObject,
): Promise<CommandReceipt> {
if (!this.session.active) return { disposition: "rejected", code: "inactive" };
const localID = this.newID(kind);
const controlID = typeof payload.control_id === "string" ? payload.control_id : undefined;
const cancelID = typeof payload.cancel_id === "string" ? payload.cancel_id : undefined;
const localID = controlID ? `interaction-dismiss:${controlID}` : cancelID ? `tool-cancel:${cancelID}` : this.newID(kind);
const envelope: Envelope = {
v: 1,
id: this.newID("msg"),
@@ -463,6 +730,16 @@ export class LineUpRuntime {
data: {},
});
}
if (action.type === "chat.continue_app_session") {
const old = this.lifecycle.instances.list(this.requireConversationID()).find(instance => instance.app_session_id === action.app_session_id);
if (!old || old.state !== "stopped" && old.state !== "failed" || old.app_scope === "chat") return { disposition: "rejected", code: "invalid_action" };
const launched = this.orchestrator.launch(old.app_scope, this.requireConversationID(), this.now(), { continued_from_app_session_id: action.app_session_id });
if (launched.disposition !== "foreground") return { disposition: "rejected", code: "invalid_action" };
this.persistWorkspace();
this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
this.queueAppSessionOpened(launched.instance);
return { disposition: "accepted" };
}
return { disposition: "rejected", code: "invalid_action" };
}
@@ -485,12 +762,92 @@ export class LineUpRuntime {
this.emit({ type: "scope-rejected", reason: scopeResolution.reason, raw: payload });
return;
}
const route = this.toolRouter.route(payload, { app_scope: scopeResolution.scope.app_scope, conversation_id: this.requireConversationID() });
const route = this.toolRouter.route(payload, { app_scope: scopeResolution.scope.app_scope, conversation_id: this.requireConversationID(), inventory_revision: this.inventoryRevision });
if (route.disposition === "rejected") {
runtimeLog("tool.rejected", { reason: route.code });
this.emit({ type: "scope-rejected", reason: route.code === "scope_mismatch" ? "scope_mismatch" : "invalid_scope", raw: payload });
return;
}
if (route.disposition === "interactive" && route.app_session_id) {
const appSession = this.lifecycle.instances.list(this.requireConversationID()).find(instance => instance.app_session_id === route.app_session_id);
if (!appSession) {
runtimeLog("interaction.rejected", { reason: "app_session_context_invalid", app_session_id: route.app_session_id });
this.emit({ type: "scope-rejected", reason: "scope_mismatch", raw: payload });
return;
}
}
if (route.disposition === "dismiss") {
const transition = this.interactionService.dismiss({
call_id: route.call_id,
agent_id: this.session.agent_uid,
conversation_id: this.requireConversationID(),
}, this.now());
if (transition.disposition === "accepted") {
this.store.replaceStandardInteractions(this.interactionService.list());
void this.queueProtocolAction("tool-cancel", "lineup.v1.tool.cancel", {
call_id: route.call_id,
reason: route.reason ?? "agent_dismissed",
control_id: route.control_id,
});
runtimeLog("interaction.dismissed", { call_id: route.call_id, control_id: route.control_id });
} else if (transition.disposition !== "invalid_transition") {
runtimeLog("interaction.dismiss_ignored", { call_id: route.call_id, control_id: route.control_id, disposition: transition.disposition });
}
return;
}
let miniAppInstanceID: string | undefined;
if (route.disposition === "miniapp") {
const requested = route.instance_id ? this.lifecycle.instances.get(route.instance_id) : undefined;
if (requested && (requested.app_scope !== route.app_scope || requested.conversation_id !== this.requireConversationID() || ["stopped", "failed", "stopping"].includes(requested.state))) {
runtimeLog("tool.rejected", { reason: "app_instance_not_found" });
this.emit({ type: "scope-rejected", reason: "scope_mismatch", raw: payload });
return;
}
const existing = requested ?? this.lifecycle.instances.activeFor(route.app_scope, this.requireConversationID());
if (route.handling === "launch" || route.handling === "foreground" || (!existing && route.requires_foreground)) {
const launched = this.orchestrator.launch(route.app_scope, this.requireConversationID(), this.now(), { instance_id: route.instance_id });
if (launched.disposition !== "foreground") {
runtimeLog("tool.rejected", { reason: launched.code });
this.emit({ type: "scope-rejected", reason: "invalid_scope", raw: payload });
return;
}
miniAppInstanceID = launched.instance.instance_id;
this.persistWorkspace();
this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
this.queueAppSessionOpened(launched.instance);
} else if (!existing) {
// A direct/background operation may create an instance without
// stealing focus from the current App. The orchestrator performs the
// common creation and focus bookkeeping; immediately backgrounding
// here leaves the prior foreground instance active.
const launched = this.orchestrator.launch(route.app_scope, this.requireConversationID(), this.now(), { instance_id: route.instance_id });
if (launched.disposition !== "foreground") {
runtimeLog("tool.rejected", { reason: launched.code });
this.emit({ type: "scope-rejected", reason: "invalid_scope", raw: payload });
return;
}
this.lifecycle.background(launched.instance.instance_id, this.now());
miniAppInstanceID = launched.instance.instance_id;
this.persistWorkspace();
this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
this.queueAppSessionOpened(launched.instance);
} else {
miniAppInstanceID = existing.instance_id;
}
const created = this.miniappTools.receive({
call_id: route.call.call_id,
tool_id: route.call.tool_id,
inventory_revision: route.call.inventory_revision,
app_scope: route.app_scope,
...(miniAppInstanceID ? { instance_id: miniAppInstanceID } : {}),
conversation_id: this.requireConversationID(),
input: route.call.input,
created_at: this.now(),
});
if (created.disposition === "invalid_transition" || created.disposition === "invalid_scope") return;
if (created.disposition === "accepted" && miniAppInstanceID) this.miniappTools.route(route.call.call_id, miniAppInstanceID, this.now());
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
}
const result = this.kernel.ingest({ raw: payload, source: "sync", transport_id: String(message.message_seq), received_at: this.now() });
this.store.replaceToolCalls(result.snapshot.tool_calls);
this.store.replaceTasks(result.snapshot.tasks);
@@ -507,26 +864,56 @@ export class LineUpRuntime {
received_at: receivedAt,
message_seq: message.message_seq,
};
const targetScope = route.disposition === "launch" ? route.app_scope : scopeResolution.scope.app_scope;
this.store.enqueueAppInbox({
message_id: messageID,
app_scope: targetScope,
conversation_id: scopeResolution.scope.conversation_id,
item,
received_at: receivedAt,
message_seq: message.message_seq,
});
const targetScope = route.disposition === "launch" || route.disposition === "miniapp" ? route.app_scope : scopeResolution.scope.app_scope;
if (route.disposition !== "interactive") {
this.store.enqueueAppInbox({
message_id: messageID,
app_scope: targetScope,
conversation_id: scopeResolution.scope.conversation_id,
item,
received_at: receivedAt,
message_seq: message.message_seq,
...(route.disposition === "miniapp" && miniAppInstanceID ? { instance_id: miniAppInstanceID } : {}),
});
}
this.emit({ type: "agent-message", message: scoped });
if (targetScope === "chat") this.emitChatMessage(scoped);
if (route.disposition === "interactive" || targetScope === "chat") this.emitChatMessage(scoped);
if (route.disposition === "interactive" && item.kind === "tool-call") {
const interactionRequest = standardRequestFromToolCall(item.call, receivedAt);
if (interactionRequest) {
const chatInstance = this.lifecycle.instances.activeFor("chat", this.requireConversationID());
const created = this.interactionService.create({
interaction_id: this.newID("interaction"),
call_id: item.call.call_id,
agent_id: this.session.agent_uid,
conversation_id: this.requireConversationID(),
interact_instance_id: chatInstance?.instance_id ?? "chat",
...(route.app_session_id ? { app_session_id: route.app_session_id } : {}),
request: interactionRequest,
created_at: receivedAt,
});
if (created.disposition === "invalid_request") runtimeLog("interaction.rejected", { reason: "invalid_request" });
if (created.disposition === "accepted") {
const presented = this.interactionService.present(created.record.interaction_id, receivedAt);
this.store.replaceStandardInteractions(this.interactionService.list());
if (presented.disposition === "accepted" && presented.record.status === "completed") {
void this.queueProtocolAction("tool-result", "lineup.v1.tool.result", { call_id: item.call.call_id, status: "completed", result: {} });
}
}
}
}
}
if (route.disposition === "launch") {
const prior = this.lifecycle.instances.activeFor(route.app_scope, this.requireConversationID());
const launched = this.orchestrator.launch(route.app_scope, this.requireConversationID(), this.now(), { instance_id: route.instance_id });
if (launched.disposition === "foreground") {
this.persistWorkspace();
runtimeLog("app.lifecycle", { action: "launched", app_scope: route.app_scope, instance_id: launched.instance.instance_id, prior_instance_id: launched.previous?.instance_id ?? "none" });
this.emit({ type: "app-lifecycle", workspace: this.workspaceSnapshot(), reason: "launched" });
if (!prior) this.queueAppSessionOpened(launched.instance);
}
}
if (route.disposition === "miniapp") this.emit({ type: "state", snapshot: this.kernel.snapshot() });
this.emit({ type: "state", snapshot: result.snapshot });
this.emitState();
}
@@ -538,7 +925,18 @@ export class LineUpRuntime {
this.emit({ type: "delivery", local_id: entry.local_id, ...(item ? { item } : {}) });
return;
}
try {
const parsed = JSON.parse(entry.payload) as { type?: string; payload?: { call_id?: unknown; status?: unknown } };
if (parsed.type === "lineup.v1.miniapp.tool.result" && typeof parsed.payload?.call_id === "string" && parsed.payload.status === "completed") {
this.miniappTools.complete(parsed.payload.call_id, this.now());
this.store.replaceMiniAppToolCalls(this.miniappTools.list());
}
} catch {
// Outbox payload validation happened before enqueue; a malformed local
// payload is still acknowledged rather than retried forever.
}
this.store.acknowledgeOutbox(entry.local_id);
this.emitState();
}
private handleOutboxFailure(entry: OutboxEntry, reason: unknown): void {
@@ -564,6 +962,17 @@ export class LineUpRuntime {
private chatView(): ChatViewModel {
const snapshot = this.kernel.snapshot();
const interactions = this.interactionService.list();
const appSessions = this.lifecycle.instances.list(this.currentConversationID()).flatMap(instance => instance.app_session_id ? [{
app_session_id: instance.app_session_id,
app_scope: instance.app_scope,
instance_id: instance.instance_id,
state: instance.state,
interaction_count: interactions.filter(interaction => interaction.app_session_id === instance.app_session_id).length,
pending_interaction_count: interactions.filter(interaction => interaction.app_session_id === instance.app_session_id && (interaction.status === "pending" || interaction.status === "presented")).length,
history: appSessionHistory(interactions.filter(interaction => interaction.app_session_id === instance.app_session_id)),
...(instance.continued_from_app_session_id ? { continued_from_app_session_id: instance.continued_from_app_session_id } : {}),
}] : []);
return {
app_scope: "chat",
conversation_id: this.currentConversationID(),
@@ -571,15 +980,33 @@ export class LineUpRuntime {
agent_presence: snapshot.agent_presence,
tool_calls: snapshot.tool_calls,
tasks: snapshot.tasks,
app_sessions: appSessions,
};
}
private listChatMessages(afterMessageID?: string): readonly AgentChatMessage[] {
return this.listAppMessages("chat", afterMessageID) as readonly AgentChatMessage[];
const inboxMessages = this.listAppMessages("chat", afterMessageID) as readonly AgentChatMessage[];
const knownIDs = new Set(inboxMessages.map(message => message.message_id));
const interactionMessages = this.store.snapshot().items
.filter(entry => entry.item.kind === "tool-call" && entry.item.envelope?.sender.kind === "agent")
.map(entry => {
const messageID = entry.item.id ?? entry.local_id;
return {
message_id: messageID,
scope: { app_scope: "chat" as const, conversation_id: this.requireConversationID() },
item: entry.item,
received_at: entry.created_at,
...(entry.message_seq !== undefined ? { message_seq: entry.message_seq } : {}),
} satisfies AgentChatMessage;
})
.filter(message => !knownIDs.has(message.message_id));
const merged = [...inboxMessages, ...interactionMessages];
const start = afterMessageID ? merged.findIndex(entry => entry.message_id === afterMessageID) + 1 : 0;
return merged.slice(Math.max(0, start));
}
private listAppMessages(appScope: AppScope, afterMessageID?: string): readonly ScopedConversationItem[] {
const entries = this.store.listAppInbox(appScope);
private listAppMessages(appScope: AppScope, afterMessageID?: string, instanceID?: string): readonly ScopedConversationItem[] {
const entries = this.store.listAppInbox(appScope, instanceID);
const start = afterMessageID ? entries.findIndex(entry => entry.message_id === afterMessageID) + 1 : 0;
return entries.slice(Math.max(0, start)).map(entry => ({
message_id: entry.message_id,
@@ -603,10 +1030,43 @@ export class LineUpRuntime {
private persistWorkspace(): void { this.store.replaceAppWorkspace(this.lifecycle.snapshot()); }
private queueAppSessionOpened(instance: { app_scope: AppScope; instance_id: string; app_session_id?: string }): void {
if (!instance.app_session_id) return;
void this.queueProtocolAction("app-result", "lineup.v1.app.session.opened", {
app_scope: instance.app_scope,
instance_id: instance.instance_id,
app_session_id: instance.app_session_id,
});
}
private emit(event: RuntimeAppEvent): void {
for (const listener of this.listeners) listener(event);
}
/**
* Surface requests from a bundled MiniApp stay inside the local Runtime →
* Host path. They are not Agent protocol messages: the Runtime checks the
* instance scope and normalizes the app identity before emitting a local
* event for the trusted Host adapter.
*/
private requestBundledSurface(
appScope: AppScope,
instanceID: string,
event: "open" | "patch" | "close",
data: JsonObject,
): CommandReceipt {
const app = this.apps.get(appScope);
const instance = this.lifecycle.instances.get(instanceID);
const conversationID = this.currentConversationID();
if (!this.session.active || !conversationID || !app || app.kind !== "bundled" || !app.enabled
|| !instance || instance.app_scope !== appScope || instance.conversation_id !== conversationID
|| instance.state === "stopped" || instance.state === "failed" || instance.state === "stopping") {
return { disposition: "rejected", code: "invalid_action" };
}
this.emit({ type: "surface-request", app_scope: appScope, instance_id: instanceID, event, data: { ...data } });
return { disposition: "accepted" };
}
private requireConversationID(): string {
const conversationID = this.currentConversationID();
if (!conversationID) throw new Error("LineUpRuntime has no active conversation.");
@@ -619,6 +1079,58 @@ function boundedFailure(value: string): string {
return message ? message.slice(0, 500) : "Extension App failed.";
}
function appSessionHistory(records: readonly StandardInteractionRecord[]): readonly { id: string; role: "agent" | "user"; text: string }[] {
const history: Array<{ id: string; role: "agent" | "user"; text: string }> = [];
for (const record of records) {
const request = record.request;
const prompt = "prompt" in request ? `${request.title}: ${request.prompt}` : `${request.title}: ${request.message}`;
history.push({ id: `${record.interaction_id}:agent`, role: "agent", text: prompt.slice(0, 1000) });
if (record.result?.outcome === "answered") {
const answer = record.result.answer;
const text = "text" in answer && typeof answer.text === "string" ? answer.text : "approved" in answer ? (answer.approved ? "已确认" : "已取消") : `选择:${String(answer.action_id)}`;
history.push({ id: `${record.interaction_id}:user`, role: "user", text: text.slice(0, 1000) });
} else if (record.result?.outcome === "cancelled" || record.result?.outcome === "expired") {
history.push({ id: `${record.interaction_id}:user`, role: "user", text: record.result.outcome === "cancelled" ? "已取消" : "已超时" });
}
}
return history;
}
function standardRequestFromToolCall(call: ToolCallRequest, createdAt: string): StandardInteractionRequest | undefined {
const expiresIn = call.expires_at === undefined ? undefined : Date.parse(call.expires_at) - Date.parse(createdAt);
if (expiresIn !== undefined && !Number.isFinite(expiresIn)) return undefined;
if (call.tool === "notice" && call.notice) {
return { kind: "notice", title: call.title, message: call.notice.message, ...(call.notice.dismiss_label ? { dismiss_label: call.notice.dismiss_label } : {}) };
}
if (call.tool === "choice" && call.action_group?.mode === "single-choice") {
return { kind: "choice", title: call.title, prompt: call.prompt, mode: "single-choice", actions: call.action_group.actions, ...(expiresIn !== undefined ? { expires_in_ms: expiresIn } : {}) };
}
if (call.tool === "confirm" && call.confirm) {
return { kind: "confirm", title: call.title, prompt: call.prompt, approve_label: call.confirm.approve_label, cancel_label: call.confirm.cancel_label, ...(expiresIn !== undefined ? { expires_in_ms: expiresIn } : {}) };
}
if (call.tool === "input" && call.form?.fields.length === 1) {
const field = call.form.fields[0];
if (field.type !== "text" && field.type !== "textarea") return undefined;
return {
kind: "input",
title: call.title,
prompt: call.prompt,
field: { id: field.id, label: field.label, type: field.type, required: field.required, ...(field.placeholder ? { placeholder: field.placeholder } : {}), ...(field.max_length !== undefined ? { max_length: field.max_length } : {}) },
submit_label: call.form.submit_label,
cancel_label: call.form.cancel_label,
...(expiresIn !== undefined ? { expires_in_ms: expiresIn } : {}),
};
}
return undefined;
}
function validProgress(progress: MiniAppToolProgress): boolean {
return progress !== null && typeof progress === "object"
&& (progress.percent === undefined || (typeof progress.percent === "number" && Number.isFinite(progress.percent) && progress.percent >= 0 && progress.percent <= 100))
&& (progress.status === undefined || (typeof progress.status === "string" && progress.status.length <= 80))
&& (progress.detail === undefined || (typeof progress.detail === "string" && progress.detail.length <= 500));
}
/** Deliberately excludes identities, conversation IDs, message bodies and Tool arguments. */
function runtimeLog(event: string, fields: Record<string, string | number>): void {
console.info("[LineUp Runtime]", event, fields);