mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-15 13:52:39 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7595325095 | ||
|
|
f1b097a563 | ||
|
|
76804cba66 |
@@ -39,11 +39,11 @@
|
||||
<img src="https://paseo.sh/mobile-mockup.png" alt="Paseo mobile app" width="100%">
|
||||
</p>
|
||||
|
||||
Paseo is an open source agentic development environment for desktop, mobile, web, and CLI. Open the desktop app and work: agents, editor, terminals, diffs, pull requests, and a browser in one window. Run many agents at once, each in its own worktree, on one machine or several. The mobile app is the full app, native on iOS and Android.
|
||||
Paseo is a desktop, mobile, web, and CLI app for coding agents. Open the desktop app and work: agents, editor, terminals, diffs, pull requests, and a browser in one window. Run many agents at once, each in its own worktree, on one machine or several. The mobile app is the full app, native on iOS and Android.
|
||||
|
||||
- **Parallel agents:** Run many agents at once, each in its own worktree.
|
||||
- **Built-in orchestration:** Agents in Paseo can create worktrees, launch other agents, and talk to them, across providers.
|
||||
- **Complete development workflow:** Edit files, review diffs, open pull requests, and run terminals, in split panes you arrange how you want.
|
||||
- **Full IDE:** Edit files, review diffs, open pull requests, and run terminals, in split panes you arrange how you want.
|
||||
- **Self-hosted:** Agents run on your machine with your full dev environment. Use your tools, your configs, and your skills.
|
||||
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
|
||||
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
|
||||
|
||||
+2
-28
@@ -69,11 +69,11 @@ the marker. Closing a tab sets that client's label to `false`. Any `true` client
|
||||
open. Detach clears the parent and every open-tab label. The surviving child therefore becomes a
|
||||
normal root agent immediately, and closing its still-open tab archives it.
|
||||
|
||||
Runtime ownership is resolved from explicit workspace ID and caller context, never from `cwd`. Workspace creation is a separate operation with `local | worktree` isolation; agent creation reuses that workspace unless a new workspace is explicitly requested.
|
||||
Runtime ownership is resolved from explicit workspace ID and caller context, never from `cwd`. Workspace creation is a separate operation with `local | worktree` isolation; agent creation only selects an existing workspace.
|
||||
|
||||
Users can also detach an existing subagent from the subagents track. Detach is deliberately a manual lifecycle gesture, not an agent-facing MCP tool. It removes the parent and open-tab lifecycle labels: it does not stop, archive, move, or restart the agent. The agent keeps its current `cwd` and `workspaceId`, leaves the former parent's track, and behaves like a root agent for tab close, workspace activity, and future parent archive.
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` only for truly fire-and-forget agents or prompts.
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and background prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` only for truly fire-and-forget agents or prompts.
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
A watched child that closes before its finish event also notifies the caller so delegated work cannot disappear silently during archive or workspace teardown.
|
||||
@@ -84,32 +84,6 @@ Some providers can create their own child sessions inside one provider runtime.
|
||||
|
||||
The provider still owns the underlying runtime. Paseo keeps an agent record so the child can be opened, tracked, archived, and cascaded with the parent, but prompts and history hydration route through the provider adapter for that native child handle.
|
||||
|
||||
## Background workspaces
|
||||
|
||||
`workspace.background` controls discovery only. Background workspaces contain ordinary durable
|
||||
agents and terminals: provider history, plugin hooks, parentage, archive, and restart recovery
|
||||
keep their normal behavior. Visibility is creation-only; selecting an existing workspace cannot
|
||||
change it. New workspaces default to false, inherit the caller workspace's value when an agent
|
||||
creates one without an override, and accept explicit true or false.
|
||||
|
||||
The daemon derives agent discovery from workspace ownership. Default workspace and agent lists,
|
||||
including History requests, exclude background work; `filter.includeBackground` includes it.
|
||||
Exact-ID operations bypass discovery filtering. The app replicates both kinds and filters only
|
||||
its sidebar with **Show background**, so direct navigation and restored tabs remain available.
|
||||
|
||||
Sequenced directories keep complete canonical collections. A filtered read must never replace
|
||||
those collections with its subset. Inclusive and default observations have distinct cursor
|
||||
scopes, so changing scope requires a fresh snapshot rather than reusing an incomplete cache.
|
||||
Clients gate creation and inclusive discovery on `features.backgroundWorkspaces`.
|
||||
|
||||
### Private daemon helpers
|
||||
|
||||
Branch-name and commit-message generators still use private disposable internal runtimes.
|
||||
`AgentManager` does not persist them or their provider sessions, excludes them from public
|
||||
discovery and plugin hooks, and drops their timelines on archive. An archived helper retains
|
||||
its exact-ID result briefly to cover completion before a waiter attaches. This internal
|
||||
lifecycle is separate from public workspace visibility and is not a public creation option.
|
||||
|
||||
## Archive
|
||||
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
@@ -345,10 +345,6 @@ join active work or reuse committed stages. A persisted resource alone cannot pr
|
||||
that a provider accepted its initial prompt. Interrupted side effects with no conclusive
|
||||
receipt return an unknown outcome instead of being repeated.
|
||||
|
||||
Agent registration commits creation. Rejecting the first prompt is a turn error on that
|
||||
agent; reporting creation failure leaves an orphaned agent and invites another Create.
|
||||
Receipt replay must not resend the prompt.
|
||||
|
||||
`packages/client/src/creation/` owns capability selection and legacy orchestration.
|
||||
Callers always pass the initial prompt to agent creation. On an older host, the client
|
||||
adapts keyed creation to the legacy create/send sequence; it cannot continue that
|
||||
|
||||
@@ -61,8 +61,6 @@ Core direct providers: `claude` (in `providers/claude/agent.ts`), `codex` (`code
|
||||
|
||||
Claude first-party model metadata lives in `packages/server/src/server/agent/providers/claude/model-manifest.ts`. When adding or updating a Claude model, update that manifest only; the model picker thinking options and Claude-specific feature gates are derived from the manifest. Do not add model-specific Claude capability lists in feature code.
|
||||
|
||||
Keep the curated Claude catalog: `supportedModels()` has historically omitted older versions and carries less metadata. Discovery is only an opt-in visibility gate, not a replacement catalog or an entitlement guarantee. Claude Code v2.1.197 added `resolvedModel` to disambiguate alias rows; a bare family alias does not establish access to a particular version. Explicit user-configured models must remain selectable when discovery fails or omits them.
|
||||
|
||||
Paseo tools are not implemented as MCP tools internally. They live in a shared tool catalog under `packages/server/src/server/agent/tools/`; MCP is only the fallback adapter. The daemon resolves `agents.providers.<provider>.paseoTools` by the exact provider ID. The catalog policy belongs to the caller: it filters the tools exposed to the current agent. When that agent calls `create_agent`, the child receives the policy for the child provider ID; the caller's policy is not inherited.
|
||||
|
||||
A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume the already-filtered `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/mcp/agents`; the MCP server builds the same policy-filtered catalog for that caller. Filtering is enforced at catalog registration in both paths. Browser tools remain subject to the daemon browser-tools setting and browser-host availability.
|
||||
|
||||
+5
-19
@@ -223,7 +223,7 @@ submission. Overlapping sends settle independently rather than collapsing to one
|
||||
message.
|
||||
|
||||
Daemons advertising `server_info.features.canonicalSubmittedPrompts` guarantee that every accepted
|
||||
human prompt carrying a client message id is recorded and streamed as a canonical `user_message` with that
|
||||
prompt carrying a client message id is recorded and streamed as a canonical `user_message` with that
|
||||
same id. This includes daemon-handled commands that do not allocate a foreground turn; their submitted
|
||||
row is recorded before handler output. The app tracks submission transactions only for hosts with this
|
||||
capability. Older hosts keep the shipped untracked optimistic-row behavior and roll that row back on RPC
|
||||
@@ -238,25 +238,11 @@ foreground control ownership remains a separate daemon concern. Cancellation req
|
||||
with that record rather than in a React component, so an old request cannot clear a newer one. Submissions
|
||||
remain a separate pre-turn registry and retire on canonical acknowledgement.
|
||||
|
||||
Canonical turns and visible responses are different boundaries. Agent-originated prompts and lifecycle
|
||||
notifications project into tool rows, so they do not create a human-message boundary. Legacy system
|
||||
prompts, including schedule injections, remain hidden. One visible response can span several canonical
|
||||
turns; layout and copy group that response together while lifecycle, timing, tool sequences, and exact
|
||||
Canonical turns and visible responses are different boundaries. System-injected prompts are absent from
|
||||
the Paseo timeline, so one visible response can span several canonical turns without a user message
|
||||
between them. Layout and copy group that response together; lifecycle, timing, tool sequences, and exact
|
||||
fork positions retain the canonical `turnId` boundaries.
|
||||
|
||||
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
|
||||
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
|
||||
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
|
||||
removed senders must remain understandable without a live directory lookup.
|
||||
|
||||
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
|
||||
presentation (`protocol/agent-message-display`) owns its heading and expanded details. The daemon
|
||||
must not construct UI labels or prepend sender labels to the semantic message body. The existing
|
||||
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
|
||||
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
|
||||
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
|
||||
|
||||
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
|
||||
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
|
||||
does not combine anonymous lifecycle events, timestamps, timeline rows, and resume coverage to infer a
|
||||
@@ -264,7 +250,7 @@ second running state. Disconnect preserves the last replicated turn until cache
|
||||
advances it; replica removal remains the destructive close boundary. Elapsed time comes only from turn
|
||||
liveness, never from submission records or whichever timeline rows happen to be mounted.
|
||||
|
||||
For human prompts, the daemon records one canonical submitted user row at acceptance. Its wire `messageId` is the
|
||||
The daemon records one canonical submitted user row at acceptance. Its wire `messageId` is the
|
||||
submission's `clientMessageId`, so the row is born with its final identity and remains immutable on
|
||||
the wire. A correlated provider echo records the provider's native identity internally without
|
||||
dispatching another timeline event. Rewind resolves the wire identity to that provider identity at
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-CK96G7MWsmd/VDvkuaFJ23U04EGNmeiXdTYbmR8RDDQ=
|
||||
sha256-AKY6OMZgHeyn/To/2zsmtfb5C4fKniUp8gvpEYaR7/o=
|
||||
|
||||
@@ -284,6 +284,7 @@ async function expectRejectedSubmissionRestored(
|
||||
await expectComposerDraft(page, input.prompt);
|
||||
await expectComposerEditable(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: input.prompt })).toHaveCount(0);
|
||||
if (input.preservesActiveTurn) {
|
||||
await expect(page.getByTestId("turn-working-indicator")).toBeVisible();
|
||||
return;
|
||||
@@ -294,21 +295,13 @@ async function expectRejectedSubmissionRestored(
|
||||
|
||||
async function retryRestoredSubmission(page: Page, prompt: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Message agent..." }).first().press("Enter");
|
||||
const attempts = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(attempts).toHaveCount(2);
|
||||
const userMessage = attempts.last();
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toHaveCount(1);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false", { timeout: 30_000 });
|
||||
await expect(userMessage.getByRole("button", { name: "Open image attachment" })).toBeVisible();
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function expectRejectedPromptBeforeError(page: Page, prompt: string, errorMessage: string) {
|
||||
const messages = page.getByTestId("user-message").or(page.getByTestId("assistant-message"));
|
||||
await expect(messages).toHaveCount(2);
|
||||
await expect(messages.nth(0)).toContainText(prompt);
|
||||
await expect(messages.nth(1)).toContainText(`[System Error] ${errorMessage}`);
|
||||
}
|
||||
|
||||
async function configureSteerInSettings(page: Page): Promise<void> {
|
||||
const modifier = process.platform === "darwin" ? "Meta" : "Control";
|
||||
await page.keyboard.press(`${modifier}+Comma`);
|
||||
@@ -1180,14 +1173,13 @@ test.describe("Agent message submission", () => {
|
||||
await toasts.expectNeverShown("agent-updating-toast");
|
||||
});
|
||||
|
||||
test("retains a rejected submission before its error and accepts its retry", async ({
|
||||
test("restores a rejected submission and accepts its retry", async ({
|
||||
page,
|
||||
rejectionScenario,
|
||||
}) => {
|
||||
const prompt = "Restore this rejected submission.";
|
||||
await submitMessageThatWillBeRejected(page, prompt);
|
||||
await expectRejectedSubmissionRestored(page, { prompt, ...rejectionScenario });
|
||||
await expectRejectedPromptBeforeError(page, prompt, rejectionScenario.errorMessage);
|
||||
await retryRestoredSubmission(page, prompt);
|
||||
});
|
||||
|
||||
@@ -1217,7 +1209,6 @@ test.describe("Agent message submission", () => {
|
||||
errorMessage: "Requested mock steer transport failure",
|
||||
preservesActiveTurn: true,
|
||||
});
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
|
||||
|
||||
expect(gate.getClientRequestCount("send_agent_message_request")).toBe(sendsBefore + 1);
|
||||
expect(gate.getClientRequestCount("cancel_agent_request")).toBe(cancelsBefore);
|
||||
|
||||
@@ -128,46 +128,3 @@ for (const scenario of [
|
||||
await creation.expectAgentCount(1);
|
||||
});
|
||||
}
|
||||
|
||||
for (const entry of [
|
||||
{
|
||||
name: "agent draft",
|
||||
open: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
|
||||
creation.openAgentDraft(),
|
||||
button: "Send message",
|
||||
settled: async (_creation: Awaited<ReturnType<typeof createCreationScenario>>) => {},
|
||||
},
|
||||
{
|
||||
name: "new workspace",
|
||||
open: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
|
||||
creation.openWorkspaceForm("local"),
|
||||
button: "Create",
|
||||
settled: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
|
||||
creation.expectOneCreatedWorkspace(),
|
||||
},
|
||||
]) {
|
||||
test(`${entry.name} becomes an agent tab when the first prompt is rejected`, async ({
|
||||
creation,
|
||||
promptRejection,
|
||||
page,
|
||||
}, testInfo) => {
|
||||
void promptRejection;
|
||||
const prompt =
|
||||
"Continue the attached conversation.\n" + "Earlier conversation context.\n".repeat(100);
|
||||
await entry.open(creation);
|
||||
await creation.submitPrompt(prompt, entry.button);
|
||||
await entry.settled(creation);
|
||||
await creation.expectCreatedAgentError();
|
||||
await creation.expectPromptBeforeError(prompt);
|
||||
await page.screenshot({ path: testInfo.outputPath("created-agent-prompt-error.png") });
|
||||
await creation.reloadAgent();
|
||||
await creation.expectPromptBeforeError(prompt);
|
||||
await creation.submitPrompt("emit 1 coalesced agent stream updates for a corrected prompt.");
|
||||
await creation.expectPromptVisible(
|
||||
"emit 1 coalesced agent stream updates for a corrected prompt.",
|
||||
);
|
||||
await creation.expectAssistantReply();
|
||||
await creation.expectAgentCount(1);
|
||||
await expect(page.getByText("agent_request_key_conflict", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
function workspaceRowTestId(workspaceId: string): string {
|
||||
@@ -74,75 +73,3 @@ test.describe("Sidebar workspace rename", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function toggleBackgroundWorkspaces(page: Page): Promise<void> {
|
||||
await page.getByLabel("Display preferences", { exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Show background", exact: true }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
async function expectWorkspaceInSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
// Rows have no single accessible role: their nested title and actions share this container.
|
||||
await expect(page.getByTestId(workspaceRowTestId(workspaceId))).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function expectWorkspaceHidden(page: Page, workspaceId: string): Promise<void> {
|
||||
await expect(page.getByTestId(workspaceRowTestId(workspaceId))).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function reconnectApp(page: Page): Promise<void> {
|
||||
await page.reload();
|
||||
await expect(page.getByLabel("Display preferences", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectWorkerOpen(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(page.getByText("Background reviewer", { exact: true }).first()).toBeVisible();
|
||||
await expect(page.getByText("Background review prompt", { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
test("background workspace stays directly accessible across sidebar toggles and reconnect", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const workspace = await seedWorkspace({
|
||||
repoPrefix: "sidebar-background-",
|
||||
title: "Background review",
|
||||
background: true,
|
||||
});
|
||||
try {
|
||||
const worker = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title: "Background reviewer",
|
||||
initialPrompt: "Background review prompt",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
await test.step("Default sidebar hides background work", async () => {
|
||||
await gotoAppShell(page);
|
||||
await expectWorkspaceHidden(page, workspace.workspaceId);
|
||||
});
|
||||
await test.step("Show background exposes the fully replicated workspace", async () => {
|
||||
await toggleBackgroundWorkspaces(page);
|
||||
await expectWorkspaceInSidebar(page, workspace.workspaceId);
|
||||
await reconnectApp(page);
|
||||
await expectWorkspaceInSidebar(page, workspace.workspaceId);
|
||||
});
|
||||
await test.step("Direct agent navigation survives hiding and reconnect", async () => {
|
||||
await toggleBackgroundWorkspaces(page);
|
||||
await expectWorkspaceHidden(page, workspace.workspaceId);
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: worker.id });
|
||||
await expectWorkerOpen(page);
|
||||
await expectWorkspaceHidden(page, workspace.workspaceId);
|
||||
await reconnectApp(page);
|
||||
await expectWorkerOpen(page);
|
||||
await expectWorkspaceHidden(page, workspace.workspaceId);
|
||||
await page.screenshot({ path: testInfo.outputPath("background-direct-open.png") });
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# Native iOS text geometry regression
|
||||
|
||||
Run on the Namespace Mac with a fresh simulator development build. Use the PID
|
||||
returned by `xcrun simctl launch <your-task-simulator-UDID> sh.paseo.debug`.
|
||||
Attach only to your task's app, while no device replay is running:
|
||||
|
||||
```sh
|
||||
PASEO_NATIVE_TEXT_REFLOW_PID=12345 \
|
||||
PASEO_NATIVE_TEXT_REFLOW_LOG=/Volumes/devbox/workspace/native-text-reflow.log \
|
||||
bash packages/app/e2e/mobile/native-text-reflow/ios.sh
|
||||
```
|
||||
|
||||
The probe constructs the installed `RNUITextView`, fills its real UIKit text view,
|
||||
and resizes its content container from 500 to 240 and back to 500 points. It
|
||||
asserts the inner frame follows both widths and the same selection survives.
|
||||
It then recycles the view the way Fabric's pool does and remounts it 30 points
|
||||
wider and at the same size; the inner frame must still match the container.
|
||||
A zeroed frame on recycle comes back 30 or 0 points wide. This assertion checks
|
||||
the intermediate recycled geometry; it does not reproduce visible clipping in a
|
||||
mounted Fabric paragraph or exercise the subsequent `drawRect` call.
|
||||
It uses public UIView/UITextView operations, without mocking React Native.
|
||||
LLDB detaches after the probe. An assertion failure or evaluation error fails the
|
||||
shell command; the log distinguishes them.
|
||||
|
||||
This covers native container resizing and selection retention. It does not cover
|
||||
Fabric event delivery, chat row height, reader anchoring, or the on-screen copy
|
||||
menu. Those require the real chat journey: read an older multiline response,
|
||||
open/close Explorer, resize/rotate, inspect complete paragraphs and bullets,
|
||||
retain expanded/collapsed details, and check a stationary reader's position.
|
||||
Accessibility exposes full text even when glyphs are clipped, so a text wait
|
||||
alone does not verify that journey.
|
||||
@@ -1,76 +0,0 @@
|
||||
import lldb
|
||||
|
||||
|
||||
def __lldb_init_module(debugger, _internal_dict):
|
||||
process = debugger.GetSelectedTarget().GetProcess()
|
||||
main_threads = [thread for thread in process if thread.GetQueueName() == "com.apple.main-thread"]
|
||||
if len(main_threads) != 1 or not process.SetSelectedThread(main_threads[0]):
|
||||
raise RuntimeError("Could not select the UIKit main thread")
|
||||
debugger.HandleCommand("expression -l objc++ -- @import UIKit")
|
||||
frame = process.GetSelectedThread().GetSelectedFrame()
|
||||
options = lldb.SBExpressionOptions()
|
||||
options.SetLanguage(lldb.eLanguageTypeObjC_plus_plus)
|
||||
is_main_thread = frame.EvaluateExpression("(BOOL)[NSThread isMainThread]", options)
|
||||
if is_main_thread.GetError().Fail() or is_main_thread.GetValueAsUnsigned() != 1:
|
||||
raise RuntimeError("Refusing to run UIKit probe outside the main thread")
|
||||
result = frame.EvaluateExpression(
|
||||
r'''({
|
||||
UIView *host = (UIView *)[[NSClassFromString(@"RNUITextView") alloc] init];
|
||||
auto hostFrame = host.frame;
|
||||
hostFrame.size.width = 500;
|
||||
hostFrame.size.height = 200;
|
||||
host.frame = hostFrame;
|
||||
UIView *container = (UIView *)[host performSelector:@selector(contentView)];
|
||||
container.frame = host.bounds;
|
||||
UITextView *text = nil;
|
||||
for (UIView *child in host.subviews) {
|
||||
if ([child isKindOfClass:UITextView.class]) text = (UITextView *)child;
|
||||
for (UIView *nested in child.subviews) {
|
||||
if ([nested isKindOfClass:UITextView.class]) text = (UITextView *)nested;
|
||||
}
|
||||
}
|
||||
text.frame = container.bounds;
|
||||
text.font = [UIFont systemFontOfSize:16];
|
||||
text.text = @"A realistic multiline paragraph must reflow when Explorer narrows the available chat width, then fill the restored width without replacing the text view or discarding a selection.";
|
||||
auto range = text.selectedRange;
|
||||
range.location = 12;
|
||||
range.length = 9;
|
||||
text.selectedRange = range;
|
||||
auto frame = container.frame;
|
||||
frame.size.width = 240;
|
||||
container.frame = frame;
|
||||
[container layoutIfNeeded];
|
||||
CGFloat narrow = text.frame.size.width;
|
||||
auto selection = text.selectedRange;
|
||||
frame.size.width = 500;
|
||||
container.frame = frame;
|
||||
[container layoutIfNeeded];
|
||||
CGFloat wide = text.frame.size.width;
|
||||
auto keptSelection = text.selectedRange;
|
||||
// Fabric recycles the view: the container keeps its size in the pool,
|
||||
// and the next paragraph mounts it 30 points wider (a list-item paragraph
|
||||
// reused by a full-width one) or at the same size.
|
||||
[host performSelector:@selector(prepareForRecycle)];
|
||||
frame.size.width = 530;
|
||||
container.frame = frame;
|
||||
[container layoutIfNeeded];
|
||||
CGFloat reusedWider = text.frame.size.width;
|
||||
[host performSelector:@selector(prepareForRecycle)];
|
||||
container.frame = frame;
|
||||
[container layoutIfNeeded];
|
||||
CGFloat reusedSame = text.frame.size.width;
|
||||
BOOL ok = text != nil && narrow == 240 && wide == 500 &&
|
||||
reusedWider == 530 && reusedSame == 530 &&
|
||||
selection.location == keptSelection.location &&
|
||||
selection.length == keptSelection.length &&
|
||||
selection.location == 12 && selection.length == 9;
|
||||
[NSString stringWithFormat:@"NATIVE_REFLOW_%@ narrow=%.0f wide=%.0f recycled=%.0f,%.0f selection=%lu:%lu",
|
||||
ok ? @"PASS" : @"FAIL", narrow, wide, reusedWider, reusedSame,
|
||||
(unsigned long)keptSelection.location,
|
||||
(unsigned long)keptSelection.length];
|
||||
})''',
|
||||
options,
|
||||
)
|
||||
if result.GetError().Fail():
|
||||
raise RuntimeError(result.GetError().GetCString())
|
||||
print(result.GetObjectDescription())
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
: "${PASEO_NATIVE_TEXT_REFLOW_PID:?Set the PID of your task-owned Paseo iOS simulator app}"
|
||||
: "${PASEO_NATIVE_TEXT_REFLOW_LOG:?Set the test output log path}"
|
||||
|
||||
if [[ "$(ps -p "$PASEO_NATIVE_TEXT_REFLOW_PID" -o comm=)" != *PaseoDebug.app/PaseoDebug ]]; then
|
||||
echo "Expected a running PaseoDebug simulator app" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
probe_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
xcrun lldb --batch -p "$PASEO_NATIVE_TEXT_REFLOW_PID" \
|
||||
-o "command script import $probe_dir/ios.py" \
|
||||
-o "process detach" -o quit > "$PASEO_NATIVE_TEXT_REFLOW_LOG" 2>&1
|
||||
|
||||
grep '^NATIVE_REFLOW_' "$PASEO_NATIVE_TEXT_REFLOW_LOG"
|
||||
grep -q '^NATIVE_REFLOW_PASS narrow=240 wide=500 recycled=530,530 selection=12:9$' "$PASEO_NATIVE_TEXT_REFLOW_LOG"
|
||||
@@ -13,7 +13,6 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
|
||||
|
||||
export const test = base.extend<{
|
||||
startup: { release(): Promise<void>; fail(): Promise<void> };
|
||||
promptRejection: void;
|
||||
creation: Awaited<ReturnType<typeof createCreationScenario>>;
|
||||
promptRetry: ReturnType<typeof createPromptRetryScenario>;
|
||||
agentRetries: Awaited<ReturnType<typeof retryNextAgentCreation>>;
|
||||
@@ -66,37 +65,6 @@ export default function contribute(server) {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
promptRejection: async ({ page }, provide) => {
|
||||
void page;
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
const plugin = await copyPluginExample("lifecycle-logger");
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(plugin.directory, "index.server.ts"),
|
||||
`
|
||||
export default function contribute(server) {
|
||||
return server.before("agent.create", ({ request }) => ({
|
||||
...request,
|
||||
config: {
|
||||
...request.config,
|
||||
model: "e2e-fast-stream",
|
||||
featureValues: { ...request.config.featureValues, mockPromptRejections: 1 },
|
||||
},
|
||||
}));
|
||||
}
|
||||
`,
|
||||
);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(plugin.directory);
|
||||
await provide();
|
||||
} finally {
|
||||
await client.removePlugin("lifecycle-logger");
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||
await plugin.cleanup();
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
creation: async ({ page }, provide) => {
|
||||
const creation = await createCreationScenario(page);
|
||||
try {
|
||||
|
||||
@@ -98,6 +98,7 @@ async function createCodexRestoreJourney(page: Page, client: SeedDaemonClient, i
|
||||
settings: { modeId: "full-access", thinkingOptionId: "low" },
|
||||
title: "Codex worktree restore reproduction",
|
||||
initialPrompt: `Reply with exactly ${REPLY} and nothing else. Do not use tools.`,
|
||||
background: true,
|
||||
}),
|
||||
);
|
||||
agentId = agent.agentId;
|
||||
|
||||
@@ -182,47 +182,6 @@ export async function createCreationScenario(page: Page) {
|
||||
await this.expectWorkspaceReadyBeforeAgentCompletion();
|
||||
expect((await project.client.fetchAgents()).entries).toHaveLength(0);
|
||||
},
|
||||
async expectCreatedAgentError() {
|
||||
await requests.settled();
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ hasText: "[System Error] Requested mock prompt rejection", visible: true }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page
|
||||
.locator('[data-testid^="workspace-tab-agent_"][aria-selected="true"]')
|
||||
.filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeEditable();
|
||||
await expect(page.getByTestId("turn-working-indicator")).toHaveCount(0);
|
||||
},
|
||||
async expectPromptBeforeError(prompt: string) {
|
||||
const messages = page
|
||||
.getByTestId("user-message")
|
||||
.or(page.getByTestId("assistant-message"))
|
||||
.filter({ visible: true });
|
||||
await expect(messages).toHaveCount(2);
|
||||
await expect(messages.nth(0)).toContainText(prompt);
|
||||
await expect(messages.nth(1)).toContainText("[System Error]");
|
||||
await expect(messages.nth(1)).toBeInViewport();
|
||||
},
|
||||
async reloadAgent() {
|
||||
await page.reload();
|
||||
await expect(page.getByText("Updating messages", { exact: true })).toHaveCount(0);
|
||||
await this.expectCreatedAgentError();
|
||||
},
|
||||
async expectAssistantReply() {
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ visible: true, hasNotText: "[System Error]" })
|
||||
.first(),
|
||||
).toBeVisible();
|
||||
},
|
||||
async expectStartupFailure() {
|
||||
await expect(page.getByText(/Creation startup failed for test/).first()).toBeVisible();
|
||||
},
|
||||
|
||||
@@ -66,7 +66,6 @@ export interface SeedDaemonClient {
|
||||
worktreeSlug?: string;
|
||||
};
|
||||
title?: string;
|
||||
background?: boolean;
|
||||
}): Promise<{
|
||||
workspace: SeedWorkspaceDescriptor | null;
|
||||
error: string | null;
|
||||
@@ -224,7 +223,6 @@ export interface SeededWorkspace {
|
||||
export async function seedWorkspace(options: {
|
||||
repoPrefix: string;
|
||||
title?: string;
|
||||
background?: boolean;
|
||||
port?: number;
|
||||
/** Repo fixture options; only applies to git projects (the default). */
|
||||
repo?: Parameters<typeof createTempGitRepo>[1];
|
||||
@@ -240,7 +238,6 @@ export async function seedWorkspace(options: {
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "directory", path: project.path },
|
||||
title: options.title,
|
||||
background: options.background,
|
||||
});
|
||||
if (!created.workspace) {
|
||||
throw new Error(created.error ?? `Failed to create workspace ${project.path}`);
|
||||
|
||||
@@ -792,7 +792,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
detail={data.detail}
|
||||
cwd={context.cwd}
|
||||
metadata={data.metadata}
|
||||
agentMessage={data.agentMessage}
|
||||
isLastInSequence={isLastInSequence}
|
||||
onOpenFilePath={handleToolCallOpenFile}
|
||||
maxDetailHeight={maxDetailHeight}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import { ASSISTANT_IMAGE_DEFAULT_ASPECT_RATIO } from "@/utils/assistant-image-metadata";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
@@ -3023,7 +3022,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa
|
||||
}
|
||||
|
||||
interface ToolCallProps {
|
||||
agentMessage?: AgentMessage;
|
||||
toolName: string;
|
||||
args?: unknown;
|
||||
result?: unknown;
|
||||
@@ -3043,7 +3041,6 @@ interface ToolCallProps {
|
||||
}
|
||||
|
||||
export const ToolCall = memo(function ToolCall({
|
||||
agentMessage,
|
||||
toolName,
|
||||
args,
|
||||
result,
|
||||
@@ -3084,7 +3081,6 @@ export const ToolCall = memo(function ToolCall({
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
buildToolCallPresentation({
|
||||
agentMessage,
|
||||
toolName,
|
||||
status,
|
||||
error: error ?? null,
|
||||
@@ -3093,7 +3089,7 @@ export const ToolCall = memo(function ToolCall({
|
||||
cwd,
|
||||
resolveIcon: resolveToolCallIcon,
|
||||
}),
|
||||
[toolName, status, error, effectiveDetail, metadata, cwd, agentMessage],
|
||||
[toolName, status, error, effectiveDetail, metadata, cwd],
|
||||
);
|
||||
const handleOpenFile = useMemo(() => {
|
||||
const openFilePath = presentation.openFilePath;
|
||||
@@ -3109,7 +3105,7 @@ export const ToolCall = memo(function ToolCall({
|
||||
toolName,
|
||||
displayName: presentation.displayName,
|
||||
summary: presentation.summary,
|
||||
detail: presentation.detail,
|
||||
detail: effectiveDetail,
|
||||
errorText: presentation.errorText,
|
||||
icon: presentation.icon,
|
||||
showLoadingSkeleton: presentation.isLoadingDetails,
|
||||
@@ -3121,12 +3117,12 @@ export const ToolCall = memo(function ToolCall({
|
||||
shouldRenderInline,
|
||||
openToolCall,
|
||||
toolName,
|
||||
presentation.detail,
|
||||
presentation.displayName,
|
||||
presentation.summary,
|
||||
presentation.errorText,
|
||||
presentation.icon,
|
||||
presentation.isLoadingDetails,
|
||||
effectiveDetail,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -3162,7 +3158,7 @@ export const ToolCall = memo(function ToolCall({
|
||||
return (
|
||||
<ToolCallDetailsContent
|
||||
toolName={toolName}
|
||||
detail={presentation.detail}
|
||||
detail={effectiveDetail}
|
||||
errorText={presentation.errorText}
|
||||
maxHeight={maxDetailHeight}
|
||||
showLoadingSkeleton={presentation.isLoadingDetails}
|
||||
@@ -3171,7 +3167,7 @@ export const ToolCall = memo(function ToolCall({
|
||||
}, [
|
||||
shouldRenderInline,
|
||||
toolName,
|
||||
presentation.detail,
|
||||
effectiveDetail,
|
||||
presentation.errorText,
|
||||
presentation.isLoadingDetails,
|
||||
maxDetailHeight,
|
||||
|
||||
@@ -63,7 +63,11 @@ import {
|
||||
type SidebarWorkspacePlacement,
|
||||
} from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { useSidebarOrderStore } from "@/stores/sidebar-order-store";
|
||||
import { useSidebarViewStore, type SidebarGroupMode } from "@/stores/sidebar-view-store";
|
||||
import {
|
||||
hasActiveSidebarLabelFilter,
|
||||
useSidebarViewStore,
|
||||
type SidebarGroupMode,
|
||||
} from "@/stores/sidebar-view-store";
|
||||
import { useShowShortcutBadges } from "@/hooks/use-show-shortcut-badges";
|
||||
import {
|
||||
ContextMenu,
|
||||
@@ -1915,6 +1919,9 @@ export function SidebarWorkspaceList({
|
||||
const onToggleWorkspacePin = useSidebarWorkspacePinController();
|
||||
const getPinnedWorkspaceOrder = useSidebarOrderStore((state) => state.getPinnedWorkspaceOrder);
|
||||
const setPinnedWorkspaceOrder = useSidebarOrderStore((state) => state.setPinnedWorkspaceOrder);
|
||||
const hasActiveLabelFilter = useSidebarViewStore((state) =>
|
||||
hasActiveSidebarLabelFilter(state.labelFilter),
|
||||
);
|
||||
const handlePinnedWorkspaceReorder = useCallback(
|
||||
(reorderedWorkspaces: SidebarWorkspacePlacement[]) => {
|
||||
const reorderedWorkspaceKeys = reorderedWorkspaces.map((workspace) => workspace.workspaceKey);
|
||||
@@ -1946,10 +1953,11 @@ export function SidebarWorkspaceList({
|
||||
// this whole subtree, which unmounted the header — and the header is where the display menu's
|
||||
// trigger lives, so filtering the last row away closed the menu you were filtering from.
|
||||
//
|
||||
// Background visibility can also hide the last project. Keep the header mounted
|
||||
// whenever a local filter empties an otherwise populated directory, so users can
|
||||
// reach the display menu to reveal their work again.
|
||||
const sidebarFilterEmpty = hasProjectsBeforeFilter && projects.length === 0;
|
||||
// Only the label filter can get here. The project filter resolves against the projects it can
|
||||
// see and falls back to "all projects" when nothing matches, so it either keeps at least one
|
||||
// project or is not applied at all — it can narrow this list but never empty it.
|
||||
const sidebarFilterEmpty =
|
||||
hasActiveLabelFilter && hasProjectsBeforeFilter && projects.length === 0;
|
||||
|
||||
// Project mode is the one that keeps its project headers; every other grouping mode is a flat
|
||||
// list of grouped rows, so a new mode lands in the grouped branch rather than silently in this
|
||||
|
||||
@@ -301,13 +301,6 @@ export function SidebarDisplayPreferencesMenu(): ReactElement {
|
||||
sheetTitle={t("sidebar.display.heading")}
|
||||
testID="sidebar-display-preferences-content"
|
||||
>
|
||||
<MenuItem
|
||||
selected={preferences.showBackground}
|
||||
closeOnSelect={false}
|
||||
onSelect={preferences.toggleBackground}
|
||||
>
|
||||
{t("sidebar.display.showBackground")}
|
||||
</MenuItem>
|
||||
<MenuSubTrigger
|
||||
id="grouping"
|
||||
value={t(GROUPING_LABEL_KEYS[preferences.grouping])}
|
||||
|
||||
@@ -16,8 +16,6 @@ import { DEFAULT_SIDEBAR_ROW_ITEMS, type SidebarRowItem, type SidebarRowItems }
|
||||
export type SidebarTrailingChoice = Exclude<SidebarWorkspaceTrailing, "none">;
|
||||
|
||||
export interface SidebarDisplayPreferences {
|
||||
showBackground: boolean;
|
||||
toggleBackground: () => void;
|
||||
grouping: SidebarGroupMode;
|
||||
setGrouping: (mode: SidebarGroupMode) => void;
|
||||
titleSource: WorkspaceTitleSource;
|
||||
@@ -50,8 +48,6 @@ export interface SidebarDisplayPreferences {
|
||||
* this for a value and set it; where it lands is this module's problem.
|
||||
*/
|
||||
export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
|
||||
const showBackground = useSidebarViewStore((state) => state.showBackground);
|
||||
const toggleBackground = useSidebarViewStore((state) => state.toggleBackground);
|
||||
const grouping = useSidebarViewStore((state) => state.groupMode);
|
||||
const setGrouping = useSidebarViewStore((state) => state.setGroupMode);
|
||||
const hostFilters = useSidebarViewStore((state) => state.hostFilters);
|
||||
@@ -108,8 +104,6 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
showBackground,
|
||||
toggleBackground,
|
||||
grouping,
|
||||
setGrouping,
|
||||
titleSource: workspaceTitleSource,
|
||||
@@ -131,8 +125,6 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
|
||||
clearLabelFilter,
|
||||
}),
|
||||
[
|
||||
showBackground,
|
||||
toggleBackground,
|
||||
grouping,
|
||||
setGrouping,
|
||||
workspaceTitleSource,
|
||||
|
||||
@@ -57,7 +57,6 @@ export function SidebarModelProvider({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const list = useSidebarWorkspacesList({ enabled: active });
|
||||
const showBackground = useSidebarViewStore((state) => state.showBackground);
|
||||
const groupMode = useSidebarViewStore((state) => state.groupMode);
|
||||
const labelFilter = useSidebarViewStore((state) => state.labelFilter);
|
||||
const projectFilters = useSidebarViewStore((state) => state.projectFilters);
|
||||
@@ -108,12 +107,9 @@ export function SidebarModelProvider({
|
||||
workspaces: [...workspaceEntriesByKey.values()],
|
||||
projectFilters: resolvedProjectFilters,
|
||||
});
|
||||
const filtered = filterWorkspacesByLabels({
|
||||
workspaces: byProject.filter((workspace) => showBackground || !workspace.background),
|
||||
...labelFilter,
|
||||
});
|
||||
const filtered = filterWorkspacesByLabels({ workspaces: byProject, ...labelFilter });
|
||||
return new Map(filtered.map((workspace) => [workspace.workspaceKey, workspace]));
|
||||
}, [showBackground, labelFilter, resolvedProjectFilters, workspaceEntriesByKey]);
|
||||
}, [labelFilter, resolvedProjectFilters, workspaceEntriesByKey]);
|
||||
const visibleWorkspaceKeys = useMemo(
|
||||
() => new Set(filteredWorkspaceEntriesByKey.keys()),
|
||||
[filteredWorkspaceEntriesByKey],
|
||||
@@ -128,19 +124,16 @@ export function SidebarModelProvider({
|
||||
const included = new Set(resolvedProjectFilters);
|
||||
projects = projects.filter((project) => included.has(project.viewKey));
|
||||
}
|
||||
if (hasActiveLabelFilter || !showBackground) {
|
||||
if (hasActiveLabelFilter) {
|
||||
projects = projects.flatMap((project) => {
|
||||
const workspaces = project.workspaces.filter((workspace) =>
|
||||
visibleWorkspaceKeys.has(workspace.workspaceKey),
|
||||
);
|
||||
return workspaces.length > 0 || (!hasActiveLabelFilter && project.workspaces.length === 0)
|
||||
? [{ ...project, workspaces }]
|
||||
: [];
|
||||
return workspaces.length > 0 ? [{ ...project, workspaces }] : [];
|
||||
});
|
||||
}
|
||||
return projects;
|
||||
}, [
|
||||
showBackground,
|
||||
hasActiveLabelFilter,
|
||||
hasActiveProjectFilter,
|
||||
resolvedProjectFilters,
|
||||
|
||||
@@ -27,7 +27,6 @@ export interface SidebarWorkspacePlacement {
|
||||
workspaceDirectory?: string;
|
||||
projectKind: WorkspaceStructureProject["projectKind"];
|
||||
workspaceKind: WorkspaceDescriptor["workspaceKind"];
|
||||
background?: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@@ -165,7 +164,6 @@ export function createSidebarWorkspaceEntry(input: {
|
||||
input.workspace.worktreeSlug ?? shortenPath(input.workspace.workspaceDirectory),
|
||||
projectKind: input.workspace.projectKind,
|
||||
workspaceKind: input.workspace.workspaceKind,
|
||||
background: input.workspace.background,
|
||||
name: input.workspace.name,
|
||||
title: input.workspace.title ?? null,
|
||||
pinnedAt: input.workspace.pinnedAt,
|
||||
|
||||
@@ -1147,7 +1147,6 @@ export const ar: TranslationResources = {
|
||||
done: "تم",
|
||||
},
|
||||
display: {
|
||||
showBackground: "إظهار مساحات العمل في الخلفية",
|
||||
trigger: "تفضيلات العرض",
|
||||
heading: "العرض",
|
||||
grouping: {
|
||||
|
||||
@@ -1155,7 +1155,6 @@ export const en = {
|
||||
done: "Done",
|
||||
},
|
||||
display: {
|
||||
showBackground: "Show background",
|
||||
trigger: "Display preferences",
|
||||
heading: "Display",
|
||||
grouping: {
|
||||
|
||||
@@ -1183,7 +1183,6 @@ export const es: TranslationResources = {
|
||||
done: "Terminado",
|
||||
},
|
||||
display: {
|
||||
showBackground: "Mostrar espacios en segundo plano",
|
||||
trigger: "Preferencias de visualización",
|
||||
heading: "Visualización",
|
||||
grouping: {
|
||||
|
||||
@@ -1174,7 +1174,6 @@ export const fr: TranslationResources = {
|
||||
done: "Terminé",
|
||||
},
|
||||
display: {
|
||||
showBackground: "Afficher les espaces en arrière-plan",
|
||||
trigger: "Préférences d’affichage",
|
||||
heading: "Affichage",
|
||||
grouping: {
|
||||
|
||||
@@ -1160,7 +1160,6 @@ export const ja: TranslationResources = {
|
||||
done: "完了",
|
||||
},
|
||||
display: {
|
||||
showBackground: "バックグラウンドを表示",
|
||||
trigger: "表示設定",
|
||||
heading: "表示",
|
||||
grouping: {
|
||||
|
||||
@@ -1154,7 +1154,6 @@ export const ko: TranslationResources = {
|
||||
done: "완료",
|
||||
},
|
||||
display: {
|
||||
showBackground: "백그라운드 표시",
|
||||
trigger: "표시 설정",
|
||||
heading: "표시",
|
||||
grouping: {
|
||||
|
||||
@@ -1173,7 +1173,6 @@ export const ptBR: TranslationResources = {
|
||||
done: "Concluído",
|
||||
},
|
||||
display: {
|
||||
showBackground: "Mostrar espaços em segundo plano",
|
||||
trigger: "Preferências de exibição",
|
||||
heading: "Exibição",
|
||||
grouping: {
|
||||
|
||||
@@ -1164,7 +1164,6 @@ export const ru: TranslationResources = {
|
||||
done: "Готово",
|
||||
},
|
||||
display: {
|
||||
showBackground: "Показать фоновые пространства",
|
||||
trigger: "Настройки отображения",
|
||||
heading: "Отображение",
|
||||
grouping: {
|
||||
|
||||
@@ -1139,7 +1139,6 @@ export const zhCN: TranslationResources = {
|
||||
done: "已完成",
|
||||
},
|
||||
display: {
|
||||
showBackground: "显示后台工作区",
|
||||
trigger: "显示偏好",
|
||||
heading: "显示",
|
||||
grouping: {
|
||||
|
||||
@@ -33,10 +33,6 @@ type ProjectListResult = Awaited<ReturnType<DaemonClient["listProjects"]>>;
|
||||
type AgentFetchResult = Awaited<ReturnType<DaemonClient["fetchAgents"]>>;
|
||||
|
||||
class FakeDirectoryClient {
|
||||
supportsBackgroundWorkspaces(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
supportsWorkspaceLabels = false;
|
||||
listWorkspaceLabelsCalls = 0;
|
||||
fetchAgentsCalls = 0;
|
||||
|
||||
@@ -535,7 +535,6 @@ export class DirectorySync {
|
||||
let subscribe = initialSubscribe;
|
||||
while (true) {
|
||||
const query: Parameters<DaemonClient["observeWorkspaces"]>[0] = {
|
||||
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
|
||||
sort: [{ key: "activity_at", direction: "desc" }],
|
||||
page: cursor ? { limit: PAGE_LIMIT, cursor } : { limit: PAGE_LIMIT },
|
||||
...(supportsDirectorySync
|
||||
@@ -635,7 +634,6 @@ export class DirectorySync {
|
||||
const limit = input.page?.limit ?? PAGE_LIMIT;
|
||||
const query: Omit<FetchAgentsOptions, "subscribe"> = {
|
||||
...(input.filter ? { filter: input.filter } : { scope: "active" as const }),
|
||||
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
|
||||
sort: AGENT_SORT,
|
||||
page: cursor ? { limit, cursor } : { limit },
|
||||
...(!input.filter && cursor === null && this.supportsDirectorySync()
|
||||
|
||||
@@ -52,9 +52,6 @@ it("requests the managed connection credential through desktop main without a we
|
||||
});
|
||||
|
||||
class FakeDaemonClient {
|
||||
supportsBackgroundWorkspaces(): boolean {
|
||||
return false;
|
||||
}
|
||||
private state: ConnectionState = { status: "idle" };
|
||||
private listeners = new Set<(status: ConnectionState) => void>();
|
||||
private error: string | null = null;
|
||||
|
||||
@@ -859,36 +859,3 @@ describe("ReplicaCache", () => {
|
||||
expect(storage.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("retains semantic agent messages across disk-cache reconstruction", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const value = timeline();
|
||||
value.items = [
|
||||
{
|
||||
kind: "tool_call",
|
||||
id: "delivery",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
provider: "codex",
|
||||
callId: "delivery",
|
||||
name: "agent_message",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", text: "Done" },
|
||||
agentMessage: {
|
||||
event: "finished",
|
||||
sender: { id: "remote::worker", title: "Reviewer" },
|
||||
text: "Done",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", value);
|
||||
await writer.flush();
|
||||
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toEqual(value);
|
||||
});
|
||||
|
||||
@@ -421,7 +421,6 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
|
||||
name: data.name,
|
||||
detail: data.detail,
|
||||
...(data.metadata ? { metadata: data.metadata } : {}),
|
||||
...(data.agentMessage ? { agentMessage: data.agentMessage } : {}),
|
||||
};
|
||||
switch (data.status) {
|
||||
case "running":
|
||||
@@ -585,7 +584,6 @@ function deserializeBuiltinTimelineItem(
|
||||
error: tool.error,
|
||||
detail: tool.detail,
|
||||
...(tool.metadata ? { metadata: tool.metadata } : {}),
|
||||
...(tool.agentMessage ? { agentMessage: tool.agentMessage } : {}),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -113,7 +113,6 @@ export interface WorkspaceDescriptor {
|
||||
worktreeSlug?: WorkspaceDescriptorPayload["worktreeSlug"];
|
||||
projectKind: WorkspaceDescriptorPayload["projectKind"];
|
||||
workspaceKind: WorkspaceDescriptorPayload["workspaceKind"];
|
||||
background?: boolean;
|
||||
name: string;
|
||||
title?: string | null;
|
||||
pinnedAt?: string | null;
|
||||
@@ -151,7 +150,6 @@ export function normalizeWorkspaceDescriptor(
|
||||
worktreeSlug: payload.worktreeSlug,
|
||||
projectKind: payload.projectKind,
|
||||
workspaceKind: payload.workspaceKind,
|
||||
background: payload.background ?? false,
|
||||
name: payload.name,
|
||||
title: payload.title ?? null,
|
||||
pinnedAt: payload.pinnedAt ?? null,
|
||||
|
||||
@@ -32,7 +32,6 @@ function createMemoryStorage(entries: Record<string, string | null>): MemoryStor
|
||||
describe("sidebar view store", () => {
|
||||
beforeEach(() => {
|
||||
useSidebarViewStore.setState({
|
||||
showBackground: false,
|
||||
groupMode: "project",
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
@@ -85,7 +84,6 @@ describe("sidebar view store", () => {
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
showBackground: false,
|
||||
groupMode: "status",
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
@@ -100,7 +98,6 @@ describe("sidebar view store", () => {
|
||||
hostFilter: "host-a",
|
||||
}),
|
||||
).toEqual({
|
||||
showBackground: false,
|
||||
groupMode: "status",
|
||||
hostFilters: ["host-a"],
|
||||
projectFilters: [],
|
||||
@@ -115,7 +112,6 @@ describe("sidebar view store", () => {
|
||||
hostFilters: ["host-a", "host-b"],
|
||||
}),
|
||||
).toEqual({
|
||||
showBackground: false,
|
||||
groupMode: "status",
|
||||
hostFilters: ["host-a", "host-b"],
|
||||
projectFilters: [],
|
||||
@@ -226,7 +222,6 @@ describe("sidebar view store", () => {
|
||||
projectFilters: ["project-a", "project-b"],
|
||||
}),
|
||||
).toEqual({
|
||||
showBackground: false,
|
||||
groupMode: "project",
|
||||
hostFilters: ["host-a"],
|
||||
projectFilters: ["project-a", "project-b"],
|
||||
@@ -236,7 +231,6 @@ describe("sidebar view store", () => {
|
||||
|
||||
it("never keeps project filters from state the schema rejects", () => {
|
||||
expect(migrateSidebarViewState({ projectFilters: "project-a" })).toEqual({
|
||||
showBackground: false,
|
||||
groupMode: "project",
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
|
||||
@@ -9,7 +9,7 @@ export type SidebarGroupMode = "project" | "status";
|
||||
|
||||
const SIDEBAR_VIEW_STORAGE_KEY = "sidebar-view";
|
||||
const LEGACY_SIDEBAR_GROUP_MODE_STORAGE_KEY = "sidebar-group-mode";
|
||||
const SIDEBAR_VIEW_STORE_VERSION = 7;
|
||||
const SIDEBAR_VIEW_STORE_VERSION = 6;
|
||||
|
||||
/**
|
||||
* The key standing for "this workspace carries no labels at all".
|
||||
@@ -47,7 +47,6 @@ function toggleFilterEntry(list: readonly string[], key: string): string[] {
|
||||
|
||||
interface SidebarViewStoreState {
|
||||
groupMode: SidebarGroupMode;
|
||||
showBackground: boolean;
|
||||
// Empty means "all hosts". A non-empty list pins the sidebar to those hosts.
|
||||
hostFilters: string[];
|
||||
/**
|
||||
@@ -62,7 +61,6 @@ interface SidebarViewStoreState {
|
||||
*/
|
||||
projectFilters: string[];
|
||||
labelFilter: SidebarLabelFilter;
|
||||
toggleBackground: () => void;
|
||||
setGroupMode: (mode: SidebarGroupMode) => void;
|
||||
toggleHostFilter: (serverId: string) => void;
|
||||
clearHostFilters: () => void;
|
||||
@@ -76,7 +74,6 @@ interface SidebarViewStoreState {
|
||||
|
||||
interface SidebarViewPersistedState {
|
||||
groupMode: SidebarGroupMode;
|
||||
showBackground: boolean;
|
||||
hostFilters: string[];
|
||||
projectFilters: string[];
|
||||
labelFilter: SidebarLabelFilter;
|
||||
@@ -87,7 +84,6 @@ const SidebarLabelFilterSchema = z.object({
|
||||
labels: z.array(z.string()),
|
||||
});
|
||||
const SidebarViewPersistedStateSchema = z.strictObject({
|
||||
showBackground: z.boolean().optional(),
|
||||
groupMode: PersistedSidebarGroupModeSchema.optional(),
|
||||
hostFilters: z.array(z.string()).optional(),
|
||||
hostFilter: z.string().nullable().optional(),
|
||||
@@ -126,7 +122,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
|
||||
const result = SidebarViewPersistedStateSchema.safeParse(persistedState);
|
||||
if (!result.success) {
|
||||
return {
|
||||
showBackground: false,
|
||||
groupMode: "project",
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
@@ -138,7 +133,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
|
||||
const legacyGroupMode = readLegacyGroupMode(state);
|
||||
if (legacyGroupMode) {
|
||||
return {
|
||||
showBackground: false,
|
||||
groupMode: legacyGroupMode,
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
@@ -147,7 +141,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
|
||||
}
|
||||
|
||||
return {
|
||||
showBackground: state.showBackground ?? false,
|
||||
groupMode: state.groupMode === "status" ? "status" : "project",
|
||||
hostFilters: readHostFilters(state),
|
||||
projectFilters: state.projectFilters ?? [],
|
||||
@@ -185,12 +178,10 @@ export function createSidebarViewStorage(
|
||||
export const useSidebarViewStore = create<SidebarViewStoreState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
showBackground: false,
|
||||
groupMode: "project",
|
||||
hostFilters: [],
|
||||
projectFilters: [],
|
||||
labelFilter: emptyLabelFilter(),
|
||||
toggleBackground: () => set((state) => ({ showBackground: !state.showBackground })),
|
||||
setGroupMode: (mode) => set({ groupMode: mode }),
|
||||
toggleHostFilter: (serverId) =>
|
||||
set((state) => ({ hostFilters: toggleFilterEntry(state.hostFilters, serverId) })),
|
||||
@@ -237,7 +228,6 @@ export const useSidebarViewStore = create<SidebarViewStoreState>()(
|
||||
SidebarViewPersistedStateSchema,
|
||||
),
|
||||
partialize: (state) => ({
|
||||
showBackground: state.showBackground ?? false,
|
||||
groupMode: state.groupMode,
|
||||
hostFilters: state.hostFilters,
|
||||
projectFilters: state.projectFilters,
|
||||
|
||||
@@ -92,42 +92,3 @@ describe("tool-call presentation", () => {
|
||||
expect(presentation.icon).toBe(fakeIcons.brain);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["message", "Message from QA messenger"],
|
||||
["finished", "QA messenger finished"],
|
||||
["errored", "QA messenger errored"],
|
||||
["permission-required", "QA messenger needs permission"],
|
||||
["closed", "QA messenger closed"],
|
||||
] as const)("presents %s from structured provenance without a second label", (event, heading) => {
|
||||
const presentation = buildToolCallPresentation({
|
||||
toolName: "internal_name_should_not_be_visible",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", label: "legacy summary", text: "legacy body" },
|
||||
agentMessage: {
|
||||
event,
|
||||
sender: { id: "server::sender", title: "QA messenger" },
|
||||
text: "The delivered message.",
|
||||
},
|
||||
resolveIcon: fakeResolveIcon,
|
||||
});
|
||||
expect(presentation.displayName).toBe(heading);
|
||||
expect(presentation.summary).toBeUndefined();
|
||||
expect(presentation.detail).toEqual({
|
||||
type: "plain_text",
|
||||
icon: "bot",
|
||||
text: "From agent: server::sender\n\nThe delivered message.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses an opaque sender ID when no title is available", () => {
|
||||
const presentation = buildToolCallPresentation({
|
||||
toolName: "agent_message",
|
||||
status: "completed",
|
||||
error: null,
|
||||
agentMessage: { event: "message", sender: { id: "remote::worker" }, text: "Hello" },
|
||||
resolveIcon: fakeResolveIcon,
|
||||
});
|
||||
expect(presentation.displayName).toBe("Message from remote::worker");
|
||||
});
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import { buildAgentMessageDisplay } from "@getpaseo/protocol/agent-message-display";
|
||||
import type { PlanOutcome } from "@/components/plan-card";
|
||||
import type { ComponentType } from "react";
|
||||
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
|
||||
@@ -15,7 +13,6 @@ type ToolCallStatus = "executing" | "running" | "completed" | "failed" | "cancel
|
||||
export type ToolCallPresentationIcon = ComponentType<{ size?: number; color?: string }>;
|
||||
|
||||
interface BuildToolCallPresentationInput {
|
||||
agentMessage?: AgentMessage;
|
||||
toolName: string;
|
||||
status: ToolCallStatus;
|
||||
error: unknown;
|
||||
@@ -26,7 +23,6 @@ interface BuildToolCallPresentationInput {
|
||||
}
|
||||
|
||||
export interface ToolCallPresentation {
|
||||
detail: ToolCallDetail | undefined;
|
||||
displayName: string;
|
||||
summary?: string;
|
||||
errorText?: string;
|
||||
@@ -55,13 +51,9 @@ function displayDetail(detail: ToolCallDetail | undefined): ToolCallDetail {
|
||||
export function buildToolCallPresentation(
|
||||
input: BuildToolCallPresentationInput,
|
||||
): ToolCallPresentation {
|
||||
const detail = input.agentMessage
|
||||
? buildAgentMessageDisplay(input.agentMessage).detail
|
||||
: input.detail;
|
||||
const detailForDisplay = displayDetail(detail);
|
||||
const detailForDisplay = displayDetail(input.detail);
|
||||
const displayModel = buildToolCallDisplayModel({
|
||||
name: input.toolName,
|
||||
agentMessage: input.agentMessage,
|
||||
status: displayStatus(input.status),
|
||||
error: input.error ?? null,
|
||||
detail: detailForDisplay,
|
||||
@@ -69,22 +61,21 @@ export function buildToolCallPresentation(
|
||||
cwd: input.cwd,
|
||||
});
|
||||
const isLoadingDetails = isPendingToolCallDetail({
|
||||
detail,
|
||||
detail: input.detail,
|
||||
status: input.status,
|
||||
error: input.error,
|
||||
});
|
||||
const hasDetails = Boolean(input.error) || hasMeaningfulToolCallDetail(detail);
|
||||
const hasDetails = Boolean(input.error) || hasMeaningfulToolCallDetail(input.detail);
|
||||
|
||||
return {
|
||||
detail,
|
||||
displayName: displayModel.displayName,
|
||||
summary: displayModel.summary,
|
||||
errorText: displayModel.errorText,
|
||||
icon: input.resolveIcon(input.toolName, detail),
|
||||
icon: input.resolveIcon(input.toolName, input.detail),
|
||||
isLoadingDetails,
|
||||
hasDetails,
|
||||
canOpenDetails: hasDetails || isLoadingDetails,
|
||||
openFilePath: extractToolCallFilePath(detail),
|
||||
openFilePath: extractToolCallFilePath(input.detail),
|
||||
isPlan: input.detail?.type === "plan",
|
||||
planOutcome: input.detail?.type === "plan" ? resolvePlanOutcome(input) : undefined,
|
||||
};
|
||||
|
||||
@@ -2305,28 +2305,3 @@ describe("notification timeline items", () => {
|
||||
expect(new Set(state.map((item) => item.id)).size).toBe(state.length);
|
||||
});
|
||||
});
|
||||
|
||||
it("retains agent-message provenance through live delivery and repeated history", () => {
|
||||
const agentMessage = {
|
||||
event: "finished" as const,
|
||||
sender: { id: "remote::worker", title: "Reviewer" },
|
||||
text: "Done",
|
||||
};
|
||||
const event = {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "tool_call",
|
||||
callId: "delivery",
|
||||
name: "agent_message",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", text: "Done" },
|
||||
agentMessage,
|
||||
},
|
||||
} satisfies AgentStreamEventPayload;
|
||||
const live = reduceStreamUpdate([], event, new Date(1));
|
||||
const replay = reduceStreamUpdate(live, event, new Date(2));
|
||||
expect(replay).toHaveLength(1);
|
||||
expect(replay[0]).toMatchObject({ payload: { data: { agentMessage } } });
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type {
|
||||
AgentProvider,
|
||||
AgentTimelineItem,
|
||||
@@ -746,7 +745,6 @@ interface OrchestratorToolCallData {
|
||||
}
|
||||
|
||||
export interface AgentToolCallData {
|
||||
agentMessage?: AgentMessage;
|
||||
provider: AgentProvider;
|
||||
callId: string;
|
||||
name: string;
|
||||
@@ -1448,7 +1446,6 @@ function reduceTimelineToolCall(
|
||||
error: item.error,
|
||||
detail: item.detail,
|
||||
metadata: item.metadata,
|
||||
...(item.agentMessage ? { agentMessage: item.agentMessage } : {}),
|
||||
},
|
||||
timestamp,
|
||||
timelineCursor,
|
||||
|
||||
@@ -46,25 +46,10 @@ describe("canonical CLI surface", () => {
|
||||
expect(help).toContain("--forge <forge>");
|
||||
});
|
||||
|
||||
it("uses --no-wait for execution, --internal for visibility, and reserves detach for ownership", () => {
|
||||
it("uses background for execution and reserves detach for ownership", () => {
|
||||
const run = createCli().commands.find((command) => command.name() === "run");
|
||||
const help = run?.helpInformation();
|
||||
expect(help).toContain("--no-wait");
|
||||
expect(help).not.toContain("--background");
|
||||
expect(help).not.toContain("--background");
|
||||
expect(help).not.toContain("--detach");
|
||||
});
|
||||
|
||||
it("hides internal agents and workspaces from listings unless --internal is passed", () => {
|
||||
const cli = createCli();
|
||||
const ls = cli.commands.find((command) => command.name() === "ls");
|
||||
const workspace = cli.commands.find((command) => command.name() === "workspace");
|
||||
const workspaceLs = workspace?.commands.find((command) => command.name() === "ls");
|
||||
const workspaceCreate = workspace?.commands.find((command) => command.name() === "create");
|
||||
|
||||
expect(ls?.helpInformation()).toContain("--background");
|
||||
expect(workspaceLs?.helpInformation()).toContain("--background");
|
||||
expect(workspaceCreate?.helpInformation()).toContain("--background");
|
||||
expect(run?.helpInformation()).toContain("--background");
|
||||
expect(run?.helpInformation()).not.toContain("--detach");
|
||||
});
|
||||
|
||||
it("offers thinking configuration when running, updating, and scheduling agents", () => {
|
||||
@@ -111,15 +96,3 @@ describe("canonical CLI surface", () => {
|
||||
).toContain("--id <id>");
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves omitted and explicit false workspace background intent", () => {
|
||||
const readOptions = (args: string[]) => {
|
||||
const workspace = createCli().commands.find((command) => command.name() === "workspace")!;
|
||||
const create = workspace.commands.find((command) => command.name() === "create")!;
|
||||
create.parseOptions(args);
|
||||
return create.opts();
|
||||
};
|
||||
expect(readOptions([]).background).toBeUndefined();
|
||||
expect(readOptions(["--background"]).background).toBe(true);
|
||||
expect(readOptions(["--no-background"]).background).toBe(false);
|
||||
});
|
||||
|
||||
@@ -23,21 +23,15 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("asks the daemon for internal agents only with --internal", () => {
|
||||
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
|
||||
filter: { includeBackground: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("fetches global non-archived agents for -g", () => {
|
||||
expect(buildAgentLsFetchOptions({ global: true })).toEqual({});
|
||||
});
|
||||
|
||||
it("includes archived and background agents with -a", () => {
|
||||
it("keeps -a within the active scope", () => {
|
||||
expect(buildAgentLsFetchOptions({ all: true })).toEqual({
|
||||
scope: "active",
|
||||
filter: {
|
||||
includeArchived: true,
|
||||
includeBackground: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -46,7 +40,6 @@ describe("buildAgentLsFetchOptions", () => {
|
||||
expect(buildAgentLsFetchOptions({ all: true, global: true })).toEqual({
|
||||
filter: {
|
||||
includeArchived: true,
|
||||
includeBackground: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,9 +12,8 @@ type FetchAgentsOptions = NonNullable<
|
||||
export function addLsOptions(cmd: Command): Command {
|
||||
return cmd
|
||||
.description("List agents. By default excludes archived agents.")
|
||||
.option("-a, --all", "Include archived and background agents")
|
||||
.option("-a, --all", "Include archived agents")
|
||||
.option("-g, --global", "List agents across all directories")
|
||||
.option("--background", "Include background workspace agents")
|
||||
.option(
|
||||
"--label <key=value>",
|
||||
"Filter by label (can be used multiple times)",
|
||||
@@ -110,8 +109,6 @@ export interface AgentLsOptions extends CommandOptions {
|
||||
all?: boolean;
|
||||
/** -g: List agents across all directories */
|
||||
global?: boolean;
|
||||
/** --background: Include background workspace agents */
|
||||
background?: boolean;
|
||||
/** Filter by specific status */
|
||||
status?: string;
|
||||
/** Filter by specific cwd */
|
||||
@@ -136,7 +133,7 @@ function parseLabelFilters(labels: string[] | undefined): Record<string, string>
|
||||
}
|
||||
|
||||
export function buildAgentLsFetchOptions(
|
||||
options: Pick<AgentLsOptions, "all" | "global" | "background" | "label" | "thinking">,
|
||||
options: Pick<AgentLsOptions, "all" | "global" | "label" | "thinking">,
|
||||
): FetchAgentsOptions {
|
||||
const labelFilters = parseLabelFilters(options.label);
|
||||
const normalizedThinkingOptionId = options.thinking?.trim();
|
||||
@@ -145,9 +142,6 @@ export function buildAgentLsFetchOptions(
|
||||
if (options.all) {
|
||||
daemonFilter.includeArchived = true;
|
||||
}
|
||||
if (options.background || options.all) {
|
||||
daemonFilter.includeBackground = true;
|
||||
}
|
||||
if (Object.keys(labelFilters).length > 0) {
|
||||
daemonFilter.labels = labelFilters;
|
||||
}
|
||||
@@ -156,7 +150,7 @@ export function buildAgentLsFetchOptions(
|
||||
}
|
||||
|
||||
const fetchOptions: FetchAgentsOptions = {};
|
||||
if (!options.global && !options.all) {
|
||||
if (!options.global) {
|
||||
fetchOptions.scope = "active";
|
||||
}
|
||||
if (Object.keys(daemonFilter).length > 0) {
|
||||
@@ -169,7 +163,7 @@ export function buildAgentLsFetchOptions(
|
||||
* Agent ls command semantics:
|
||||
* - `paseo agent ls` → active non-archived agents
|
||||
* - `paseo agent ls -g` → global non-archived agents
|
||||
* - `paseo agent ls -a` → all agents, including archived and background
|
||||
* - `paseo agent ls -a` → active agents, including archived
|
||||
* - `paseo agent ls -ag` → global agents, including archived
|
||||
*/
|
||||
export async function runLsCommand(
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
|
||||
import { resolveCallerAgentId as resolveRunCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import {
|
||||
resolveExistingRunWorkspace,
|
||||
resolveRunCallerAgentId,
|
||||
runRunCommand,
|
||||
waitsForFinish,
|
||||
type AgentRunOptions,
|
||||
} from "./run";
|
||||
|
||||
@@ -22,15 +21,6 @@ function daemonWithAgents(...agentIds: string[]) {
|
||||
};
|
||||
}
|
||||
|
||||
describe("run wait policy", () => {
|
||||
it("waits by default and stops waiting on --no-wait or a legacy alias", () => {
|
||||
expect(waitsForFinish({})).toBe(true);
|
||||
expect(waitsForFinish({ wait: false })).toBe(false);
|
||||
expect(waitsForFinish({ background: true })).toBe(false);
|
||||
expect(waitsForFinish({ detach: true })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed agent caller context", () => {
|
||||
it("uses a trimmed PASEO_AGENT_ID when the target daemon runs that agent", async () => {
|
||||
await expect(
|
||||
@@ -48,20 +38,17 @@ describe("managed agent caller context", () => {
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(["DAEMON_CONNECTION_LOST", "DAEMON_REQUEST_TIMEOUT"] as const)(
|
||||
"preserves %s instead of dropping the caller",
|
||||
async (code) => {
|
||||
const disconnectedDaemon = {
|
||||
async fetchAgent(): Promise<never> {
|
||||
throw new DaemonConnectionError("Caller lookup transport failed", code);
|
||||
},
|
||||
};
|
||||
it("fails instead of dropping the caller when the lookup loses its connection", async () => {
|
||||
const disconnectedDaemon = {
|
||||
async fetchAgent(): Promise<never> {
|
||||
throw new DaemonConnectionError("Connection lost before message could be sent");
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
resolveRunCallerAgentId(disconnectedDaemon, { PASEO_AGENT_ID: "parent-agent" }),
|
||||
).rejects.toBeInstanceOf(DaemonConnectionError);
|
||||
},
|
||||
);
|
||||
await expect(
|
||||
resolveRunCallerAgentId(disconnectedDaemon, { PASEO_AGENT_ID: "parent-agent" }),
|
||||
).rejects.toBeInstanceOf(DaemonConnectionError);
|
||||
});
|
||||
|
||||
it("omits blank caller ids", async () => {
|
||||
await expect(
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
StructuredAgentResponseError,
|
||||
} from "@getpaseo/server/agent-response";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import type {
|
||||
CommandOptions,
|
||||
@@ -27,13 +27,10 @@ export function addRunOptions(cmd: Command): Command {
|
||||
cmd
|
||||
.description("Create and start an agent with a task")
|
||||
.argument("<prompt>", "The task/prompt for the agent")
|
||||
.option("--no-wait", "Return immediately without waiting for completion")
|
||||
// COMPAT(backgroundRunFlag): --background was the documented spelling of
|
||||
// --no-wait. Added in v0.2.0; remove after 2027-04-01.
|
||||
.addOption(new Option("-d, --background", "Legacy alias for --no-wait").hideHelp())
|
||||
.option("-d, --background", "Run in background")
|
||||
// COMPAT(detachRunFlag): --detach used to mean background execution, not
|
||||
// ownership transfer. Added in v0.2.0; remove after 2027-01-17.
|
||||
.addOption(new Option("--detach", "Legacy alias for --no-wait").hideHelp())
|
||||
.addOption(new Option("--detach", "Legacy alias for --background").hideHelp())
|
||||
.option("--title <title>", "Assign a title to the agent")
|
||||
.addOption(new Option("--name <name>", "Hidden alias for --title").hideHelp())
|
||||
.option(
|
||||
@@ -114,7 +111,6 @@ export const agentRunSchema: OutputSchema<AgentRunResult> = {
|
||||
};
|
||||
|
||||
export interface AgentRunOptions extends CommandOptions {
|
||||
wait?: boolean;
|
||||
background?: boolean;
|
||||
detach?: boolean;
|
||||
title?: string;
|
||||
@@ -393,25 +389,19 @@ function validateRunOptions(prompt: string, options: AgentRunOptions, outputSche
|
||||
} satisfies CommandError;
|
||||
}
|
||||
|
||||
if (options.background) {
|
||||
console.error("Warning: --background (-d) is deprecated. Use --no-wait instead.");
|
||||
}
|
||||
|
||||
validateRunWorkspaceOptions(options);
|
||||
|
||||
if (outputSchema && !waitsForFinish(options)) {
|
||||
if (outputSchema && runsInBackground(options)) {
|
||||
throw {
|
||||
code: "INVALID_OPTIONS",
|
||||
message: "--output-schema cannot be used with --no-wait",
|
||||
message: "--output-schema cannot be used with --background",
|
||||
details: "Structured output requires waiting for the agent to finish",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
}
|
||||
|
||||
export function waitsForFinish(
|
||||
options: Pick<AgentRunOptions, "wait" | "background" | "detach">,
|
||||
): boolean {
|
||||
return options.wait !== false && !options.background && !options.detach;
|
||||
function runsInBackground(options: Pick<AgentRunOptions, "background" | "detach">): boolean {
|
||||
return Boolean(options.background || options.detach);
|
||||
}
|
||||
|
||||
function parseWaitTimeoutOption(waitTimeout: string | undefined): number {
|
||||
@@ -567,10 +557,7 @@ async function resolveRunWorkspace(
|
||||
// TODO: thread the run `prompt` as firstAgentContext so workspace-level
|
||||
// title/branch generation picks up the task description (U8/U6 deferred).
|
||||
const source = buildRunWorkspaceSource(options, cwd);
|
||||
const result = await client.createWorkspace({
|
||||
source,
|
||||
...(callerAgentId ? { callerAgentId } : {}),
|
||||
});
|
||||
const result = await client.createWorkspace({ source });
|
||||
|
||||
if (!result.workspace) {
|
||||
throw {
|
||||
@@ -624,7 +611,7 @@ export async function runRunCommand(
|
||||
const env = parseRunEnv(options.env);
|
||||
const requestEnv = Object.keys(env).length > 0 ? env : undefined;
|
||||
|
||||
const callerAgentId = await resolveCallerAgentId(client);
|
||||
const callerAgentId = await resolveRunCallerAgentId(client);
|
||||
const workspace = await resolveRunWorkspace(client, options, cwd, callerAgentId);
|
||||
const workspaceId = workspace.id;
|
||||
const runCwd = workspace.cwd;
|
||||
@@ -720,8 +707,8 @@ export async function runRunCommand(
|
||||
labels: Object.keys(labels).length > 0 ? labels : undefined,
|
||||
});
|
||||
|
||||
// Default run behavior is foreground: wait for completion unless --no-wait is set.
|
||||
if (waitsForFinish(options)) {
|
||||
// Default run behavior is foreground: wait for completion unless background execution is set.
|
||||
if (!runsInBackground(options)) {
|
||||
const state = await client.waitForFinish(agent.id, waitTimeoutMs);
|
||||
await client.close();
|
||||
|
||||
@@ -757,3 +744,29 @@ export async function runRunCommand(
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunCallerLookupClient {
|
||||
fetchAgent(options: { agentId: string }): Promise<{ agent: { id: string } } | null>;
|
||||
}
|
||||
|
||||
// PASEO_AGENT_ID names an agent on the daemon that launched this shell. A run
|
||||
// sent to another daemon (--host or --home) has no caller there, so it runs as
|
||||
// a top-level agent instead of failing on an unknown caller.
|
||||
export async function resolveRunCallerAgentId(
|
||||
client: RunCallerLookupClient,
|
||||
env: { PASEO_AGENT_ID?: string } = process.env,
|
||||
): Promise<string | undefined> {
|
||||
const agentId = env.PASEO_AGENT_ID?.trim();
|
||||
if (!agentId) {
|
||||
return undefined;
|
||||
}
|
||||
const caller = await client.fetchAgent({ agentId }).catch((error: unknown) => {
|
||||
// A daemon without this agent answers with an error. A lost or timed-out
|
||||
// connection is not an answer, so it must not drop the caller.
|
||||
if (error instanceof DaemonConnectionError) {
|
||||
throw error;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return caller?.agent.id === agentId ? agentId : undefined;
|
||||
}
|
||||
|
||||
@@ -192,10 +192,7 @@ export async function runSendCommand(
|
||||
options.image && options.image.length > 0 ? await readImageFiles(options.image) : undefined;
|
||||
|
||||
// Send the message
|
||||
await client.sendAgentMessage(agentIdArg, promptInput, {
|
||||
images,
|
||||
sourceAgentId: process.env.PASEO_AGENT_ID?.trim() || undefined,
|
||||
});
|
||||
await client.sendAgentMessage(agentIdArg, promptInput, { images });
|
||||
|
||||
// If --no-wait, return immediately
|
||||
if (options.wait === false) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
@@ -16,7 +15,6 @@ export interface WorkspaceCreateOptions extends CommandOptions {
|
||||
branch?: string;
|
||||
prNumber?: string;
|
||||
forge?: string;
|
||||
background?: boolean;
|
||||
}
|
||||
|
||||
interface WorktreeSourceBase {
|
||||
@@ -146,12 +144,9 @@ export async function runCreateCommand(
|
||||
});
|
||||
|
||||
try {
|
||||
const callerAgentId = await resolveCallerAgentId(client);
|
||||
const payload = await client.createWorkspace({
|
||||
source: buildWorkspaceSource(options),
|
||||
...(options.title ? { title: options.title } : {}),
|
||||
...(options.background !== undefined ? { background: options.background } : {}),
|
||||
...(callerAgentId ? { callerAgentId } : {}),
|
||||
});
|
||||
if (!payload.workspace) {
|
||||
throw new Error(payload.error ?? "Workspace creation failed");
|
||||
|
||||
@@ -34,17 +34,12 @@ export function createWorkspaceCommand(): Command {
|
||||
.option("--base <ref>", "Base ref (--mode branch-off)")
|
||||
.option("--branch <name>", "Existing branch (--mode checkout-branch)")
|
||||
.option("--pr-number <n>", "Pull request or change request number (--mode checkout-pr)")
|
||||
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)")
|
||||
.option("--background", "Create a background workspace")
|
||||
.option("--no-background", "Create a visible workspace instead of inheriting background"),
|
||||
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)"),
|
||||
).action(withOutput(runCreateCommand));
|
||||
|
||||
addJsonAndDaemonHostOptions(
|
||||
workspace
|
||||
.command("ls")
|
||||
.description("List active workspaces")
|
||||
.option("--background", "Include background workspaces"),
|
||||
).action(withOutput(runLsCommand));
|
||||
addJsonAndDaemonHostOptions(workspace.command("ls").description("List active workspaces")).action(
|
||||
withOutput(runLsCommand),
|
||||
);
|
||||
|
||||
addJsonAndDaemonHostOptions(
|
||||
workspace
|
||||
|
||||
@@ -1,22 +1,10 @@
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import type { CommandError, ListResult } from "../../output/index.js";
|
||||
import {
|
||||
toWorkspaceRow,
|
||||
workspaceSchema,
|
||||
workspaceWithBackgroundSchema,
|
||||
type WorkspaceRow,
|
||||
} from "./shared.js";
|
||||
|
||||
export interface WorkspaceLsOptions {
|
||||
host?: string;
|
||||
daemonTarget: import("../../utils/daemon-target.js").DaemonTarget;
|
||||
/** --background: Include background workspaces */
|
||||
background?: boolean;
|
||||
}
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
export async function runLsCommand(
|
||||
options: WorkspaceLsOptions,
|
||||
options: { host?: string; daemonTarget: import("../../utils/daemon-target.js").DaemonTarget },
|
||||
_command: Command,
|
||||
): Promise<ListResult<WorkspaceRow>> {
|
||||
const host = getDaemonHost({ target: options.daemonTarget });
|
||||
@@ -32,17 +20,12 @@ export async function runLsCommand(
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const payload = await client.fetchWorkspaces({
|
||||
...(options.background ? { filter: { includeBackground: true } } : {}),
|
||||
page: { limit: 200, ...(cursor ? { cursor } : {}) },
|
||||
});
|
||||
workspaces.push(...payload.entries.map(toWorkspaceRow));
|
||||
cursor = payload.pageInfo.nextCursor ?? undefined;
|
||||
} while (cursor);
|
||||
return {
|
||||
type: "list",
|
||||
data: workspaces,
|
||||
schema: options.background ? workspaceWithBackgroundSchema : workspaceSchema,
|
||||
};
|
||||
return { type: "list", data: workspaces, schema: workspaceSchema };
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ export interface WorkspaceRow {
|
||||
name: string;
|
||||
isolation: "local" | "worktree";
|
||||
cwd: string;
|
||||
background: boolean;
|
||||
}
|
||||
|
||||
export const workspaceSchema: OutputSchema<WorkspaceRow> = {
|
||||
@@ -21,15 +20,6 @@ export const workspaceSchema: OutputSchema<WorkspaceRow> = {
|
||||
],
|
||||
};
|
||||
|
||||
/** `--background` listings add a column so hidden workspaces stand out. */
|
||||
export const workspaceWithBackgroundSchema: OutputSchema<WorkspaceRow> = {
|
||||
...workspaceSchema,
|
||||
columns: [
|
||||
...workspaceSchema.columns,
|
||||
{ header: "BACKGROUND", field: (row) => (row.background ? "yes" : ""), width: 8 },
|
||||
],
|
||||
};
|
||||
|
||||
export function toWorkspaceRow(workspace: WorkspaceDescriptorPayload): WorkspaceRow {
|
||||
return {
|
||||
workspaceId: workspace.id,
|
||||
@@ -37,6 +27,5 @@ export function toWorkspaceRow(workspace: WorkspaceDescriptorPayload): Workspace
|
||||
name: workspace.name,
|
||||
isolation: workspace.workspaceKind === "worktree" ? "worktree" : "local",
|
||||
cwd: workspace.workspaceDirectory,
|
||||
background: workspace.background === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
|
||||
|
||||
interface CallerLookupClient {
|
||||
fetchAgent(options: { agentId: string }): Promise<{ agent: { id: string } } | null>;
|
||||
}
|
||||
|
||||
// PASEO_AGENT_ID belongs to the daemon that launched this shell. Commands
|
||||
// targeting another daemon (--host or --home) have no caller on that daemon.
|
||||
export async function resolveCallerAgentId(
|
||||
client: CallerLookupClient,
|
||||
env: { PASEO_AGENT_ID?: string } = process.env,
|
||||
): Promise<string | undefined> {
|
||||
const agentId = env.PASEO_AGENT_ID?.trim();
|
||||
if (!agentId) return undefined;
|
||||
const caller = await client.fetchAgent({ agentId }).catch((error: unknown) => {
|
||||
// A missing agent is a daemon answer; a lost or timed-out connection is not.
|
||||
if (error instanceof DaemonConnectionError) throw error;
|
||||
return null;
|
||||
});
|
||||
return caller?.agent.id === agentId ? agentId : undefined;
|
||||
}
|
||||
@@ -53,12 +53,8 @@ try {
|
||||
console.log("Test 1: run --help shows options");
|
||||
const result = await $`npx paseo run --help`.nothrow();
|
||||
assert.strictEqual(result.exitCode, 0, "run --help should exit 0");
|
||||
assert(result.stdout.includes("--no-wait"), "help should mention --no-wait flag");
|
||||
assert(
|
||||
!result.stdout.includes("--internal"),
|
||||
"help should not mention removed --internal flag",
|
||||
);
|
||||
assert(!result.stdout.includes("--background"), "help should hide legacy --background syntax");
|
||||
assert(result.stdout.includes("-d"), "help should mention -d flag");
|
||||
assert(result.stdout.includes("--background"), "help should mention --background flag");
|
||||
assert(!result.stdout.includes("--detach"), "help should hide legacy --detach syntax");
|
||||
assert(result.stdout.includes("--title"), "help should mention --title option");
|
||||
assert(result.stdout.includes("--provider"), "help should mention --provider option");
|
||||
@@ -182,18 +178,18 @@ try {
|
||||
console.log("✓ run --output-schema flag is accepted\n");
|
||||
}
|
||||
|
||||
// Test 10: run --output-schema cannot be used with --no-wait
|
||||
// Test 10: run --output-schema cannot be used with --background
|
||||
{
|
||||
console.log("Test 10: run --output-schema cannot be used with --no-wait");
|
||||
console.log("Test 10: run --output-schema cannot be used with --background");
|
||||
const result =
|
||||
await $`PASEO_HOME=${paseoHome} npx paseo --host localhost:${port} run --no-wait --output-schema ${schemaPath} "test prompt"`.nothrow();
|
||||
assert.notStrictEqual(result.exitCode, 0, "should fail with --no-wait and --output-schema");
|
||||
await $`PASEO_HOME=${paseoHome} npx paseo --host localhost:${port} run --background --output-schema ${schemaPath} "test prompt"`.nothrow();
|
||||
assert.notStrictEqual(result.exitCode, 0, "should fail with --background and --output-schema");
|
||||
const output = result.stdout + result.stderr;
|
||||
assert(
|
||||
output.includes("--output-schema cannot be used with --no-wait"),
|
||||
output.includes("--output-schema cannot be used with --background"),
|
||||
"error should explain background incompatibility",
|
||||
);
|
||||
console.log("✓ run --output-schema cannot be used with --no-wait\n");
|
||||
console.log("✓ run --output-schema cannot be used with --background\n");
|
||||
}
|
||||
|
||||
// Test 11: -q (quiet) flag is accepted with run
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import assert from "node:assert";
|
||||
import { basename } from "node:path";
|
||||
import { createPaseoClient } from "@getpaseo/client";
|
||||
import { createE2ETestContext } from "./helpers/test-daemon.ts";
|
||||
|
||||
console.log("=== Workspace Rename Command ===\n");
|
||||
@@ -52,61 +51,8 @@ try {
|
||||
)?.name,
|
||||
basename(ctx.workDir),
|
||||
);
|
||||
|
||||
await verifyWorkspaceCallerContext();
|
||||
} finally {
|
||||
await ctx.stop();
|
||||
}
|
||||
|
||||
console.log("=== Workspace Rename Command Tests Passed ===");
|
||||
|
||||
async function verifyWorkspaceCallerContext() {
|
||||
const sdk = createPaseoClient({ url: `${ctx.wsUrl}/ws`, reconnect: { enabled: false } });
|
||||
try {
|
||||
await sdk.connect();
|
||||
const parentWorkspace = await sdk.workspaces.create({
|
||||
source: { kind: "directory", path: ctx.workDir },
|
||||
background: true,
|
||||
});
|
||||
// Creation without a prompt stays idle; this visibility test runs no provider turn.
|
||||
const parent = await parentWorkspace.agents.create({ config: { provider: "claude/haiku" } });
|
||||
const cases = [
|
||||
{ caller: parent.id, background: undefined, expected: true },
|
||||
{ caller: parent.id, background: false, expected: false },
|
||||
{ caller: parent.id, background: true, expected: true },
|
||||
{ caller: "foreign-or-missing-agent", background: undefined, expected: false },
|
||||
{ caller: "foreign-or-missing-agent", background: true, expected: true },
|
||||
{ caller: "foreign-or-missing-agent", background: false, expected: false },
|
||||
{ caller: "", background: undefined, expected: false },
|
||||
{ caller: "", background: true, expected: true },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const result = await ctx.paseo(
|
||||
[
|
||||
"workspace",
|
||||
"create",
|
||||
"--host",
|
||||
`127.0.0.1:${ctx.port}`,
|
||||
"--isolation",
|
||||
"local",
|
||||
"--path",
|
||||
ctx.workDir,
|
||||
...(entry.background === undefined
|
||||
? []
|
||||
: [entry.background ? "--background" : "--no-background"]),
|
||||
"--json",
|
||||
],
|
||||
{ env: { PASEO_AGENT_ID: entry.caller } },
|
||||
);
|
||||
assert.strictEqual(result.exitCode, 0, result.stderr);
|
||||
assert.strictEqual(
|
||||
JSON.parse(result.stdout).background,
|
||||
entry.expected,
|
||||
JSON.stringify(entry),
|
||||
);
|
||||
}
|
||||
console.log("✓ workspace create caller inheritance, foreign/blank defaults, and overrides");
|
||||
} finally {
|
||||
await sdk.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3100,162 +3100,6 @@ test("sends worktree target and autoArchive in create_agent_request", async () =
|
||||
await expect(createPromise).rejects.toThrow("worktree auto archive sentinel");
|
||||
});
|
||||
|
||||
test("sends internal in create_agent_request when the host advertises internal agents", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen({ features: { backgroundWorkspaces: true } });
|
||||
await connectPromise;
|
||||
|
||||
const createPromise = client.createAgent({
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(mock.sent).toHaveLength(1);
|
||||
const request = parseSentFrame(mock.sent[0]);
|
||||
expect(request).toEqual(
|
||||
expect.objectContaining({
|
||||
type: "create_agent_request",
|
||||
config: { provider: "codex", cwd: "/tmp/project" },
|
||||
background: true,
|
||||
}),
|
||||
);
|
||||
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "agent_create_failed",
|
||||
requestId: request.requestId,
|
||||
error: "internal agent sentinel",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(createPromise).rejects.toThrow("internal agent sentinel");
|
||||
});
|
||||
|
||||
test("rejects an internal create before sending when the host predates internal agents", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen({ features: {} });
|
||||
await connectPromise;
|
||||
|
||||
await expect(
|
||||
client.createAgent({ provider: "codex", cwd: "/tmp/project", background: true }),
|
||||
).rejects.toThrow("Update the host to use background workspaces.");
|
||||
expect(mock.sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("sends internal workspace creation and internal listings only to hosts that support them", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
// workspaceMultiplicity keeps the fetch on the real workspace directory RPC.
|
||||
mock.triggerOpen({
|
||||
features: { workspaceMultiplicity: true, backgroundWorkspaces: true },
|
||||
});
|
||||
await connectPromise;
|
||||
|
||||
void client
|
||||
.createWorkspace({ source: { kind: "directory", path: "/tmp/project" }, background: true })
|
||||
.catch(() => undefined);
|
||||
void client.fetchWorkspaces({ filter: { includeBackground: true } }).catch(() => undefined);
|
||||
void client.fetchAgents({ filter: { includeBackground: true } }).catch(() => undefined);
|
||||
|
||||
expect(mock.sent.map((frame) => parseSentFrame(frame))).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "workspace.create.request", background: true }),
|
||||
expect.objectContaining({
|
||||
type: "fetch_workspaces_request",
|
||||
filter: { includeBackground: true },
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "fetch_agents_request",
|
||||
filter: { includeBackground: true },
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects internal workspace creation and internal listings before sending on older hosts", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen({ features: {} });
|
||||
await connectPromise;
|
||||
|
||||
await expect(
|
||||
client.createWorkspace({
|
||||
source: { kind: "directory", path: "/tmp/project" },
|
||||
background: true,
|
||||
}),
|
||||
).rejects.toThrow("Update the host to use background workspaces.");
|
||||
await expect(client.fetchWorkspaces({ filter: { includeBackground: true } })).rejects.toThrow(
|
||||
"Update the host to use background workspaces.",
|
||||
);
|
||||
expect(mock.sent).toHaveLength(0);
|
||||
|
||||
// Agent listings gate on the older internalAgents feature.
|
||||
const olderMock = createMockTransport();
|
||||
const olderClient = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => olderMock.transport,
|
||||
});
|
||||
clients.push(olderClient);
|
||||
const olderConnect = olderClient.connect();
|
||||
olderMock.triggerOpen({ features: {} });
|
||||
await olderConnect;
|
||||
await expect(olderClient.fetchAgents({ filter: { includeBackground: true } })).rejects.toThrow(
|
||||
"Update the host to use background workspaces.",
|
||||
);
|
||||
expect(olderMock.sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("sends structured attachments with create_agent_request", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
@@ -7481,49 +7325,3 @@ test("usage request timeout detaches its update listener", async () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([false, true])(
|
||||
"agent provenance requires host support=%s while human sends remain compatible",
|
||||
async (supported) => {
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "provenance",
|
||||
transportFactory: () => transport.transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
const connecting = client.connect();
|
||||
transport.triggerOpen({ features: { agentMessageProvenance: supported } });
|
||||
await connecting;
|
||||
if (!supported) {
|
||||
await expect(
|
||||
client.sendAgentMessage("recipient", "review", { sourceAgentId: "server::sender" }),
|
||||
).rejects.toThrow("Update the Paseo host");
|
||||
expect(transport.sent).toHaveLength(0);
|
||||
}
|
||||
const send = client.sendAgentMessage("recipient", "review", {
|
||||
messageId: "delivery",
|
||||
...(supported ? { sourceAgentId: "server::sender" } : {}),
|
||||
});
|
||||
const request = parseSentFrame(transport.sent[0]);
|
||||
expect(request).toMatchObject({
|
||||
type: "send_agent_message_request",
|
||||
text: "review",
|
||||
messageId: "delivery",
|
||||
});
|
||||
expect(request.sourceAgentId).toBe(supported ? "server::sender" : undefined);
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
agentId: "recipient",
|
||||
accepted: true,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await send;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -424,7 +424,6 @@ export interface DaemonClientTrace {
|
||||
}
|
||||
|
||||
export interface SendMessageOptions {
|
||||
sourceAgentId?: string;
|
||||
messageId?: string;
|
||||
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
@@ -460,7 +459,6 @@ export interface CreateAgentRequestOptions extends AgentConfigOverrides {
|
||||
git?: GitSetupOptions;
|
||||
worktree?: CreateAgentRequestMessage["worktree"];
|
||||
autoArchive?: CreateAgentRequestMessage["autoArchive"];
|
||||
background?: CreateAgentRequestMessage["background"];
|
||||
// COMPAT(createAgentWorktree): low-level old callers may still send the
|
||||
// create-agent worktree field. Added in v0.2.0; remove after 2027-01-17.
|
||||
worktreeName?: string;
|
||||
@@ -471,9 +469,6 @@ export interface CreateAgentRequestOptions extends AgentConfigOverrides {
|
||||
export interface CreateWorkspaceRequestOptions {
|
||||
source: WorkspaceCreateRequest["source"];
|
||||
title?: string;
|
||||
/** Workspace discovery visibility; contents retain normal durability. */
|
||||
background?: boolean;
|
||||
callerAgentId?: string;
|
||||
idempotencyKey?: string;
|
||||
workspaceId?: string;
|
||||
agent?: Omit<
|
||||
@@ -1200,25 +1195,6 @@ export function supportsUsageReports(features: ServerInfoStatusPayload["features
|
||||
return features?.usageSources === true || features?.providerUsageList === true;
|
||||
}
|
||||
|
||||
function buildFetchAgentsRequest(
|
||||
options: FetchAgentsOptions | undefined,
|
||||
requestId: string,
|
||||
): SessionInboundMessage {
|
||||
return SessionInboundMessageSchema.parse({
|
||||
type: "fetch_agents_request",
|
||||
requestId,
|
||||
...(options?.scope ? { scope: options.scope } : {}),
|
||||
...(options?.filter ? { filter: options.filter } : {}),
|
||||
...(options?.sort ? { sort: options.sort } : {}),
|
||||
...(options?.page ? { page: options.page } : {}),
|
||||
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
|
||||
...(options?.sync ? { sync: options.sync } : {}),
|
||||
...(options?.includeBackground !== undefined
|
||||
? { includeBackground: options.includeBackground }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
export class DaemonClient {
|
||||
private readonly providerSnapshotUpdates = new ProviderSnapshotUpdates({
|
||||
active: (message) => this.owned.owns(message),
|
||||
@@ -2365,8 +2341,6 @@ export class DaemonClient {
|
||||
observeAgents(
|
||||
options: Omit<FetchAgentsOptions, "subscribe"> = {},
|
||||
): OwnedSubscription<FetchAgentsPayload> {
|
||||
if (options.includeBackground || options.filter?.includeBackground)
|
||||
this.requireBackgroundWorkspaces();
|
||||
const { signal, requestId, timeout, ...query } = options;
|
||||
return this.observe(
|
||||
"fetch_agents_response",
|
||||
@@ -2378,8 +2352,6 @@ export class DaemonClient {
|
||||
observeWorkspaces(
|
||||
options: Omit<FetchWorkspacesOptions, "subscribe"> = {},
|
||||
): OwnedSubscription<FetchWorkspacesPayload> {
|
||||
if (options.includeBackground || options.filter?.includeBackground)
|
||||
this.requireBackgroundWorkspaces();
|
||||
const { signal, requestId, ...query } = options;
|
||||
return this.observe(
|
||||
"fetch_workspaces_response",
|
||||
@@ -2395,8 +2367,6 @@ export class DaemonClient {
|
||||
async fetchAgents(
|
||||
options?: FetchAgentsOptions,
|
||||
): Promise<FetchAgentsPayload & { subscription?: OwnedSubscription<FetchAgentsPayload> }> {
|
||||
if (options?.includeBackground || options?.filter?.includeBackground)
|
||||
this.requireBackgroundWorkspaces();
|
||||
if (options?.subscribe) {
|
||||
if (options.subscribe.subscriptionId !== undefined)
|
||||
throw new Error("Subscription IDs are assigned by the host");
|
||||
@@ -2404,7 +2374,16 @@ export class DaemonClient {
|
||||
return { ...(await subscription.ready), subscription };
|
||||
}
|
||||
const resolvedRequestId = this.createRequestId(options?.requestId);
|
||||
const message = buildFetchAgentsRequest(options, resolvedRequestId);
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
type: "fetch_agents_request",
|
||||
requestId: resolvedRequestId,
|
||||
...(options?.scope ? { scope: options.scope } : {}),
|
||||
...(options?.filter ? { filter: options.filter } : {}),
|
||||
...(options?.sort ? { sort: options.sort } : {}),
|
||||
...(options?.page ? { page: options.page } : {}),
|
||||
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
|
||||
...(options?.sync ? { sync: options.sync } : {}),
|
||||
});
|
||||
return this.sendRequest({
|
||||
requestId: resolvedRequestId,
|
||||
message,
|
||||
@@ -2423,7 +2402,6 @@ export class DaemonClient {
|
||||
}
|
||||
|
||||
async fetchAgentHistory(options?: FetchAgentHistoryOptions): Promise<FetchAgentHistoryPayload> {
|
||||
if (options?.filter?.includeBackground) this.requireBackgroundWorkspaces();
|
||||
const resolvedRequestId = this.createRequestId(options?.requestId);
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
type: "fetch_agent_history_request",
|
||||
@@ -2487,8 +2465,6 @@ export class DaemonClient {
|
||||
): Promise<
|
||||
FetchWorkspacesPayload & { subscription?: OwnedSubscription<FetchWorkspacesPayload> }
|
||||
> {
|
||||
if (options?.includeBackground || options?.filter?.includeBackground)
|
||||
this.requireBackgroundWorkspaces();
|
||||
if (options?.subscribe) {
|
||||
if (options.subscribe.subscriptionId !== undefined)
|
||||
throw new Error("Subscription IDs are assigned by the host");
|
||||
@@ -2498,8 +2474,12 @@ export class DaemonClient {
|
||||
const resolvedRequestId = this.createRequestId(options?.requestId);
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
type: "fetch_workspaces_request",
|
||||
...options,
|
||||
requestId: resolvedRequestId,
|
||||
...(options?.filter ? { filter: options.filter } : {}),
|
||||
...(options?.sort ? { sort: options.sort } : {}),
|
||||
...(options?.page ? { page: options.page } : {}),
|
||||
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
|
||||
...(options?.sync ? { sync: options.sync } : {}),
|
||||
});
|
||||
return this.sendRequest({
|
||||
requestId: resolvedRequestId,
|
||||
@@ -2872,19 +2852,7 @@ export class DaemonClient {
|
||||
legacyWorkspace: (input) => this.createLegacyWorkspace(input, input.requestId),
|
||||
});
|
||||
|
||||
// Background workspaces are gated once at the transport boundary.
|
||||
private requireBackgroundWorkspaces(): void {
|
||||
if (this.lastServerInfoMessage?.features?.backgroundWorkspaces !== true) {
|
||||
throw new Error("Update the host to use background workspaces.");
|
||||
}
|
||||
}
|
||||
|
||||
supportsBackgroundWorkspaces(): boolean {
|
||||
return this.lastServerInfoMessage?.features?.backgroundWorkspaces === true;
|
||||
}
|
||||
|
||||
async createAgent(options: CreateAgentRequestOptions): Promise<AgentSnapshotPayload> {
|
||||
if (options.background !== undefined) this.requireBackgroundWorkspaces();
|
||||
const result = await this.creations.createAgent({
|
||||
...options,
|
||||
config: resolveAgentConfig(options),
|
||||
@@ -2917,7 +2885,6 @@ export class DaemonClient {
|
||||
...(options.git ? { git: options.git } : {}),
|
||||
...(options.worktree ? { worktree: options.worktree } : {}),
|
||||
...(options.autoArchive !== undefined ? { autoArchive: options.autoArchive } : {}),
|
||||
...(options.background !== undefined ? { background: options.background } : {}),
|
||||
...(options.worktreeName ? { worktreeName: options.worktreeName } : {}),
|
||||
...(options.labels && Object.keys(options.labels).length > 0
|
||||
? { labels: options.labels }
|
||||
@@ -3480,12 +3447,6 @@ export class DaemonClient {
|
||||
text: string,
|
||||
options?: SendMessageOptions,
|
||||
): Promise<void> {
|
||||
if (
|
||||
options?.sourceAgentId &&
|
||||
this.lastServerInfoMessage?.features?.agentMessageProvenance !== true
|
||||
) {
|
||||
throw new Error("Update the Paseo host to send messages with agent provenance.");
|
||||
}
|
||||
const requestId = this.createRequestId();
|
||||
const messageId = options?.messageId ?? crypto.randomUUID();
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
@@ -3493,7 +3454,6 @@ export class DaemonClient {
|
||||
requestId,
|
||||
agentId,
|
||||
text,
|
||||
sourceAgentId: options?.sourceAgentId,
|
||||
...(messageId ? { messageId } : {}),
|
||||
...(options?.activeTurnBehavior ? { activeTurnBehavior: options.activeTurnBehavior } : {}),
|
||||
...(options?.images ? { images: options.images } : {}),
|
||||
@@ -4592,9 +4552,6 @@ export class DaemonClient {
|
||||
requestId?: string,
|
||||
): Promise<WorkspaceCreatePayload> {
|
||||
const resolvedRequestId = this.createRequestId(requestId ?? input.requestId);
|
||||
if (input.background !== undefined || input.callerAgentId) this.requireBackgroundWorkspaces();
|
||||
if (input.agent?.background !== undefined)
|
||||
throw new Error("Configure background on the workspace, not its initial agent.");
|
||||
const result = await this.creations.createWorkspace({
|
||||
...input,
|
||||
requestId: resolvedRequestId,
|
||||
@@ -4626,8 +4583,6 @@ export class DaemonClient {
|
||||
? { idempotencyKey: input.idempotencyKey }
|
||||
: {}),
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.background !== undefined ? { background: input.background } : {}),
|
||||
...(input.callerAgentId ? { callerAgentId: input.callerAgentId } : {}),
|
||||
...(input.firstAgentContext !== undefined
|
||||
? { firstAgentContext: input.firstAgentContext }
|
||||
: {}),
|
||||
@@ -6977,7 +6932,6 @@ function resolveAgentConfig(options: CreateAgentRequestOptions): AgentSessionCon
|
||||
attachments: _attachments,
|
||||
worktree: _worktree,
|
||||
autoArchive: _autoArchive,
|
||||
background: _background,
|
||||
env: _env,
|
||||
workspaceId: _workspaceId,
|
||||
initialPrompt: _initialPrompt,
|
||||
|
||||
@@ -691,61 +691,6 @@ test("plugin-shaped PR workspace create and agent create use the existing daemon
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("agents.create forwards internal on the request, outside the agent config", async () => {
|
||||
const { client, ws } = await connectClient({
|
||||
providerUsageList: true,
|
||||
providersSnapshotCwd: true,
|
||||
ownedSubscriptions: true,
|
||||
backgroundWorkspaces: true,
|
||||
});
|
||||
|
||||
const createPromise = client.agents.create({
|
||||
config: { provider: "codex/gpt-5.4" },
|
||||
cwd: "/repo/sdk",
|
||||
title: "Summary helper",
|
||||
background: true,
|
||||
autoArchive: true,
|
||||
});
|
||||
const request = parseSentSessionMessage(ws.sent.at(-1));
|
||||
expect(request).toMatchObject({
|
||||
type: "create_agent_request",
|
||||
config: { provider: "codex", model: "gpt-5.4", cwd: "/repo/sdk", title: "Summary helper" },
|
||||
background: true,
|
||||
autoArchive: true,
|
||||
});
|
||||
expect(request.config).not.toHaveProperty("internal");
|
||||
ws.message(
|
||||
sessionMessage({
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "agent_created",
|
||||
requestId: request.requestId,
|
||||
agentId: "agent_helper",
|
||||
agent: createAgent({ id: "agent_helper" }),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const agent = await createPromise;
|
||||
expect(agent.id).toBe("agent_helper");
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("agents.create with internal fails before sending on a host without internal agents", async () => {
|
||||
const { client, ws } = await connectClient();
|
||||
const sentBefore = ws.sent.length;
|
||||
|
||||
await expect(
|
||||
client.agents.create({
|
||||
config: { provider: "codex/gpt-5.4" },
|
||||
cwd: "/repo/sdk",
|
||||
background: true,
|
||||
}),
|
||||
).rejects.toThrow("Update the host to use background workspaces.");
|
||||
expect(ws.sent).toHaveLength(sentBefore);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("agent handles delegate create, send, timeline refetch, archive, and local updates", async () => {
|
||||
const { client, ws } = await connectClient();
|
||||
const createdAgent = createAgent();
|
||||
|
||||
@@ -257,8 +257,6 @@ export interface PaseoAgentCreateOptions {
|
||||
git?: CreateAgentRequestMessage["git"];
|
||||
worktree?: CreateAgentRequestMessage["worktree"];
|
||||
autoArchive?: CreateAgentRequestMessage["autoArchive"];
|
||||
/** Visibility intent for a NEW workspace. Existing targets reject this option. */
|
||||
background?: CreateAgentRequestMessage["background"];
|
||||
requestId?: string;
|
||||
labels?: Record<string, string>;
|
||||
}
|
||||
@@ -782,12 +780,9 @@ function createWorkspaceHandleFactory(
|
||||
const refresh = async (options?: { requestId?: string }) => {
|
||||
let cursor: string | undefined;
|
||||
let requestId = options?.requestId;
|
||||
// A ref addresses one workspace by id, so a background one resolves too.
|
||||
const filter = daemonClient.supportsBackgroundWorkspaces() ? { includeBackground: true } : {};
|
||||
do {
|
||||
const result = await daemonClient.fetchWorkspaces({
|
||||
requestId,
|
||||
filter,
|
||||
page: { limit: 200, ...(cursor ? { cursor } : {}) },
|
||||
});
|
||||
const match = result.entries.find((entry) => entry.id === id);
|
||||
|
||||
@@ -287,6 +287,7 @@ async function createCallerAgent(daemonPort, workspaceId = workspaceIds[0]) {
|
||||
provider: "mock/ten-second-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Remain available while the browser bridge regression runs.",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
const result = response.structuredContent;
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { AgentMessage } from "./agent-message.js";
|
||||
import type { ToolCallDetail } from "./agent-types.js";
|
||||
|
||||
/** Presentation shared by clients; never used to encode provider prompts. */
|
||||
export function buildAgentMessageDisplay(message: AgentMessage): {
|
||||
displayName: string;
|
||||
detail: ToolCallDetail;
|
||||
} {
|
||||
const sender = message.sender.title ?? message.sender.id;
|
||||
const headings: Record<AgentMessage["event"], string> = {
|
||||
message: `Message from ${sender}`,
|
||||
finished: `${sender} finished`,
|
||||
errored: `${sender} errored`,
|
||||
"permission-required": `${sender} needs permission`,
|
||||
closed: `${sender} closed`,
|
||||
};
|
||||
return {
|
||||
displayName: headings[message.event],
|
||||
detail: {
|
||||
type: "plain_text",
|
||||
icon: "bot",
|
||||
text: `From agent: ${message.sender.id}\n\n${message.text}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Semantic provenance, independent of provider envelopes and timeline presentation. */
|
||||
export const AgentMessageSchema = z.object({
|
||||
event: z.enum(["message", "finished", "errored", "permission-required", "closed"]),
|
||||
sender: z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1).optional(),
|
||||
}),
|
||||
text: z.string(),
|
||||
});
|
||||
|
||||
export type AgentMessage = z.infer<typeof AgentMessageSchema>;
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { AgentMessage } from "./agent-message.js";
|
||||
import type { AgentAttachment } from "./messages.js";
|
||||
|
||||
export type AgentProvider = string;
|
||||
@@ -312,7 +311,6 @@ export type ToolCallDetail =
|
||||
};
|
||||
|
||||
interface ToolCallBase {
|
||||
agentMessage?: AgentMessage;
|
||||
[key: string]: unknown;
|
||||
type: "tool_call";
|
||||
callId: string;
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { SessionInboundMessageSchema } from "./messages.js";
|
||||
|
||||
describe("create request internal field", () => {
|
||||
test("accepts internal on create_agent_request", () => {
|
||||
const parsed = SessionInboundMessageSchema.parse({
|
||||
type: "create_agent_request",
|
||||
requestId: "create-agent-internal",
|
||||
config: {
|
||||
provider: "codex",
|
||||
cwd: "/repo/app",
|
||||
},
|
||||
internal: true,
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: "create_agent_request",
|
||||
requestId: "create-agent-internal",
|
||||
config: {
|
||||
provider: "codex",
|
||||
cwd: "/repo/app",
|
||||
},
|
||||
internal: true,
|
||||
labels: {},
|
||||
});
|
||||
});
|
||||
|
||||
test("accepts internal on agent.create.request", () => {
|
||||
const parsed = SessionInboundMessageSchema.parse({
|
||||
type: "agent.create.request",
|
||||
requestId: "agent-create-internal",
|
||||
config: {
|
||||
provider: "codex",
|
||||
cwd: "/repo/app",
|
||||
},
|
||||
internal: true,
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
type: "agent.create.request",
|
||||
requestId: "agent-create-internal",
|
||||
config: {
|
||||
provider: "codex",
|
||||
cwd: "/repo/app",
|
||||
},
|
||||
internal: true,
|
||||
labels: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
AgentTimelineItemPayloadSchema,
|
||||
FileExplorerRequestSchema,
|
||||
PaseoWorktreeArchiveRequestSchema,
|
||||
parseServerInfoStatusPayload,
|
||||
@@ -521,30 +520,3 @@ describe("viewed timeline subscription messages", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("agent messages are an optional semantic payload on existing tool rows", () => {
|
||||
const legacy = {
|
||||
type: "tool_call",
|
||||
callId: "delivery",
|
||||
name: "agent_message",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", text: "Done" },
|
||||
};
|
||||
const agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "server::worker", title: "Reviewer" },
|
||||
text: "Done",
|
||||
};
|
||||
expect(AgentTimelineItemPayloadSchema.parse(legacy)).toEqual(legacy);
|
||||
expect(AgentTimelineItemPayloadSchema.parse({ ...legacy, agentMessage })).toEqual({
|
||||
...legacy,
|
||||
agentMessage,
|
||||
});
|
||||
expect(
|
||||
AgentTimelineItemPayloadSchema.safeParse({
|
||||
...legacy,
|
||||
agentMessage: { ...agentMessage, sender: { id: 42 } },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { AgentMessageSchema } from "./agent-message.js";
|
||||
import { PluginRegistryIdentitySchema } from "./plugin-registry.js";
|
||||
import { AgentProfileSchema, AgentSkillSelectionSchema } from "./agent-profile.js";
|
||||
export {
|
||||
@@ -626,7 +625,6 @@ const ToolCallDetailPayloadSchema: z.ZodType<ToolCallDetail, unknown> = z.discri
|
||||
);
|
||||
|
||||
const ToolCallBasePayloadSchema = z.object({
|
||||
agentMessage: AgentMessageSchema.optional(),
|
||||
type: z.literal("tool_call"),
|
||||
callId: z.string(),
|
||||
name: z.string(),
|
||||
@@ -839,8 +837,6 @@ export const AgentSnapshotPayloadSchema = z.object({
|
||||
attentionTimestamp: z.string().nullable().optional(),
|
||||
archivedAt: z.string().nullable().optional(),
|
||||
providerUnavailable: z.boolean().optional(),
|
||||
// Private helper marker, retained for exact-ID snapshots and older wire messages.
|
||||
internal: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type AgentSnapshotPayload = z.infer<typeof AgentSnapshotPayloadSchema>;
|
||||
@@ -912,9 +908,6 @@ const AgentDirectoryFilterSchema = z.object({
|
||||
includeArchived: z.boolean().optional(),
|
||||
requiresAttention: z.boolean().optional(),
|
||||
thinkingOptionId: z.string().nullable().optional(),
|
||||
// Retained for wire parsing; private helpers are excluded from public discovery.
|
||||
includeInternal: z.boolean().optional(),
|
||||
includeBackground: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const DeleteAgentRequestMessageSchema = z.object({
|
||||
@@ -1242,7 +1235,6 @@ export const FetchAgentsRequestMessageSchema = z.object({
|
||||
type: z.literal("fetch_agents_request"),
|
||||
requestId: z.string(),
|
||||
scope: z.enum(["active"]).optional(),
|
||||
includeBackground: z.boolean().optional(),
|
||||
filter: AgentDirectoryFilterSchema.optional(),
|
||||
sort: z
|
||||
.array(
|
||||
@@ -1276,7 +1268,6 @@ const WorkspaceStateBucketSchema = z.enum([
|
||||
]);
|
||||
|
||||
export const FetchWorkspacesRequestMessageSchema = z.object({
|
||||
includeBackground: z.boolean().optional(),
|
||||
type: z.literal("fetch_workspaces_request"),
|
||||
requestId: z.string(),
|
||||
filter: z
|
||||
@@ -1285,9 +1276,6 @@ export const FetchWorkspacesRequestMessageSchema = z.object({
|
||||
projectId: z.string().optional(),
|
||||
// Unused: accepted so older clients still parse, but the server does not filter on it.
|
||||
idPrefix: z.string().optional(),
|
||||
// Retained for wire parsing of older requests.
|
||||
includeInternal: z.boolean().optional(),
|
||||
includeBackground: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
sort: z
|
||||
@@ -1366,8 +1354,6 @@ export const SendAgentMessageRequestSchema = z.object({
|
||||
/** Accepts full ID, unique prefix, or exact full title (server resolves). */
|
||||
agentId: z.string(),
|
||||
text: z.string(),
|
||||
/** Opaque sender identity for agent-originated prompts. */
|
||||
sourceAgentId: z.string().min(1).optional(),
|
||||
messageId: z.string().optional(), // Client-provided ID for deduplication
|
||||
activeTurnBehavior: ActiveTurnBehaviorSchema.optional(),
|
||||
images: z.array(ImageAttachmentSchema).optional(),
|
||||
@@ -1724,13 +1710,6 @@ export const CreateAgentRequestMessageSchema = z.object({
|
||||
git: GitSetupOptionsSchema.optional(),
|
||||
worktree: CreateAgentWorktreeTargetSchema.optional(),
|
||||
autoArchive: z.boolean().optional(),
|
||||
// An ephemeral helper: the daemon never persists, lists, flags or announces
|
||||
// it, and plugin lifecycle hooks skip it. Lives on the request rather than
|
||||
// in the config schema, which is reused for updates. Retained for wire parsing;
|
||||
// public internal creation is no longer supported.
|
||||
internal: z.boolean().optional(),
|
||||
// Workspace creation intent, rejected when selecting an existing workspace.
|
||||
background: z.boolean().optional(),
|
||||
labels: z.record(z.string(), z.string()).default({}),
|
||||
requestId: z.string(),
|
||||
});
|
||||
@@ -2650,10 +2629,6 @@ export const WorkspaceCreateRequestSchema = z.object({
|
||||
title: z.string().optional(),
|
||||
// Optional prompt context for workspace-level name/branch generation.
|
||||
firstAgentContext: FirstAgentContextSchema.optional(),
|
||||
// Retained for wire parsing; public internal creation is no longer supported.
|
||||
internal: z.boolean().optional(),
|
||||
background: z.boolean().optional(),
|
||||
callerAgentId: z.string().optional(),
|
||||
source: z.discriminatedUnion("kind", [
|
||||
z.object({
|
||||
kind: z.literal("directory"),
|
||||
@@ -3579,11 +3554,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
creationLifecycle: z.boolean().optional(),
|
||||
// COMPAT(hubAgentRpc): added in v0.8.0; remove gate after 2027-03-05.
|
||||
hubAgentRpc: z.boolean().optional(),
|
||||
// COMPAT(internalAgents): added in v0.9.0; remove gate after 2027-03-17.
|
||||
internalAgents: z.boolean().optional(),
|
||||
// COMPAT(internalWorkspaces): added in v0.9.0; remove gate after 2027-03-17.
|
||||
internalWorkspaces: z.boolean().optional(),
|
||||
backgroundWorkspaces: z.boolean().optional(),
|
||||
providersSnapshot: z.boolean().optional(),
|
||||
usageSources: z.boolean().optional(),
|
||||
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
|
||||
@@ -3725,7 +3695,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
ownedSubscriptions: z.boolean().optional(),
|
||||
// COMPAT(canonicalSubmittedPrompts): added in v0.2.6, remove gate after 2027-01-30.
|
||||
canonicalSubmittedPrompts: z.boolean().optional(),
|
||||
agentMessageProvenance: z.boolean().optional(),
|
||||
// COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31.
|
||||
agentTurnIdentity: z.boolean().optional(),
|
||||
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
|
||||
@@ -4050,9 +4019,6 @@ export const WorkspaceDescriptorPayloadSchema = z
|
||||
pinnedAt: z.string().nullable().optional(),
|
||||
// COMPAT(workspaceLabels): added in v0.5.0, remove optional after 2027-08-14.
|
||||
labels: z.array(z.string()).optional(),
|
||||
// Retained for wire parsing of older daemon descriptors.
|
||||
internal: z.boolean().optional(),
|
||||
background: z.boolean().optional(),
|
||||
archivingAt: z.string().nullable().optional().default(null),
|
||||
status: WorkspaceStateBucketSchema,
|
||||
// Best-effort workspace status entry timestamp. Old daemons omit the
|
||||
|
||||
@@ -47,7 +47,6 @@ const AGENT_FIELDS = [
|
||||
"modeId",
|
||||
"background",
|
||||
"notifyOnFinish",
|
||||
"internal",
|
||||
"settings",
|
||||
"labels",
|
||||
] as const;
|
||||
@@ -197,7 +196,6 @@ const FIELD_LABELS: Readonly<Record<string, string>> = {
|
||||
newMode: "New mode",
|
||||
nextRunAt: "Next run",
|
||||
notifyOnFinish: "Notify on finish",
|
||||
internal: "Internal",
|
||||
prNumber: "Change request",
|
||||
projectId: "Project",
|
||||
removedDirectory: "Removed directory",
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { buildAgentMessageDisplay } from "./agent-message-display.js";
|
||||
import type { ToolCallTimelineItem } from "./agent-types.js";
|
||||
import { getPaseoToolLeafName, isPaseoToolName } from "./tool-name-normalization.js";
|
||||
import { stripCwdPrefix } from "./path-utils.js";
|
||||
|
||||
export type ToolCallDisplayInput = Pick<
|
||||
ToolCallTimelineItem,
|
||||
"name" | "status" | "error" | "metadata" | "detail" | "agentMessage"
|
||||
"name" | "status" | "error" | "metadata" | "detail"
|
||||
> & {
|
||||
cwd?: string;
|
||||
};
|
||||
@@ -152,9 +151,6 @@ function buildUnknownDetailOverride(input: ToolCallDisplayInput): DetailDisplay
|
||||
}
|
||||
|
||||
export function buildToolCallDisplayModel(input: ToolCallDisplayInput): ToolCallDisplayModel {
|
||||
if (input.agentMessage) {
|
||||
return { displayName: buildAgentMessageDisplay(input.agentMessage).displayName };
|
||||
}
|
||||
const canonicalDisplay = buildCanonicalDetailDisplay(input);
|
||||
const unknownDetailOverride = buildUnknownDetailOverride(input);
|
||||
const displayName =
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -438,49 +438,3 @@ second line'`,
|
||||
).toThrow("Selected assistant message is no longer available.");
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds fork history to 100,000 characters while preserving the newest messages", () => {
|
||||
const result = buildAgentForkContextAttachment({
|
||||
rows: [
|
||||
row(1, { type: "user_message", text: "old-message " + "x".repeat(1_100_000) }),
|
||||
row(2, { type: "assistant_message", messageId: "checkpoint", text: "Latest answer." }),
|
||||
row(3, { type: "user_message", text: "Beyond the selected checkpoint." }),
|
||||
],
|
||||
boundaryMessageId: "checkpoint",
|
||||
});
|
||||
expect(result.attachment.text.length).toBeLessThanOrEqual(100_000);
|
||||
expect(result.attachment.text).toContain("[Earlier chat history omitted]");
|
||||
expect(result.attachment.text).toContain("[Assistant] Latest answer.");
|
||||
expect(result.attachment.text).not.toContain("old-message");
|
||||
expect(result.attachment.text).not.toContain("Beyond the selected checkpoint.");
|
||||
expect(result.attachment.text).toMatch(/^<chat-history-summary>\n/);
|
||||
expect(result.attachment.text).toMatch(/\n<\/chat-history-summary>$/);
|
||||
});
|
||||
|
||||
it("bounds one oversized fork message and metadata without losing its beginning and end", () => {
|
||||
const result = buildAgentForkContextAttachment({
|
||||
rows: [
|
||||
row(1, {
|
||||
type: "assistant_message",
|
||||
text: "Beginning. " + "x".repeat(1_100_000) + " The end.",
|
||||
}),
|
||||
],
|
||||
agentTitle: "T".repeat(200_000),
|
||||
cwd: "/" + "p".repeat(200_000),
|
||||
});
|
||||
expect(result.attachment.text.length).toBe(100_000);
|
||||
expect(result.attachment.text).toContain("[Assistant] Beginning.");
|
||||
expect(result.attachment.text).toContain("[Message truncated]");
|
||||
expect(result.attachment.text).toContain("The end.");
|
||||
expect(result.attachment.text).toMatch(/\n<\/chat-history-summary>$/);
|
||||
});
|
||||
|
||||
it("preserves every message in fork history below the character budget", () => {
|
||||
const text = "Complete conversation " + "x".repeat(90_000);
|
||||
const result = buildAgentForkContextAttachment({
|
||||
rows: [row(1, { type: "user_message", text })],
|
||||
});
|
||||
expect(result.attachment.text).toBe(
|
||||
`<chat-history-summary>\nChat history from a previous Paseo agent.\n\n[User] ${text}\n</chat-history-summary>`,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -8,9 +8,6 @@ import { projectTimelineRows } from "./timeline-projection.js";
|
||||
const DEFAULT_MAX_ITEMS = 0;
|
||||
const MAX_TOOL_INPUT_CHARS = 400;
|
||||
const MAX_TOOL_SUMMARY_CHARS = 200;
|
||||
const MAX_FORK_CONTEXT_CHARS = 100_000;
|
||||
const MAX_FORK_METADATA_CHARS = 1_000;
|
||||
const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n";
|
||||
|
||||
interface ActivityCuratorOptions {
|
||||
maxItems?: number;
|
||||
@@ -279,7 +276,7 @@ function selectForkContextRows(input: {
|
||||
|
||||
function trimContextMetadata(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed.slice(0, MAX_FORK_METADATA_CHARS) : null;
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function buildForkContextText(input: {
|
||||
@@ -299,30 +296,6 @@ function buildForkContextText(input: {
|
||||
return `<chat-history-summary>\n${header.join("\n")}\n\n${input.body}\n</chat-history-summary>`;
|
||||
}
|
||||
|
||||
function fitForkContextEntries(entries: ActivityEntry[], budget: number): string {
|
||||
const length = entries.reduce((total, entry) => total + entry.text.length + 1, -1);
|
||||
if (length <= budget) return entries.map((entry) => entry.text).join("\n");
|
||||
|
||||
const selected: string[] = [];
|
||||
let remaining = budget - FORK_HISTORY_OMITTED.length;
|
||||
for (let index = entries.length - 1; index >= 0; index--) {
|
||||
const text = entries[index]!.text;
|
||||
const size = text.length + (selected.length > 0 ? 1 : 0);
|
||||
if (size > remaining) {
|
||||
if (selected.length === 0) {
|
||||
const marker = "\n[Message truncated]\n";
|
||||
const available = remaining - marker.length;
|
||||
const head = Math.ceil(available / 2);
|
||||
selected.push(text.slice(0, head) + marker + text.slice(-(available - head)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
selected.push(text);
|
||||
remaining -= size;
|
||||
}
|
||||
return FORK_HISTORY_OMITTED + selected.toReversed().join("\n");
|
||||
}
|
||||
|
||||
export function buildAgentForkContextAttachment(input: {
|
||||
rows: readonly AgentTimelineRow[];
|
||||
cursorBoundary?: ForkCursorBoundary | null;
|
||||
@@ -346,10 +319,10 @@ export function buildAgentForkContextAttachment(input: {
|
||||
includeKinds: ["user_message", "assistant_message", "tool_call"],
|
||||
includeExternalToolInput: false,
|
||||
});
|
||||
const metadata = { agentTitle: input.agentTitle, cwd: input.cwd };
|
||||
const budget = MAX_FORK_CONTEXT_CHARS - buildForkContextText({ body: "", ...metadata }).length;
|
||||
const body =
|
||||
entries.length > 0 ? fitForkContextEntries(entries, budget) : "No chat history to display.";
|
||||
entries.length > 0
|
||||
? entries.map((entry) => entry.text).join("\n")
|
||||
: "No chat history to display.";
|
||||
return {
|
||||
attachment: {
|
||||
type: "text",
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import {
|
||||
prepareAgentMessage,
|
||||
formatAgentMessage,
|
||||
formatSystemNotificationPrompt,
|
||||
} from "./agent-messages/index.js";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
@@ -23,7 +18,7 @@ import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
||||
import { toAgentPayload } from "./agent-projections.js";
|
||||
import { projectTimelineRows } from "./timeline-projection.js";
|
||||
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import { startAgentRun } from "./agent-prompt.js";
|
||||
import { formatSystemNotificationPrompt, startAgentRun } from "./agent-prompt.js";
|
||||
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
|
||||
import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
@@ -3954,23 +3949,12 @@ test("a prompt after provider replacement reopens the stale session", async () =
|
||||
clients: { [provider]: replacement },
|
||||
});
|
||||
|
||||
const dispatch = await startAgentRun(manager, created.id, "continue after reload", logger, {
|
||||
runOptions: { clientMessageId: "stale-session-retry" },
|
||||
});
|
||||
const dispatch = await startAgentRun(manager, created.id, "continue after reload", logger);
|
||||
expect(dispatch.disposition).toBe("turn_started");
|
||||
await replacement.waitForRetryStart();
|
||||
const result = await manager.waitForAgentEvent(created.id);
|
||||
expect(result.status).toBe("idle");
|
||||
expect(replacement.resumeOverrides).toHaveLength(1);
|
||||
const timeline = manager.getTimeline(created.id);
|
||||
expect(timeline.filter((item) => item.type === "user_message")).toMatchObject([
|
||||
{ text: "continue after reload", clientMessageId: "stale-session-retry" },
|
||||
]);
|
||||
expect(
|
||||
timeline.some(
|
||||
(item) => item.type === "assistant_message" && item.text.includes("[System Error]"),
|
||||
),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await manager.closeAgent(created.id).catch(() => undefined);
|
||||
await manager.flush().catch(() => undefined);
|
||||
@@ -7710,81 +7694,6 @@ test("listAgents excludes internal agents", async () => {
|
||||
const agents = manager.listAgents();
|
||||
expect(agents).toHaveLength(1);
|
||||
expect(agents[0]?.config.title).toBe("Normal Agent");
|
||||
|
||||
// Opting in lists both, and the internal one is marked.
|
||||
const everyAgent = manager.listAgents({ includeInternal: true });
|
||||
expect(everyAgent.map((agent) => [agent.config.title, agent.internal])).toEqual([
|
||||
["Normal Agent", false],
|
||||
["Internal Agent", true],
|
||||
]);
|
||||
});
|
||||
|
||||
test("workspace ownership does not turn an ordinary agent into a disposable helper", async () => {
|
||||
const agentId = "00000000-0000-4000-8000-000000000115";
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const beforeHookCalls: string[] = [];
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
logger,
|
||||
idFactory: () => agentId,
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) => {
|
||||
beforeHookCalls.push(name);
|
||||
return request;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await manager.createAgent({ provider: "codex", cwd: workdir, title: "Helper" }, undefined, {
|
||||
workspaceId: "wks_internal",
|
||||
});
|
||||
|
||||
expect(manager.getAgent(agentId)?.internal).toBe(false);
|
||||
expect(manager.listAgents().map((agent) => agent.id)).toEqual([agentId]);
|
||||
expect(await storage.get(agentId)).not.toBeNull();
|
||||
// Workspace ownership preserves ordinary agent lifecycle hooks.
|
||||
expect(beforeHookCalls).toContain("agent.create");
|
||||
});
|
||||
|
||||
test("global subscribers receive internal agent events only when they opt in", async () => {
|
||||
const internalAgentId = "00000000-0000-4000-8000-000000000116";
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
logger,
|
||||
idFactory: () => internalAgentId,
|
||||
});
|
||||
await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Internal Agent", internal: true },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
const hidden: string[] = [];
|
||||
const optedIn: string[] = [];
|
||||
const unsubscribeHidden = manager.subscribe((event) => {
|
||||
if (event.type === "agent_state") hidden.push(event.agent.id);
|
||||
});
|
||||
const unsubscribeOptedIn = manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") optedIn.push(event.agent.id);
|
||||
},
|
||||
{ includeInternal: true },
|
||||
);
|
||||
|
||||
expect(hidden).toEqual([]);
|
||||
expect(optedIn).toEqual([internalAgentId]);
|
||||
|
||||
await manager.archiveAgent(internalAgentId);
|
||||
expect(hidden).toEqual([]);
|
||||
expect(optedIn.length).toBeGreaterThan(1);
|
||||
unsubscribeHidden();
|
||||
unsubscribeOptedIn();
|
||||
});
|
||||
|
||||
test("getAgent returns internal agents by ID", async () => {
|
||||
@@ -7817,124 +7726,6 @@ test("getAgent returns internal agents by ID", async () => {
|
||||
expect(agent?.internal).toBe(true);
|
||||
});
|
||||
|
||||
test("archiveAgent closes an internal agent without writing a record", async () => {
|
||||
const internalAgentId = "00000000-0000-4000-8000-000000000108";
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new TestAgentClient(),
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
idFactory: () => internalAgentId,
|
||||
});
|
||||
|
||||
await manager.createAgent(
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: workdir,
|
||||
title: "Internal Agent",
|
||||
internal: true,
|
||||
},
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
const { archivedAt } = await manager.archiveAgent(internalAgentId);
|
||||
|
||||
expect(Number.isNaN(Date.parse(archivedAt))).toBe(false);
|
||||
expect(manager.getAgent(internalAgentId)).toBeNull();
|
||||
expect(await storage.get(internalAgentId)).toBeNull();
|
||||
expect(await storage.list()).toEqual([]);
|
||||
expect(manager.getRetiredInternalAgent(internalAgentId)).toEqual({
|
||||
record: expect.objectContaining({
|
||||
id: internalAgentId,
|
||||
title: "Internal Agent",
|
||||
internal: true,
|
||||
archivedAt,
|
||||
lastStatus: "idle",
|
||||
}),
|
||||
lastMessage: null,
|
||||
});
|
||||
expect(manager.getRetiredInternalAgent("00000000-0000-4000-8000-000000000999")).toBeNull();
|
||||
});
|
||||
|
||||
test("archiveAgent on an internal parent still archives its attached children", async () => {
|
||||
const parentAgentId = "00000000-0000-4000-8000-000000000109";
|
||||
const childAgentId = "00000000-0000-4000-8000-000000000110";
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
const ids = [parentAgentId, childAgentId];
|
||||
let agentCounter = 0;
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new TestAgentClient(),
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
idFactory: () => ids[agentCounter++] ?? randomUUID(),
|
||||
});
|
||||
|
||||
await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Internal Parent", internal: true },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await manager.createAgent({ provider: "codex", cwd: workdir, title: "Child" }, undefined, {
|
||||
workspaceId: undefined,
|
||||
labels: { "paseo.parent-agent-id": parentAgentId },
|
||||
});
|
||||
|
||||
await manager.archiveAgent(parentAgentId);
|
||||
|
||||
expect(manager.getAgent(parentAgentId)).toBeNull();
|
||||
expect(manager.getAgent(childAgentId)).toBeNull();
|
||||
const child = await storage.get(childAgentId);
|
||||
expect(child?.archivedAt).toEqual(expect.any(String));
|
||||
expect(await storage.get(parentAgentId)).toBeNull();
|
||||
});
|
||||
|
||||
test("archiveAgent on a parent archives its live internal children", async () => {
|
||||
const parentAgentId = "00000000-0000-4000-8000-000000000111";
|
||||
const childAgentId = "00000000-0000-4000-8000-000000000112";
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
const ids = [parentAgentId, childAgentId];
|
||||
let agentCounter = 0;
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new TestAgentClient(),
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
idFactory: () => ids[agentCounter++] ?? randomUUID(),
|
||||
});
|
||||
|
||||
await manager.createAgent({ provider: "codex", cwd: workdir, title: "Parent" }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
// An internal child is never in storage, so only the live scan can reach it.
|
||||
await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Internal Child", internal: true },
|
||||
undefined,
|
||||
{ workspaceId: undefined, labels: { "paseo.parent-agent-id": parentAgentId } },
|
||||
);
|
||||
expect(manager.getAgent(childAgentId)).not.toBeNull();
|
||||
|
||||
await manager.archiveAgent(parentAgentId);
|
||||
|
||||
expect(manager.getAgent(parentAgentId)).toBeNull();
|
||||
expect(manager.getAgent(childAgentId)).toBeNull();
|
||||
expect(manager.getRetiredInternalAgent(childAgentId)?.record.archivedAt).toEqual(
|
||||
expect.any(String),
|
||||
);
|
||||
expect(await storage.get(childAgentId)).toBeNull();
|
||||
});
|
||||
|
||||
test("subscribe does not emit state events for internal agents to global subscribers", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
@@ -8345,20 +8136,9 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
await expect(
|
||||
manager.runAgent(agent.id, "fail before turn id", {
|
||||
clientMessageId: "rejected-prompt",
|
||||
}),
|
||||
).rejects.toThrow("Invalid request: missing field `text`");
|
||||
expect(manager.getTimeline(agent.id)).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "fail before turn id",
|
||||
clientMessageId: "rejected-prompt",
|
||||
messageId: "rejected-prompt",
|
||||
},
|
||||
{ type: "assistant_message", text: "[System Error] Invalid request: missing field `text`" },
|
||||
]);
|
||||
await expect(manager.runAgent(agent.id, "fail before turn id")).rejects.toThrow(
|
||||
"Invalid request: missing field `text`",
|
||||
);
|
||||
|
||||
await expect(manager.runAgent(agent.id, "second turn")).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
@@ -11687,173 +11467,3 @@ test("usage session is a pure read of the live adapter and disappears on close",
|
||||
}
|
||||
expect(manager.usageSession(agent.id)).toBeNull();
|
||||
});
|
||||
|
||||
test.each(["live", "history"])(
|
||||
"agent messages become notification tools during %s ingestion",
|
||||
async (path) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-message-provenance-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const item: AgentTimelineItem = {
|
||||
type: "user_message",
|
||||
text: '<paseo-system version="1" kind="agent-message" source-agent-id="remote::sender" message-id="delivery-1">\nReview <changes> & report back.\n</paseo-system>',
|
||||
messageId: "provider-message",
|
||||
};
|
||||
const codex = fakeCodexEmitting(
|
||||
path === "live" ? { turnItems: [item] } : { historyItems: [item] },
|
||||
);
|
||||
const manager = new AgentManager({ clients: { codex }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
if (path === "live") await manager.runAgent(agent.id, { text: "start" });
|
||||
else await manager.hydrateTimelineFromProvider(agent.id, { force: true });
|
||||
expect(manager.getTimeline(agent.id)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "tool_call",
|
||||
callId: "paseo-agent-message:delivery-1",
|
||||
agentMessage: {
|
||||
event: "message",
|
||||
sender: { id: "remote::sender" },
|
||||
text: "Review <changes> & report back.",
|
||||
},
|
||||
name: "agent_message",
|
||||
status: "completed",
|
||||
detail: {
|
||||
type: "plain_text",
|
||||
icon: "bot",
|
||||
text: "Review <changes> & report back.",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(manager.getTimeline(agent.id).filter((entry) => entry.type === "user_message")).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(manager.getAgent(agent.id)?.lastUserMessageAt).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
test.each([false, true])(
|
||||
"accepted agent prompt appears once with provider echo=%s",
|
||||
async (echo) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-message-acceptance-"));
|
||||
const delivery = prepareAgentMessage(
|
||||
"Please review",
|
||||
{ kind: "agent-message", agentId: "remote::sender" },
|
||||
"accepted-delivery",
|
||||
);
|
||||
const codex = fakeCodexEmitting({
|
||||
turnItems: echo
|
||||
? [
|
||||
{
|
||||
type: "user_message",
|
||||
text: String(delivery.prompt),
|
||||
clientMessageId: delivery.messageId,
|
||||
messageId: "native-echo",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
for await (const _event of manager.streamAgent(agent.id, delivery.prompt, {
|
||||
clientMessageId: delivery.messageId,
|
||||
})) {
|
||||
}
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "tool_call")).toEqual([
|
||||
expect.objectContaining({
|
||||
callId: "paseo-agent-message:accepted-delivery",
|
||||
status: "completed",
|
||||
}),
|
||||
]);
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(manager.getAgent(agent.id)?.lastUserMessageAt).toBeNull();
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("a rejected agent prompt never becomes a delivered notification", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-message-rejected-"));
|
||||
const delivery = prepareAgentMessage(
|
||||
"Please review",
|
||||
{ kind: "agent-message", agentId: "sender" },
|
||||
"rejected",
|
||||
);
|
||||
class RejectingSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
throw new Error("provider rejected delivery");
|
||||
}
|
||||
}
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig) {
|
||||
return new RejectingSession(config);
|
||||
}
|
||||
})();
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
const run = manager.streamAgent(agent.id, delivery.prompt, {
|
||||
clientMessageId: delivery.messageId,
|
||||
});
|
||||
await expect(run.next()).rejects.toThrow("provider rejected delivery");
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "tool_call")).toEqual([]);
|
||||
expect(manager.getAgent(agent.id)?.lastUserMessageAt).toBeNull();
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.each([false, true])(
|
||||
"human envelope examples remain human after echo with correlation=%s",
|
||||
async (correlated) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "human-envelope-example-"));
|
||||
const example = formatAgentMessage({
|
||||
id: "example",
|
||||
source: { kind: "agent-message", agentId: "sender" },
|
||||
text: "hello",
|
||||
});
|
||||
const delivery = prepareAgentMessage(example, undefined, "human-submission");
|
||||
const codex = fakeCodexEmitting({
|
||||
turnItems: [
|
||||
{
|
||||
type: "user_message",
|
||||
text: String(delivery.prompt),
|
||||
messageId: "provider-echo",
|
||||
...(correlated ? { clientMessageId: "human-submission" } : {}),
|
||||
},
|
||||
],
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
for await (const _event of manager.streamAgent(agent.id, delivery.prompt, {
|
||||
clientMessageId: delivery.messageId,
|
||||
})) {
|
||||
}
|
||||
expect(manager.getTimeline(agent.id)).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: example,
|
||||
clientMessageId: "human-submission",
|
||||
messageId: "human-submission",
|
||||
},
|
||||
]);
|
||||
expect(manager.getAgent(agent.id)?.lastUserMessageAt).toBeInstanceOf(Date);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -55,7 +55,6 @@ import {
|
||||
type ListImportableSessionsOptions,
|
||||
} from "./agent-sdk-types.js";
|
||||
import { buildArchivedAgentRecord, type ArchivedStoredAgentRecord } from "./agent-archive.js";
|
||||
import { toStoredAgentRecord } from "./agent-projections.js";
|
||||
import type { StoredAgentRecord, AgentStorage } from "./agent-storage.js";
|
||||
import type { AgentOwner } from "./agent-owner.js";
|
||||
import {
|
||||
@@ -79,7 +78,7 @@ import {
|
||||
type PendingForegroundRun,
|
||||
} from "./agent-run-state.js";
|
||||
import { invokeRewindCapability, type RewindMode } from "./rewind/rewind.js";
|
||||
import { projectAgentMessage } from "./agent-messages/index.js";
|
||||
import { isSystemInjectedEnvelope } from "./agent-prompt.js";
|
||||
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { stripInternalPaseoMcpServer, withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
|
||||
import { resolveCreateAgentTitles } from "./create-agent-title.js";
|
||||
@@ -244,8 +243,6 @@ export type AgentSubscriber = (event: AgentManagerEvent) => void;
|
||||
export interface SubscribeOptions {
|
||||
agentId?: string;
|
||||
replayState?: boolean;
|
||||
/** Receive events for internal agents too. Off by default for global subscribers. */
|
||||
includeInternal?: boolean;
|
||||
}
|
||||
|
||||
interface HydrateTimelineOptions {
|
||||
@@ -319,7 +316,6 @@ export interface CreateAgentOptions {
|
||||
|
||||
export interface AgentManagerOptions {
|
||||
pluginLifecycle?: PluginLifecycle;
|
||||
/** An internal workspace makes every agent created inside it internal. */
|
||||
clients?: ProviderClientMap;
|
||||
providerDefinitions?: ProviderEnabledMap;
|
||||
idFactory?: () => string;
|
||||
@@ -572,7 +568,6 @@ function attachPersistenceCwd(
|
||||
interface SubscriptionRecord {
|
||||
callback: AgentSubscriber;
|
||||
agentId: string | null;
|
||||
includeInternal: boolean;
|
||||
}
|
||||
|
||||
interface SteerEventBarrier {
|
||||
@@ -657,12 +652,13 @@ function buildExplicitTimelineSeedForRegister(
|
||||
function buildImportedTimelineRows(entries: readonly ImportedTimelineEntry[]): AgentTimelineRow[] {
|
||||
const rows: AgentTimelineRow[] = [];
|
||||
for (const entry of entries) {
|
||||
const item = projectAgentMessage(entry.item);
|
||||
if (!item) continue;
|
||||
if (entry.item.type === "user_message" && isSystemInjectedEnvelope(entry.item.text)) {
|
||||
continue;
|
||||
}
|
||||
rows.push({
|
||||
seq: rows.length + 1,
|
||||
timestamp: entry.timestamp ?? new Date().toISOString(),
|
||||
item: limitAgentTimelineItemContent(item),
|
||||
item: limitAgentTimelineItemContent(entry.item),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
@@ -698,7 +694,7 @@ function getFirstUserMessageTextFromRows(rows: readonly AgentTimelineRow[]): str
|
||||
}
|
||||
|
||||
function shouldDetachFromArchivedParent(
|
||||
parent: Pick<StoredAgentRecord, "workspaceId">,
|
||||
parent: StoredAgentRecord,
|
||||
child: StoredAgentRecord,
|
||||
): boolean {
|
||||
const isCrossWorkspace =
|
||||
@@ -718,25 +714,8 @@ function detachedAgentLabelPatch(labels: Record<string, string>): AgentLabelPatc
|
||||
return patch;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long an archived internal agent stays readable by id. Storage plays this
|
||||
* role for public agents; internal agents never reach it, and a one-shot helper
|
||||
* can finish and auto-archive before its creator's `waitForFinish` arrives.
|
||||
*/
|
||||
const RETIRED_INTERNAL_AGENT_TTL_MS = 10 * 60 * 1000;
|
||||
const RETIRED_INTERNAL_AGENT_LIMIT = 500;
|
||||
|
||||
export interface RetiredInternalAgent {
|
||||
record: ArchivedStoredAgentRecord;
|
||||
lastMessage: string | null;
|
||||
}
|
||||
|
||||
export class AgentManager {
|
||||
private readonly pluginLifecycle: PluginLifecycle | undefined;
|
||||
private readonly retiredInternalAgents = new Map<
|
||||
string,
|
||||
RetiredInternalAgent & { expiresAt: number }
|
||||
>();
|
||||
private readonly clients = new Map<AgentProvider, AgentClient>();
|
||||
private readonly providerEnabled = new Map<AgentProvider, boolean>();
|
||||
private readonly providerDefinitions = new Map<AgentProvider, ProviderEnabledFlag>();
|
||||
@@ -970,7 +949,6 @@ export class AgentManager {
|
||||
const record: SubscriptionRecord = {
|
||||
callback,
|
||||
agentId: targetAgentId,
|
||||
includeInternal: options?.includeInternal === true,
|
||||
};
|
||||
this.subscribers.add(record);
|
||||
|
||||
@@ -984,9 +962,9 @@ export class AgentManager {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Global subscribers skip internal agents unless they opted in.
|
||||
// For global subscribers, skip internal agents during replay
|
||||
for (const agent of this.agents.values()) {
|
||||
if (agent.internal && !record.includeInternal) {
|
||||
if (agent.internal) {
|
||||
continue;
|
||||
}
|
||||
callback({
|
||||
@@ -1006,26 +984,12 @@ export class AgentManager {
|
||||
return this.subscribers.size;
|
||||
}
|
||||
|
||||
listAgents(options?: { includeInternal?: boolean }): ManagedAgent[] {
|
||||
listAgents(): ManagedAgent[] {
|
||||
return Array.from(this.agents.values())
|
||||
.filter((agent) => options?.includeInternal === true || !agent.internal)
|
||||
.filter((agent) => !agent.internal)
|
||||
.map((agent) => Object.assign({}, agent));
|
||||
}
|
||||
|
||||
/** Archived internal agents still readable by id; see getRetiredInternalAgent. */
|
||||
listRetiredInternalAgents(): RetiredInternalAgent[] {
|
||||
const now = Date.now();
|
||||
const retired: RetiredInternalAgent[] = [];
|
||||
for (const [agentId, entry] of this.retiredInternalAgents) {
|
||||
if (entry.expiresAt <= now) {
|
||||
this.retiredInternalAgents.delete(agentId);
|
||||
continue;
|
||||
}
|
||||
retired.push({ record: entry.record, lastMessage: entry.lastMessage });
|
||||
}
|
||||
return retired;
|
||||
}
|
||||
|
||||
async listImportableSessions(
|
||||
options?: ImportablePersistedAgentQueryOptions,
|
||||
): Promise<ManagedImportableSessionsResult> {
|
||||
@@ -1709,42 +1673,6 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The archived snapshot of an internal agent, for a while after archive.
|
||||
* Null once it has expired or was never an internal agent.
|
||||
*/
|
||||
getRetiredInternalAgent(agentId: string): RetiredInternalAgent | null {
|
||||
const entry = this.retiredInternalAgents.get(agentId);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
if (entry.expiresAt <= Date.now()) {
|
||||
this.retiredInternalAgents.delete(agentId);
|
||||
return null;
|
||||
}
|
||||
return { record: entry.record, lastMessage: entry.lastMessage };
|
||||
}
|
||||
|
||||
private retireInternalAgent(entry: RetiredInternalAgent): void {
|
||||
const now = Date.now();
|
||||
for (const [agentId, retired] of this.retiredInternalAgents) {
|
||||
if (retired.expiresAt <= now) {
|
||||
this.retiredInternalAgents.delete(agentId);
|
||||
}
|
||||
}
|
||||
while (this.retiredInternalAgents.size >= RETIRED_INTERNAL_AGENT_LIMIT) {
|
||||
const oldest = this.retiredInternalAgents.keys().next().value;
|
||||
if (oldest === undefined) {
|
||||
break;
|
||||
}
|
||||
this.retiredInternalAgents.delete(oldest);
|
||||
}
|
||||
this.retiredInternalAgents.set(entry.record.id, {
|
||||
...entry,
|
||||
expiresAt: now + RETIRED_INTERNAL_AGENT_TTL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
closeAgent(agentId: string): Promise<void> {
|
||||
const existing = this.inFlightAgentCloses.get(agentId);
|
||||
if (existing) {
|
||||
@@ -1830,23 +1758,6 @@ export class AgentManager {
|
||||
requestedArchivedAt?: string,
|
||||
): Promise<{ archivedAt: string }> {
|
||||
const agent = this.requireAgent(agentId);
|
||||
if (agent.internal) {
|
||||
// Nothing about an internal agent is on disk, and archiving must not put
|
||||
// it there. Its final snapshot is kept in memory for a while (see
|
||||
// getRetiredInternalAgent); the runtime is closed and the committed
|
||||
// timeline dropped, so `getAgent` returns null from here on.
|
||||
const archivedAt = requestedArchivedAt ?? new Date().toISOString();
|
||||
const lastMessage = await this.getLastAssistantMessage(agentId);
|
||||
const record = buildArchivedAgentRecord(
|
||||
toStoredAgentRecord(agent, { title: agent.config.title ?? null, internal: true }),
|
||||
{ archivedAt, updatedAt: archivedAt },
|
||||
);
|
||||
await this.closeAgentRuntime(agentId);
|
||||
await this.deleteAgentState(agentId);
|
||||
this.retireInternalAgent({ record, lastMessage });
|
||||
await this.cascadeArchiveChildren(record);
|
||||
return { archivedAt };
|
||||
}
|
||||
if (!this.registry) {
|
||||
throw new Error("Agent storage is not configured");
|
||||
}
|
||||
@@ -1865,7 +1776,7 @@ export class AgentManager {
|
||||
await this.syncNativeArchiveState(stored.provider, stored.persistence, "archive");
|
||||
this.discardRetainedAgentState(agentId);
|
||||
|
||||
await this.cascadeArchiveChildren(stored);
|
||||
await this.cascadeArchiveChildren(agentId);
|
||||
|
||||
return { archivedAt };
|
||||
}
|
||||
@@ -1874,15 +1785,16 @@ export class AgentManager {
|
||||
// label pointing back at the caller. Archiving the parent cascades to those
|
||||
// children so subagent fleets don't outlive their orchestrator. Detached
|
||||
// handoff agents omit this label, so they stand outside the cascade.
|
||||
private async cascadeArchiveChildren(
|
||||
parent: Pick<StoredAgentRecord, "id" | "workspaceId">,
|
||||
): Promise<void> {
|
||||
private async cascadeArchiveChildren(parentAgentId: string): Promise<void> {
|
||||
const registry = this.registry;
|
||||
if (!registry) {
|
||||
return;
|
||||
}
|
||||
const parentAgentId = parent.id;
|
||||
const records = await registry.list();
|
||||
const parent = records.find((record) => record.id === parentAgentId);
|
||||
if (!parent) {
|
||||
throw new Error(`Archived parent ${parentAgentId} not found in storage`);
|
||||
}
|
||||
for (const record of records) {
|
||||
if (record.archivedAt) {
|
||||
continue;
|
||||
@@ -1912,21 +1824,6 @@ export class AgentManager {
|
||||
}
|
||||
});
|
||||
}
|
||||
// Internal children never reach storage, so the scan above cannot see them.
|
||||
// They have no tab to keep open and no listing to detach into, so they
|
||||
// always archive with the parent.
|
||||
for (const child of Array.from(this.agents.values())) {
|
||||
if (!child.internal || getParentAgentIdFromLabels(child.labels) !== parentAgentId) {
|
||||
continue;
|
||||
}
|
||||
await this.runLifecycleMutation(child.id, async () => {
|
||||
const current = this.agents.get(child.id);
|
||||
if (!current || getParentAgentIdFromLabels(current.labels) !== parentAgentId) {
|
||||
return;
|
||||
}
|
||||
await this.archiveAgentUnlocked(current.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async markRecordArchived(
|
||||
@@ -2302,7 +2199,7 @@ export class AgentManager {
|
||||
if (!nextRecord.internal) this.dispatchStoredAgentState(nextRecord);
|
||||
|
||||
await this.fireAgentArchived(agentId);
|
||||
await this.cascadeArchiveChildren(record);
|
||||
await this.cascadeArchiveChildren(agentId);
|
||||
|
||||
return nextRecord;
|
||||
}
|
||||
@@ -2464,7 +2361,7 @@ export class AgentManager {
|
||||
return false;
|
||||
}
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId);
|
||||
this.emitState(agent);
|
||||
}
|
||||
const dispatch = (event: AgentStreamEvent): void => {
|
||||
@@ -2560,12 +2457,6 @@ export class AgentManager {
|
||||
agent.pendingReplacement = false;
|
||||
const errorMsg = error instanceof Error ? error.message : "Failed to start turn";
|
||||
pendingRun.start = { status: "failed", error: errorMsg };
|
||||
// A terminal rejection belongs after the submitted prompt even though no provider turn exists.
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
@@ -2655,7 +2546,7 @@ export class AgentManager {
|
||||
)
|
||||
: undefined;
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted", {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, {
|
||||
messageId: options.clientMessageId,
|
||||
turnId,
|
||||
providerMessageId:
|
||||
@@ -2961,7 +2852,7 @@ export class AgentManager {
|
||||
if (!clientMessageId) {
|
||||
return;
|
||||
}
|
||||
this.recordSubmittedPrompt(agent, prompt, clientMessageId, "accepted", {
|
||||
this.recordSubmittedPrompt(agent, prompt, clientMessageId, {
|
||||
messageId: clientMessageId,
|
||||
turnId: expectedTurnId,
|
||||
});
|
||||
@@ -3620,7 +3511,7 @@ export class AgentManager {
|
||||
// Legacy/imported chats need their existing history before startup rows.
|
||||
await this.primeTimelineFromLegacyProviderHistory(managed, false, startupHistory);
|
||||
} else {
|
||||
for (const entry of buildImportedTimelineRows(session.initialTimeline)) {
|
||||
for (const entry of session.initialTimeline) {
|
||||
this.recordTimeline(managed.id, entry.item, { timestamp: entry.timestamp });
|
||||
}
|
||||
}
|
||||
@@ -4127,9 +4018,10 @@ export class AgentManager {
|
||||
for await (const rawEvent of agent.session.streamHistory()) {
|
||||
const event = limitAgentStreamEventContent(rawEvent);
|
||||
if (event.type === "timeline") {
|
||||
const item = projectAgentMessage(event.item);
|
||||
if (!item) continue;
|
||||
historyEvents.push({ ...event, item });
|
||||
if (event.item.type === "user_message" && isSystemInjectedEnvelope(event.item.text)) {
|
||||
continue;
|
||||
}
|
||||
historyEvents.push(event);
|
||||
} else if (event.type === "provider_subagent") {
|
||||
providerSubagentEvents.push(event);
|
||||
}
|
||||
@@ -4194,9 +4086,10 @@ export class AgentManager {
|
||||
if (event.type !== "timeline") {
|
||||
continue;
|
||||
}
|
||||
const item = projectAgentMessage(event.item);
|
||||
if (!item) continue;
|
||||
historyEvents.push({ ...event, item });
|
||||
if (event.item.type === "user_message" && isSystemInjectedEnvelope(event.item.text)) {
|
||||
continue;
|
||||
}
|
||||
historyEvents.push(event);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error, agentId: agent.id }, "Failed to hydrate provider history");
|
||||
@@ -4528,14 +4421,12 @@ export class AgentManager {
|
||||
}): Promise<void> {
|
||||
const { agent, event, options, flags } = params;
|
||||
|
||||
const item = projectAgentMessage(event.item);
|
||||
if (!item) {
|
||||
if (event.item.type === "user_message" && isSystemInjectedEnvelope(event.item.text)) {
|
||||
flags.shouldDispatchEvent = false;
|
||||
flags.shouldNotifyWaiters = false;
|
||||
return;
|
||||
}
|
||||
|
||||
event.item = item;
|
||||
if (
|
||||
event.item.type === "user_message" &&
|
||||
event.item.clientMessageId &&
|
||||
@@ -4806,34 +4697,19 @@ export class AgentManager {
|
||||
agent: ActiveManagedAgent,
|
||||
prompt: AgentPromptInput,
|
||||
clientMessageId: string,
|
||||
outcome: "accepted" | "rejected",
|
||||
options?: { messageId?: string; providerMessageId?: string; turnId?: string },
|
||||
): void {
|
||||
const item = projectAgentMessage({
|
||||
if (this.timelineStore.getSubmittedUserMessage(agent.id, clientMessageId)) {
|
||||
return;
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
agent.lastUserMessageAt = new Date();
|
||||
const item: AgentTimelineItem = {
|
||||
type: "user_message",
|
||||
text: submittedPromptText(prompt),
|
||||
clientMessageId,
|
||||
...(options?.messageId ? { messageId: options.messageId } : {}),
|
||||
});
|
||||
if (!item) return;
|
||||
// Human attempts stay in history on rejection; delivery notifications require acceptance.
|
||||
if (outcome === "rejected" && item.type !== "user_message") return;
|
||||
this.recordSubmittedPromptItem(agent, item, options);
|
||||
}
|
||||
|
||||
private recordSubmittedPromptItem(
|
||||
agent: ActiveManagedAgent,
|
||||
item: AgentTimelineItem,
|
||||
options?: { providerMessageId?: string; turnId?: string },
|
||||
): void {
|
||||
if (
|
||||
item.type === "user_message" &&
|
||||
item.clientMessageId &&
|
||||
this.timelineStore.getSubmittedUserMessage(agent.id, item.clientMessageId)
|
||||
)
|
||||
return;
|
||||
this.touchUpdatedAt(agent);
|
||||
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
|
||||
};
|
||||
this.recordAndDispatchTimelineItem(agent.id, item, agent.provider, options?.turnId, options);
|
||||
}
|
||||
|
||||
@@ -4846,14 +4722,11 @@ export class AgentManager {
|
||||
if (!clientMessageId) return null;
|
||||
let existing = this.timelineStore.getSubmittedUserMessage(agent.id, clientMessageId);
|
||||
if (!existing) {
|
||||
this.recordSubmittedPromptItem(
|
||||
agent,
|
||||
{ ...item, messageId: clientMessageId },
|
||||
{
|
||||
...(messageId ? { providerMessageId: messageId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
},
|
||||
);
|
||||
this.recordSubmittedPrompt(agent, item.text, clientMessageId, {
|
||||
messageId: clientMessageId,
|
||||
...(messageId ? { providerMessageId: messageId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
});
|
||||
existing = this.timelineStore.getSubmittedUserMessage(agent.id, clientMessageId);
|
||||
}
|
||||
if (!existing || existing.item.type !== "user_message") return null;
|
||||
@@ -5188,12 +5061,8 @@ export class AgentManager {
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
// Global subscribers (no agentId) skip internal agents unless they opted in.
|
||||
if (
|
||||
!subscriber.agentId &&
|
||||
!subscriber.includeInternal &&
|
||||
this.eventBelongsToInternalAgent(event)
|
||||
) {
|
||||
// Skip internal agents for global subscribers (those without a specific agentId)
|
||||
if (!subscriber.agentId && this.eventBelongsToInternalAgent(event)) {
|
||||
continue;
|
||||
}
|
||||
subscriber.callback(event);
|
||||
|
||||
@@ -215,19 +215,22 @@ function createMcpRecordingAgentClients(recorder: LaunchRecorder) {
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForAgentFinish(options: { client: McpClient; agentId: string }): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const result = await options.client.callTool({
|
||||
name: "get_agent_status",
|
||||
args: { agentId: options.agentId },
|
||||
});
|
||||
return getStructuredContent(result)?.status;
|
||||
},
|
||||
{ timeout: 10000 },
|
||||
)
|
||||
.toBe("idle");
|
||||
async function assertAgentNotRunning(options: {
|
||||
client: McpClient;
|
||||
agentId: string;
|
||||
}): Promise<void> {
|
||||
const statusResult = await options.client.callTool({
|
||||
name: "get_agent_status",
|
||||
args: { agentId: options.agentId },
|
||||
});
|
||||
const payload = getStructuredContent(statusResult);
|
||||
if (!payload) {
|
||||
throw new Error("get_agent_status returned no structured payload");
|
||||
}
|
||||
const status = payload.status;
|
||||
if (status === "running" || status === "initializing") {
|
||||
throw new Error(`Agent still running after blocking create_agent (status=${status})`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("agent MCP end-to-end (offline)", () => {
|
||||
@@ -273,6 +276,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "claude/claude-test-model",
|
||||
mode: "bypassPermissions",
|
||||
initialPrompt,
|
||||
background: false,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -280,7 +284,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
agentId = typeof payload?.agentId === "string" ? payload.agentId : null;
|
||||
expect(agentId).toBeTruthy();
|
||||
|
||||
await waitForAgentFinish({ client, agentId: agentId! });
|
||||
await assertAgentNotRunning({ client, agentId: agentId! });
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
const contents = await readFile(filePath, "utf8");
|
||||
@@ -373,6 +377,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "claude/claude-test-model",
|
||||
mode: "bypassPermissions",
|
||||
initialPrompt: "reply with done and stop",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
const payload = getStructuredContent(result);
|
||||
@@ -447,6 +452,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "claude/claude-test-model",
|
||||
mode: "bypassPermissions",
|
||||
initialPrompt: "reply with done and stop",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
const payload = getStructuredContent(result);
|
||||
@@ -470,6 +476,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "claude/claude-test-model",
|
||||
mode: "bypassPermissions",
|
||||
initialPrompt: "reply with done and stop",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
const disabledPayload = getStructuredContent(disabledResult);
|
||||
@@ -534,6 +541,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "claude/claude-test-model",
|
||||
mode: "bypassPermissions",
|
||||
initialPrompt: "reply with done and stop",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
const payload = getStructuredContent(result);
|
||||
@@ -593,6 +601,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "codex/gpt-5.4-mini",
|
||||
mode: "full-access",
|
||||
initialPrompt: "Run exactly: sleep 30",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -763,6 +772,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const result = await client.callTool({
|
||||
name: "create_agent",
|
||||
@@ -772,13 +782,29 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
provider: "codex/gpt-5.4-mini",
|
||||
mode: "full-access",
|
||||
initialPrompt: "Run exactly: sleep 30",
|
||||
background: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(JSON.stringify(result)).toContain("Initial turn failed to start");
|
||||
expect(getStructuredContent(result)?.agentId).toBeUndefined();
|
||||
const payload = getStructuredContent(result);
|
||||
agentId = typeof payload?.agentId === "string" ? payload.agentId : null;
|
||||
expect(agentId).toBeTruthy();
|
||||
|
||||
await assertAgentNotRunning({ client, agentId: agentId! });
|
||||
const statusResult = await client.callTool({
|
||||
name: "get_agent_status",
|
||||
args: { agentId },
|
||||
});
|
||||
const statusPayload = getStructuredContent(statusResult);
|
||||
expect(statusPayload?.status).toBe("error");
|
||||
const snapshot = statusPayload?.snapshot;
|
||||
const lastError =
|
||||
snapshot && typeof snapshot === "object" ? Reflect.get(snapshot, "lastError") : undefined;
|
||||
expect(lastError).toContain("Initial turn failed to start");
|
||||
} finally {
|
||||
if (agentId) {
|
||||
await client.callTool({ name: "kill_agent", args: { agentId } });
|
||||
}
|
||||
await client.close();
|
||||
await daemon.stop();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
@@ -854,6 +880,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
initialPrompt: "say done and stop",
|
||||
worktreeName: "mcp-worktree-setup-test",
|
||||
baseBranch: "main",
|
||||
background: true,
|
||||
},
|
||||
}),
|
||||
timeoutMs: 2500,
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import type {
|
||||
AgentPromptContentBlock,
|
||||
AgentPromptInput,
|
||||
AgentTimelineItem,
|
||||
} from "../agent-sdk-types.js";
|
||||
|
||||
const agentIdSchema = z.string().min(1);
|
||||
const sourceSchema = z.discriminatedUnion("kind", [
|
||||
z.object({
|
||||
kind: z.literal("agent-message"),
|
||||
agentId: agentIdSchema,
|
||||
title: z.string().min(1).optional(),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("agent-notification"),
|
||||
agentId: agentIdSchema,
|
||||
title: z.string().min(1).optional(),
|
||||
event: z.enum(["finished", "errored", "permission-required", "closed"]),
|
||||
}),
|
||||
]);
|
||||
export type AgentPromptSource = z.infer<typeof sourceSchema>;
|
||||
|
||||
interface AgentMessage {
|
||||
id: string;
|
||||
source: AgentPromptSource | null;
|
||||
text: string;
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value.replace(/[&<>"']/g, (character) => {
|
||||
switch (character) {
|
||||
case "&":
|
||||
return "&";
|
||||
case "<":
|
||||
return "<";
|
||||
case ">":
|
||||
return ">";
|
||||
case '"':
|
||||
return """;
|
||||
default:
|
||||
return "'";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function unescapeXml(value: string): string | null {
|
||||
if (/[<>]|&(?!amp;|lt;|gt;|quot;|apos;)/.test(value)) return null;
|
||||
return value.replace(/&(amp|lt|gt|quot|apos);/g, (_, entity: string) => {
|
||||
switch (entity) {
|
||||
case "amp":
|
||||
return "&";
|
||||
case "lt":
|
||||
return "<";
|
||||
case "gt":
|
||||
return ">";
|
||||
case "quot":
|
||||
return '"';
|
||||
default:
|
||||
return "'";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function formatAgentMessage(message: AgentMessage): string {
|
||||
const { source } = message;
|
||||
const attributes = source
|
||||
? `kind="${source.kind}" source-agent-id="${escapeXml(source.agentId)}"`
|
||||
: 'kind="user-message"';
|
||||
const title = source?.title ? ` source-agent-title="${escapeXml(source.title)}"` : "";
|
||||
const event = source?.kind === "agent-notification" ? ` event="${source.event}"` : "";
|
||||
return `<paseo-system version="1" ${attributes} message-id="${escapeXml(message.id)}"${title}${event}>\n${escapeXml(message.text)}\n</paseo-system>`;
|
||||
}
|
||||
|
||||
export function parseAgentMessage(text: string): AgentMessage | null {
|
||||
const envelope = /^<paseo-system((?:\s+[a-z-]+="[^"<>]*")+)>\n([\s\S]*)\n<\/paseo-system>$/.exec(
|
||||
text,
|
||||
);
|
||||
if (!envelope) return null;
|
||||
const attributes = new Map<string, string>();
|
||||
for (const match of envelope[1].matchAll(/\s+([a-z-]+)="([^"<>]*)"/g)) {
|
||||
const value = unescapeXml(match[2]);
|
||||
if (value === null || attributes.has(match[1])) return null;
|
||||
attributes.set(match[1], value);
|
||||
}
|
||||
if (attributes.get("version") !== "1") return null;
|
||||
const id = attributes.get("message-id");
|
||||
const body = unescapeXml(envelope[2]);
|
||||
if (!id || body === null) return null;
|
||||
if (attributes.get("kind") === "user-message") {
|
||||
if (attributes.has("source-agent-id") || attributes.has("event")) return null;
|
||||
return { id, source: null, text: body };
|
||||
}
|
||||
const source = sourceSchema.safeParse({
|
||||
kind: attributes.get("kind"),
|
||||
agentId: attributes.get("source-agent-id"),
|
||||
event: attributes.get("event"),
|
||||
title: attributes.get("source-agent-title"),
|
||||
});
|
||||
if (!source.success) return null;
|
||||
return { id, source: source.data, text: body };
|
||||
}
|
||||
|
||||
function renderMessageText(block: AgentPromptContentBlock): string[] {
|
||||
if (block.type === "image") return [];
|
||||
if (block.type === "text") return [block.text];
|
||||
return [renderPromptAttachmentAsText(block)];
|
||||
}
|
||||
|
||||
export function prepareAgentMessage(
|
||||
prompt: AgentPromptInput,
|
||||
source?: AgentPromptSource,
|
||||
id?: string,
|
||||
): { prompt: AgentPromptInput; messageId?: string } {
|
||||
if (!source) {
|
||||
const submittedText =
|
||||
typeof prompt === "string"
|
||||
? prompt
|
||||
: prompt
|
||||
.flatMap((block) =>
|
||||
block.type === "text" && !("mimeType" in block) ? [block.text] : [],
|
||||
)
|
||||
.join("\n")
|
||||
.trim();
|
||||
// Quote reserved envelopes only when they arrived through the human send path.
|
||||
// This provenance must survive provider history, not only the accepted local row.
|
||||
if (!parseAgentMessage(submittedText) && !isSystemInjectedEnvelope(submittedText)) {
|
||||
return { prompt, messageId: id };
|
||||
}
|
||||
}
|
||||
const messageId = id ?? randomUUID();
|
||||
const text = typeof prompt === "string" ? prompt : prompt.flatMap(renderMessageText).join("\n\n");
|
||||
// Render textual attachments before wrapping, so provider replay still contains one
|
||||
// complete envelope instead of an envelope followed by provider-rendered context.
|
||||
const envelope = formatAgentMessage({ id: messageId, source: source ?? null, text });
|
||||
return {
|
||||
messageId,
|
||||
prompt:
|
||||
typeof prompt === "string"
|
||||
? envelope
|
||||
: [{ type: "text", text: envelope }, ...prompt.filter((block) => block.type === "image")],
|
||||
};
|
||||
}
|
||||
|
||||
/** The same projection owns provider echoes, acceptance, import, and replay. */
|
||||
export function projectAgentMessage(item: AgentTimelineItem): AgentTimelineItem | null {
|
||||
if (item.type !== "user_message") return item;
|
||||
const message = parseAgentMessage(item.text);
|
||||
if (!message) {
|
||||
// COMPAT(legacySystemEnvelope): added in v0.11.1; remove after 2027-04-08 once
|
||||
// legacy notification history is retired. Schedules still use this envelope.
|
||||
return isSystemInjectedEnvelope(item.text) ? null : item;
|
||||
}
|
||||
const { source } = message;
|
||||
if (!source) {
|
||||
return { ...item, text: message.text, clientMessageId: message.id };
|
||||
}
|
||||
return {
|
||||
type: "tool_call",
|
||||
callId: `paseo-agent-message:${message.id}`,
|
||||
agentMessage: {
|
||||
event: source.kind === "agent-message" ? "message" : source.event,
|
||||
sender: { id: source.agentId, ...(source.title ? { title: source.title } : {}) },
|
||||
text: message.text,
|
||||
},
|
||||
// COMPAT(agentMessageToolEnvelope): added in v0.11.1; remove after 2027-04-08
|
||||
// once clients can accept a dedicated timeline variant. Older clients still
|
||||
// parse this existing shape and can expand the delivered body.
|
||||
name: "agent_message",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", text: message.text, icon: "bot" },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a body in <paseo-system>…</paseo-system> so the receiving agent
|
||||
* recognizes the prompt as system-injected context — not a user turn.
|
||||
* Used by schedule fires; agent messages use the versioned envelope.
|
||||
*/
|
||||
export function formatSystemNotificationPrompt(reason: string): string {
|
||||
return `<paseo-system>\n${reason}\n</paseo-system>`;
|
||||
}
|
||||
|
||||
const SYSTEM_ENVELOPE_PATTERN = /^<paseo-system>\n[\s\S]*\n<\/paseo-system>$/;
|
||||
|
||||
export function isSystemInjectedEnvelope(text: string): boolean {
|
||||
return SYSTEM_ENVELOPE_PATTERN.test(text);
|
||||
}
|
||||
@@ -407,17 +407,6 @@ describe("toAgentPayload", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("carries a stored lastError onto the payload", () => {
|
||||
const record = toStoredAgentRecord(
|
||||
createManagedAgent({ provider: "codex", config: { provider: "codex" }, lastError: "boom" }),
|
||||
);
|
||||
|
||||
expect(buildStoredAgentPayload(record, ["codex"]).lastError).toBe("boom");
|
||||
expect(buildStoredAgentPayload({ ...record, lastError: null }, ["codex"])).not.toHaveProperty(
|
||||
"lastError",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits lastUsage when not available", () => {
|
||||
const agent = createManagedAgent({ lastUsage: undefined });
|
||||
const payload = toAgentPayload(agent);
|
||||
|
||||
@@ -139,7 +139,6 @@ export function toAgentPayload(
|
||||
persistence: projectPersistenceHandleForWire(agent.persistence),
|
||||
title: options?.title ?? null,
|
||||
labels: agent.labels,
|
||||
...(agent.internal ? { internal: true } : {}),
|
||||
};
|
||||
|
||||
const usage = sanitizeUsage(agent.lastUsage);
|
||||
@@ -248,9 +247,7 @@ export function buildStoredAgentPayload(
|
||||
attentionReason: record.attentionReason ?? null,
|
||||
attentionTimestamp: record.attentionTimestamp ?? null,
|
||||
archivedAt: record.archivedAt ?? null,
|
||||
...(record.internal ? { internal: true } : {}),
|
||||
labels: normalizeLabels(record.labels),
|
||||
...(typeof record.lastError === "string" ? { lastError: record.lastError } : {}),
|
||||
...(providerAvailable ? {} : { providerUnavailable: true }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
import {
|
||||
formatSystemNotificationPrompt,
|
||||
isSystemInjectedEnvelope,
|
||||
parseAgentMessage,
|
||||
formatAgentMessage,
|
||||
prepareAgentMessage,
|
||||
projectAgentMessage,
|
||||
} from "./agent-messages/index.js";
|
||||
import { expect, it, test, vi } from "vitest";
|
||||
import pino, { type Logger } from "pino";
|
||||
import { randomUUID } from "node:crypto";
|
||||
@@ -16,7 +8,12 @@ import { join } from "node:path";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { AgentStorage } from "./agent-storage.js";
|
||||
import { setupFinishNotification, waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
|
||||
import {
|
||||
formatSystemNotificationPrompt,
|
||||
isSystemInjectedEnvelope,
|
||||
setupFinishNotification,
|
||||
waitForAgentRunStartWithTimeout,
|
||||
} from "./agent-prompt.js";
|
||||
import type { AgentManagerEvent, ManagedAgent } from "./agent-manager.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
@@ -275,16 +272,11 @@ test("finish notifications tell the parent the child's last assistant message",
|
||||
scenario.startWatchingChild();
|
||||
const parentPrompt = await scenario.finishChildAndReadParentPrompt();
|
||||
|
||||
expect(parseAgentMessage(parentPrompt)).toEqual({
|
||||
id: expect.any(String),
|
||||
source: {
|
||||
kind: "agent-notification",
|
||||
agentId: "child-agent",
|
||||
title: "Child Agent",
|
||||
event: "finished",
|
||||
},
|
||||
text: "Agent child-agent (Child Agent) finished.\n\n<agent-response>\nImplemented the cleanup and all checks pass.\n</agent-response>",
|
||||
});
|
||||
expect(parentPrompt).toEqual(
|
||||
formatSystemNotificationPrompt(
|
||||
"Agent child-agent (Child Agent) finished.\n\n<agent-response>\nImplemented the cleanup and all checks pass.\n</agent-response>",
|
||||
),
|
||||
);
|
||||
expect(scenario.steerAttemptCount()).toBe(1);
|
||||
});
|
||||
|
||||
@@ -311,16 +303,9 @@ test("closing a watched child notifies the caller", async () => {
|
||||
scenario.startWatchingChild();
|
||||
const parentPrompt = await scenario.closeChildAndReadParentPrompt();
|
||||
|
||||
expect(parseAgentMessage(parentPrompt)).toEqual({
|
||||
id: expect.any(String),
|
||||
source: {
|
||||
kind: "agent-notification",
|
||||
agentId: "child-agent",
|
||||
title: "Child Agent",
|
||||
event: "closed",
|
||||
},
|
||||
text: "Agent child-agent (Child Agent) was closed.",
|
||||
});
|
||||
expect(parentPrompt).toEqual(
|
||||
formatSystemNotificationPrompt("Agent child-agent (Child Agent) was closed."),
|
||||
);
|
||||
});
|
||||
|
||||
test("finish notifications survive permission responses", async () => {
|
||||
@@ -333,9 +318,9 @@ test("finish notifications survive permission responses", async () => {
|
||||
expect(scenario.parentPrompts()).toHaveLength(1);
|
||||
});
|
||||
expect(scenario.parentPrompts()[0]).toContain("needs permission.");
|
||||
const permissionPayload = parseAgentMessage(scenario.parentPrompts()[0])!.text.match(
|
||||
/<permission-request>\n([\s\S]+?)\n<\/permission-request>/,
|
||||
)?.[1];
|
||||
const permissionPayload = scenario
|
||||
.parentPrompts()[0]
|
||||
.match(/<permission-request>\n([\s\S]+?)\n<\/permission-request>/)?.[1];
|
||||
expect(permissionPayload).toBeDefined();
|
||||
expect(JSON.parse(permissionPayload!)).toEqual({
|
||||
agentId: "child-agent",
|
||||
@@ -392,9 +377,7 @@ test("finish notifications report every concurrently pending permission", async
|
||||
await vi.waitFor(() => expect(scenario.parentPrompts()).toHaveLength(2));
|
||||
expect(
|
||||
scenario.parentPrompts().map((prompt) => {
|
||||
const payload = parseAgentMessage(prompt)!.text.match(
|
||||
/<permission-request>\n([\s\S]+?)\n<\/permission-request>/,
|
||||
)?.[1];
|
||||
const payload = prompt.match(/<permission-request>\n([\s\S]+?)\n<\/permission-request>/)?.[1];
|
||||
return JSON.parse(payload!).requestId;
|
||||
}),
|
||||
).toEqual(["permission-1", "permission-2"]);
|
||||
@@ -779,75 +762,3 @@ test("waiting for a run start still gives up at the run start budget", async ()
|
||||
await scenario.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("agent envelopes round-trip opaque sender IDs and XML-sensitive messages", () => {
|
||||
const message = {
|
||||
id: "delivery-1",
|
||||
source: {
|
||||
kind: "agent-message" as const,
|
||||
agentId: 'host::agent<&"',
|
||||
title: 'QA <messenger> & "reviewer"',
|
||||
},
|
||||
text: 'Review <changes> & "quotes"\n</paseo-system>\n<paseo-system>nested</paseo-system>',
|
||||
};
|
||||
const encoded = formatAgentMessage(message);
|
||||
expect(parseAgentMessage(encoded)).toEqual(message);
|
||||
expect(parseAgentMessage(`Example: ${encoded}`)).toBeNull();
|
||||
expect(parseAgentMessage(encoded.replace('version="1"', 'version="2"'))).toBeNull();
|
||||
expect(parseAgentMessage(encoded.replace("<", "<"))).toBeNull();
|
||||
expect(parseAgentMessage(encoded.replace('version="1"', 'version="1" version="1"'))).toBeNull();
|
||||
});
|
||||
|
||||
test("agent envelope includes rendered attachment context and preserves images", () => {
|
||||
const image = { type: "image" as const, data: "aW1hZ2U=", mimeType: "image/png" };
|
||||
const attachment = {
|
||||
type: "github_issue" as const,
|
||||
mimeType: "application/github-issue" as const,
|
||||
number: 42,
|
||||
title: "Review context",
|
||||
url: "https://example.com/issues/42",
|
||||
body: "Attached context",
|
||||
};
|
||||
const source = { kind: "agent-message" as const, agentId: "remote:sender" };
|
||||
expect(
|
||||
prepareAgentMessage(
|
||||
[{ type: "text", text: "First" }, image, attachment, { type: "text", text: "Second" }],
|
||||
source,
|
||||
"message",
|
||||
),
|
||||
).toEqual({
|
||||
messageId: "message",
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: formatAgentMessage({
|
||||
id: "message",
|
||||
source,
|
||||
text: "First\n\nGitHub Issue #42: Review context\nhttps://example.com/issues/42\n\nAttached context\n\nSecond",
|
||||
}),
|
||||
},
|
||||
image,
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("a human pasting an agent envelope stays a human message through provider replay", () => {
|
||||
const pasted = formatAgentMessage({
|
||||
id: "example",
|
||||
source: { kind: "agent-message", agentId: "sender" },
|
||||
text: "hello",
|
||||
});
|
||||
const delivery = prepareAgentMessage(pasted, undefined, "human-submission");
|
||||
expect(
|
||||
projectAgentMessage({
|
||||
type: "user_message",
|
||||
text: String(delivery.prompt),
|
||||
messageId: "provider-echo",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "user_message",
|
||||
text: pasted,
|
||||
messageId: "provider-echo",
|
||||
clientMessageId: "human-submission",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { prepareAgentMessage, type AgentPromptSource } from "./agent-messages/index.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type {
|
||||
@@ -28,8 +27,6 @@ export type AgentRunController = Pick<
|
||||
};
|
||||
|
||||
export interface StartAgentRunOptions {
|
||||
/** Called after selecting the run, before consuming its events. */
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
replaceRunning?: boolean;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
runOptions?: AgentRunOptions;
|
||||
@@ -116,7 +113,6 @@ export async function startAgentRun(
|
||||
// in-flight turn — replaceAgentRun would interrupt the running turn. The
|
||||
// intercept lives at this layer so it covers every prompt entrypoint.
|
||||
if (agentManager.tryRunOutOfBand(agentId, prompt, options?.runOptions)) {
|
||||
options?.onDispatch?.("out_of_band");
|
||||
return { disposition: "out_of_band" };
|
||||
}
|
||||
try {
|
||||
@@ -141,7 +137,6 @@ async function startAgentRunInner(
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
if (steered?.disposition === "steered") {
|
||||
options?.onDispatch?.("steered");
|
||||
return steered;
|
||||
}
|
||||
const { iterator, replaced } = steered
|
||||
@@ -156,7 +151,6 @@ async function startAgentRunInner(
|
||||
},
|
||||
"agent.session.start_stream.iterator_returned",
|
||||
);
|
||||
options?.onDispatch?.("turn_started");
|
||||
void (async () => {
|
||||
try {
|
||||
try {
|
||||
@@ -212,14 +206,27 @@ export async function unarchiveAgentState(
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a body in <paseo-system>…</paseo-system> so the receiving agent
|
||||
* recognizes the prompt as system-injected context — not a user turn.
|
||||
* Used by chat mentions, schedule fires, and notify-on-finish.
|
||||
*/
|
||||
export function formatSystemNotificationPrompt(reason: string): string {
|
||||
return `<paseo-system>\n${reason}\n</paseo-system>`;
|
||||
}
|
||||
|
||||
const SYSTEM_ENVELOPE_PATTERN = /^<paseo-system>\n[\s\S]*\n<\/paseo-system>$/;
|
||||
|
||||
export function isSystemInjectedEnvelope(text: string): boolean {
|
||||
return SYSTEM_ENVELOPE_PATTERN.test(text);
|
||||
}
|
||||
|
||||
export interface SendPromptToAgentParams {
|
||||
onDispatch?: StartAgentRunOptions["onDispatch"];
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
agentId: string;
|
||||
/** Prompt to dispatch to the provider (may include image blocks or wrapped text). */
|
||||
prompt: AgentPromptInput;
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
runOptions?: AgentRunOptions;
|
||||
@@ -237,12 +244,10 @@ export interface SendPromptToAgentParams {
|
||||
}
|
||||
|
||||
export interface StartCreatedAgentInitialPromptParams {
|
||||
agentStorage: AgentStorage;
|
||||
agentManager: AgentManager;
|
||||
agentId: string;
|
||||
snapshot?: ManagedAgent;
|
||||
prompt: AgentPromptInput | null;
|
||||
source?: AgentPromptSource;
|
||||
runOptions?: AgentRunOptions;
|
||||
logger: Logger;
|
||||
}
|
||||
@@ -287,18 +292,6 @@ export async function waitForAgentRunStartWithTimeout(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolvePromptSource(
|
||||
source: AgentPromptSource | undefined,
|
||||
manager: Pick<AgentManager, "getAgent">,
|
||||
storage: AgentStorage,
|
||||
): Promise<AgentPromptSource | undefined> {
|
||||
if (!source) return undefined;
|
||||
const title = (
|
||||
manager.getAgent(source.agentId)?.config.title ?? (await storage.get(source.agentId))?.title
|
||||
)?.trim();
|
||||
return title ? { ...source, title } : source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full send-prompt orchestration: (optional unarchive) → load → (optional
|
||||
* mode change) → start run.
|
||||
@@ -345,15 +338,12 @@ export async function sendPromptToAgent(
|
||||
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
|
||||
}
|
||||
|
||||
const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage);
|
||||
const delivery = prepareAgentMessage(params.prompt, source, params.messageId);
|
||||
const runOptions = delivery.messageId
|
||||
? { ...params.runOptions, clientMessageId: delivery.messageId }
|
||||
const runOptions = params.messageId
|
||||
? { ...params.runOptions, clientMessageId: params.messageId }
|
||||
: params.runOptions;
|
||||
|
||||
return await startAgentRun(params.agentManager, params.agentId, delivery.prompt, params.logger, {
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: true,
|
||||
onDispatch: params.onDispatch,
|
||||
activeTurnBehavior: params.activeTurnBehavior,
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
runOptions,
|
||||
@@ -372,17 +362,14 @@ export async function startCreatedAgentInitialPrompt(
|
||||
return currentSnapshot;
|
||||
}
|
||||
|
||||
const delivery = prepareAgentMessage(
|
||||
params.prompt,
|
||||
await resolvePromptSource(params.source, params.agentManager, params.agentStorage),
|
||||
params.runOptions?.clientMessageId,
|
||||
);
|
||||
const dispatchResult = await startAgentRun(
|
||||
params.agentManager,
|
||||
params.agentId,
|
||||
delivery.prompt,
|
||||
params.prompt,
|
||||
params.logger,
|
||||
{ runOptions: { ...params.runOptions, clientMessageId: delivery.messageId } },
|
||||
{
|
||||
runOptions: params.runOptions,
|
||||
},
|
||||
);
|
||||
|
||||
if (dispatchResult.disposition === "turn_started") {
|
||||
@@ -402,20 +389,11 @@ export interface SetupFinishNotificationParams {
|
||||
childAgentId: string;
|
||||
callerAgentId: string;
|
||||
requireParentOwnership?: boolean;
|
||||
/** A replacement must observe its new start, not the displaced running snapshot. */
|
||||
waitForTurnStart?: boolean;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
type FinishNotificationReason = "finished" | "errored" | "needs permission" | "was closed";
|
||||
|
||||
const finishNotificationEvents = {
|
||||
finished: "finished",
|
||||
errored: "errored",
|
||||
"needs permission": "permission-required",
|
||||
"was closed": "closed",
|
||||
} as const;
|
||||
|
||||
const FINISH_NOTIFICATION_MESSAGE_LIMIT = 4000;
|
||||
|
||||
interface FinishNotificationBodyInput {
|
||||
@@ -464,18 +442,16 @@ interface NotifySafelyOptions {
|
||||
// next finish reaches the caller once.
|
||||
const armedFinishNotifications = new WeakMap<AgentManager, Map<string, () => void>>();
|
||||
|
||||
export function setupFinishNotification(params: SetupFinishNotificationParams): () => void {
|
||||
export function setupFinishNotification(params: SetupFinishNotificationParams): void {
|
||||
const {
|
||||
agentManager,
|
||||
agentStorage,
|
||||
childAgentId,
|
||||
callerAgentId,
|
||||
requireParentOwnership = false,
|
||||
waitForTurnStart = false,
|
||||
logger,
|
||||
} = params;
|
||||
let hasSeenRunning = false;
|
||||
let hasSeenTurn = false;
|
||||
let stopped = false;
|
||||
const notifiedPermissionRequestIds = new Set<string>();
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
@@ -523,12 +499,7 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
|
||||
agentManager,
|
||||
agentStorage,
|
||||
agentId: callerAgentId,
|
||||
prompt: body,
|
||||
source: {
|
||||
kind: "agent-notification",
|
||||
agentId: childAgentId,
|
||||
event: finishNotificationEvents[reason],
|
||||
},
|
||||
prompt: formatSystemNotificationPrompt(body),
|
||||
activeTurnBehavior: "steer",
|
||||
unarchive: false,
|
||||
logger,
|
||||
@@ -548,37 +519,6 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
|
||||
});
|
||||
}
|
||||
|
||||
function observeState(agent: ManagedAgent): void {
|
||||
for (const requestId of notifiedPermissionRequestIds) {
|
||||
if (!agent.pendingPermissions.has(requestId)) {
|
||||
notifiedPermissionRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
if (agent.lifecycle === "running") {
|
||||
if (waitForTurnStart && !hasSeenTurn) return;
|
||||
hasSeenTurn = true;
|
||||
if (agent.pendingPermissions.size === 0) {
|
||||
hasSeenRunning = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Prior terminal state is not this task's outcome. A failure before turn start
|
||||
// is reported by the dispatch acknowledgement instead of a finish callback.
|
||||
if (agent.lifecycle === "error" && hasSeenTurn) {
|
||||
notifySafely("errored");
|
||||
return;
|
||||
}
|
||||
if (agent.lifecycle === "idle" && hasSeenRunning) {
|
||||
notifySafely("finished");
|
||||
return;
|
||||
}
|
||||
if (agent.lifecycle === "closed") {
|
||||
notifySafely("was closed");
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
unsubscribe = agentManager.subscribe(
|
||||
(event) => {
|
||||
if (stopped) {
|
||||
@@ -586,7 +526,29 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
|
||||
}
|
||||
|
||||
if (event.type === "agent_state") {
|
||||
observeState(event.agent);
|
||||
for (const requestId of notifiedPermissionRequestIds) {
|
||||
if (!event.agent.pendingPermissions.has(requestId)) {
|
||||
notifiedPermissionRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
if (event.agent.lifecycle === "running") {
|
||||
if (event.agent.pendingPermissions.size === 0) {
|
||||
hasSeenRunning = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.agent.lifecycle === "error") {
|
||||
notifySafely("errored");
|
||||
return;
|
||||
}
|
||||
if (event.agent.lifecycle === "idle" && hasSeenRunning) {
|
||||
notifySafely("finished");
|
||||
return;
|
||||
}
|
||||
if (event.agent.lifecycle === "closed") {
|
||||
notifySafely("was closed");
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -594,12 +556,6 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.event.type === "turn_started") {
|
||||
hasSeenTurn = true;
|
||||
hasSeenRunning = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.event.type === "permission_requested") {
|
||||
// A permission pause is an intermediate checkpoint. Forget the run
|
||||
// observed before it so an idle state during follow-up startup cannot
|
||||
@@ -634,11 +590,11 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
|
||||
const childSnapshot = agentManager.getAgent(childAgentId);
|
||||
if (!childSnapshot || childSnapshot.lifecycle === "closed") {
|
||||
stop();
|
||||
return stop;
|
||||
return;
|
||||
}
|
||||
if (childSnapshot.lifecycle === "running" && !waitForTurnStart) {
|
||||
hasSeenTurn = true;
|
||||
if (childSnapshot.lifecycle === "running") {
|
||||
hasSeenRunning = true;
|
||||
} else if (childSnapshot.lifecycle === "error") {
|
||||
notifySafely("errored");
|
||||
}
|
||||
return stop;
|
||||
}
|
||||
|
||||
@@ -7,11 +7,13 @@ import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-se
|
||||
import type {
|
||||
CreatePaseoWorktreeWorkflowFn,
|
||||
CreatePaseoWorktreeWorkflowResult,
|
||||
CreatePaseoWorktreeSetupContinuationInput,
|
||||
NormalizedGitOptions,
|
||||
} from "../worktree-session.js";
|
||||
import type { WorkspaceGitService } from "../workspace-git-service.js";
|
||||
import type { FirstAgentContext, SessionOutboundMessage } from "../messages.js";
|
||||
import type {
|
||||
CreateAgentWorktreeTarget,
|
||||
FirstAgentContext,
|
||||
SessionOutboundMessage,
|
||||
} from "../messages.js";
|
||||
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
|
||||
@@ -57,34 +59,18 @@ export class CreateAgentLifecycleDispatch {
|
||||
|
||||
async createWorktreeForRequest(input: {
|
||||
cwd: string;
|
||||
target: NormalizedGitOptions | null;
|
||||
target: CreateAgentWorktreeTarget | undefined;
|
||||
firstAgentContext: FirstAgentContext;
|
||||
setupContinuation?: CreatePaseoWorktreeSetupContinuationInput;
|
||||
background?: boolean;
|
||||
callerWorkspaceId?: string;
|
||||
hasLegacyGitOptions: boolean;
|
||||
}): Promise<CreatePaseoWorktreeWorkflowResult | null> {
|
||||
const target = input.target;
|
||||
if (!target?.createWorktree) return null;
|
||||
return this.dependencies.createPaseoWorktreeWorkflow(
|
||||
{
|
||||
cwd: input.cwd,
|
||||
background: input.background,
|
||||
callerWorkspaceId: input.callerWorkspaceId,
|
||||
firstAgentContext: input.firstAgentContext,
|
||||
worktreeSlug: target.worktreeSlug,
|
||||
refName: target.refName,
|
||||
action: target.action,
|
||||
checkoutSource: target.checkoutSource,
|
||||
githubPrNumber: target.githubPrNumber,
|
||||
runSetup: false,
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
worktreesRoot: this.dependencies.worktreesRoot,
|
||||
},
|
||||
{
|
||||
...(target.baseBranch ? { resolveDefaultBranch: async () => target.baseBranch! } : {}),
|
||||
setupContinuation: input.setupContinuation,
|
||||
},
|
||||
);
|
||||
if (input.target && input.hasLegacyGitOptions) {
|
||||
throw new Error("create_agent_request worktree cannot be combined with git options");
|
||||
}
|
||||
if (!input.target) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createWorktreeForTarget(input.cwd, input.target, input.firstAgentContext);
|
||||
}
|
||||
|
||||
registerAutoArchiveIfRequested(input: {
|
||||
@@ -125,6 +111,47 @@ export class CreateAgentLifecycleDispatch {
|
||||
});
|
||||
}
|
||||
|
||||
private async createWorktreeForTarget(
|
||||
cwd: string,
|
||||
target: CreateAgentWorktreeTarget,
|
||||
firstAgentContext: FirstAgentContext,
|
||||
): Promise<CreatePaseoWorktreeWorkflowResult> {
|
||||
const baseInput = {
|
||||
cwd,
|
||||
firstAgentContext,
|
||||
runSetup: false,
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
worktreesRoot: this.dependencies.worktreesRoot,
|
||||
} as const;
|
||||
|
||||
switch (target.mode) {
|
||||
case "branch-off":
|
||||
return this.dependencies.createPaseoWorktreeWorkflow(
|
||||
{
|
||||
...baseInput,
|
||||
worktreeSlug: target.newBranch,
|
||||
action: "branch-off",
|
||||
...(target.base ? { refName: target.base } : {}),
|
||||
},
|
||||
target.base ? { resolveDefaultBranch: async () => target.base! } : undefined,
|
||||
);
|
||||
case "checkout-branch":
|
||||
return this.dependencies.createPaseoWorktreeWorkflow({
|
||||
...baseInput,
|
||||
action: "checkout",
|
||||
refName: target.branch,
|
||||
});
|
||||
case "checkout-pr":
|
||||
return this.dependencies.createPaseoWorktreeWorkflow({
|
||||
...baseInput,
|
||||
action: "checkout",
|
||||
githubPrNumber: target.prNumber,
|
||||
});
|
||||
default:
|
||||
throw new Error("Unsupported create_agent_request worktree target");
|
||||
}
|
||||
}
|
||||
|
||||
private registerAutoArchiveOnTerminalState(
|
||||
agentId: string,
|
||||
target: AutoArchiveTarget,
|
||||
|
||||
@@ -11,7 +11,6 @@ import { AgentStorage } from "../agent-storage.js";
|
||||
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
|
||||
import { createAgentCommand } from "./create.js";
|
||||
import type { ManagedAgent } from "../agent-manager.js";
|
||||
import type { AgentSessionConfig } from "../agent-sdk-types.js";
|
||||
|
||||
const logger = createTestLogger();
|
||||
|
||||
@@ -212,6 +211,7 @@ test("mcp create accepts provider-only internal input and leaves model undefined
|
||||
workspaceId: "ws-create-test",
|
||||
title: "provider default",
|
||||
initialPrompt: "hello",
|
||||
background: true,
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
|
||||
@@ -329,6 +329,7 @@ test("mcp create stamps the new worktree's workspaceId, not the parent's", async
|
||||
provider: "codex/gpt-5.4",
|
||||
title: "child",
|
||||
initialPrompt: "do the thing",
|
||||
background: true,
|
||||
notifyOnFinish: false,
|
||||
callerAgentId: parent.id,
|
||||
worktree: { worktreeName: "feature", baseBranch: "main" },
|
||||
@@ -377,6 +378,7 @@ test("mcp create exposes the created worktree before dispatching the initial pro
|
||||
cwd: workdir,
|
||||
title: "worktree callback",
|
||||
initialPrompt: "Say done.",
|
||||
background: true,
|
||||
notifyOnFinish: false,
|
||||
worktree: { worktreeName: "feature", baseBranch: "main" },
|
||||
onCreated: ({ agentId, createdWorktree: callbackWorktree }) => {
|
||||
@@ -469,47 +471,3 @@ test("session create keeps an explicit title after the initial prompt settles",
|
||||
await removeRealAgentManagerWorkdir({ agentManager, storage, workdir });
|
||||
}
|
||||
});
|
||||
|
||||
test("session create with an internal config skips provider session persistence", async () => {
|
||||
const snapshot = {
|
||||
id: "agent-1",
|
||||
provider: "codex",
|
||||
cwd: "/tmp/paseo-create-test",
|
||||
runtimeInfo: null,
|
||||
} as ManagedAgent;
|
||||
const createAgent = vi.fn(async () => snapshot);
|
||||
const dependencies: Parameters<typeof createAgentCommand>[0] = {
|
||||
agentManager: {
|
||||
createAgent,
|
||||
} as unknown as Parameters<typeof createAgentCommand>[0]["agentManager"],
|
||||
agentStorage: {} as Parameters<typeof createAgentCommand>[0]["agentStorage"],
|
||||
logger: createTestLogger(),
|
||||
providerSnapshotManager: createProviderSnapshotManagerStub().manager,
|
||||
};
|
||||
const input = {
|
||||
kind: "session" as const,
|
||||
workspaceId: "ws-create-test",
|
||||
labels: {},
|
||||
provisionalTitle: null,
|
||||
firstAgentContext: { attachments: [] },
|
||||
buildSessionConfig: async (config: AgentSessionConfig) => ({ sessionConfig: config }),
|
||||
};
|
||||
|
||||
await createAgentCommand(dependencies, {
|
||||
...input,
|
||||
config: { provider: "codex", cwd: "/tmp/paseo-create-test", internal: true },
|
||||
});
|
||||
await createAgentCommand(dependencies, {
|
||||
...input,
|
||||
config: { provider: "codex", cwd: "/tmp/paseo-create-test" },
|
||||
});
|
||||
|
||||
expect(createAgent).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ provider: "codex", internal: true }),
|
||||
undefined,
|
||||
expect.objectContaining({ persistSession: false }),
|
||||
);
|
||||
expect(createAgent.mock.calls[1]?.[0]).not.toHaveProperty("internal");
|
||||
expect(createAgent.mock.calls[1]?.[2]).not.toHaveProperty("persistSession");
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { AgentPromptSource } from "../agent-messages/index.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { TerminalManager } from "../../../terminal/terminal-manager.js";
|
||||
@@ -52,7 +51,6 @@ export interface CreateAgentCommandDependencies {
|
||||
export type EnsureWorkspaceForCreate = (
|
||||
cwd: string,
|
||||
firstAgentContext?: FirstAgentContext,
|
||||
context?: { callerWorkspaceId?: string },
|
||||
) => Promise<string>;
|
||||
|
||||
export interface CreateAgentFromSessionInput {
|
||||
@@ -63,7 +61,6 @@ export interface CreateAgentFromSessionInput {
|
||||
workspaceId: string;
|
||||
worktreeName?: string;
|
||||
initialPrompt?: string;
|
||||
source?: AgentPromptSource;
|
||||
clientMessageId?: string;
|
||||
outputSchema?: Record<string, unknown>;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
@@ -95,6 +92,7 @@ export interface CreateAgentFromMcpInput {
|
||||
mode?: string;
|
||||
unattended?: boolean;
|
||||
promptFailure?: CreateAgentPromptFailureMode;
|
||||
background: boolean;
|
||||
notifyOnFinish: boolean;
|
||||
internal?: boolean;
|
||||
detached?: boolean;
|
||||
@@ -127,6 +125,7 @@ export type CreateAgentPromptFailureMode = "throw" | "log" | "return-error";
|
||||
export interface CreateAgentCommandResult {
|
||||
snapshot: ManagedAgent;
|
||||
liveSnapshot: ManagedAgent;
|
||||
background: boolean;
|
||||
initialPromptStarted: boolean;
|
||||
initialPromptError: unknown | null;
|
||||
createdWorktree?: CreatePaseoWorktreeWorkflowResult;
|
||||
@@ -165,9 +164,9 @@ interface ResolvedCreateAgent {
|
||||
config: AgentSessionConfig;
|
||||
createOptions: CreateAgentOptions;
|
||||
prompt?: AgentPromptInput;
|
||||
source?: AgentPromptSource;
|
||||
runOptions?: AgentRunOptions;
|
||||
setupContinuation?: AgentWorktreeSetupContinuation;
|
||||
background: boolean;
|
||||
promptFailure: CreateAgentPromptFailureMode;
|
||||
promptLogger?: Logger;
|
||||
createdWorktree?: CreatePaseoWorktreeWorkflowResult;
|
||||
@@ -188,6 +187,10 @@ export async function createAgentCommand(
|
||||
resolved.createOptions,
|
||||
);
|
||||
|
||||
resolved.setupContinuation?.startAfterAgentCreate({
|
||||
agentId: snapshot.id,
|
||||
});
|
||||
|
||||
if (input.kind === "session") await input.onAgentReady?.(snapshot);
|
||||
|
||||
let liveSnapshot = snapshot;
|
||||
@@ -196,37 +199,28 @@ export async function createAgentCommand(
|
||||
if (input.kind === "mcp") {
|
||||
input.onCreated?.({ agentId: snapshot.id, createdWorktree: resolved.createdWorktree ?? null });
|
||||
}
|
||||
const stopNotification =
|
||||
input.kind === "mcp" &&
|
||||
input.notifyOnFinish &&
|
||||
input.callerAgentId &&
|
||||
(resolved.prompt !== undefined || resolved.setupContinuation !== undefined)
|
||||
? setupFinishNotification({
|
||||
agentManager: dependencies.agentManager,
|
||||
agentStorage: dependencies.agentStorage,
|
||||
childAgentId: snapshot.id,
|
||||
callerAgentId: input.callerAgentId,
|
||||
requireParentOwnership: true,
|
||||
logger: dependencies.logger,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
resolved.setupContinuation?.startAfterAgentCreate({
|
||||
agentId: snapshot.id,
|
||||
});
|
||||
if (resolved.prompt !== undefined) {
|
||||
const sendResult = await sendInitialPrompt(dependencies, resolved, snapshot).catch((error) => {
|
||||
stopNotification?.();
|
||||
throw error;
|
||||
});
|
||||
const sendResult = await sendInitialPrompt(dependencies, resolved, snapshot);
|
||||
initialPromptStarted = sendResult.started;
|
||||
liveSnapshot = sendResult.liveSnapshot;
|
||||
initialPromptError = sendResult.error ?? null;
|
||||
}
|
||||
|
||||
if (input.kind === "mcp" && input.notifyOnFinish && input.callerAgentId && initialPromptStarted) {
|
||||
setupFinishNotification({
|
||||
agentManager: dependencies.agentManager,
|
||||
agentStorage: dependencies.agentStorage,
|
||||
childAgentId: snapshot.id,
|
||||
callerAgentId: input.callerAgentId,
|
||||
requireParentOwnership: true,
|
||||
logger: dependencies.logger,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
snapshot,
|
||||
liveSnapshot,
|
||||
background: resolved.background,
|
||||
initialPromptStarted,
|
||||
initialPromptError,
|
||||
...(resolved.createdWorktree ? { createdWorktree: resolved.createdWorktree } : {}),
|
||||
@@ -293,20 +287,16 @@ async function resolveSessionCreateAgent(
|
||||
initialPrompt: trimmedPrompt,
|
||||
env: input.env,
|
||||
initialTitle: input.provisionalTitle,
|
||||
// Paseo never persists an internal agent, so nothing could resume its
|
||||
// provider session either. Same as the daemon's own ephemeral helpers.
|
||||
...(sessionConfig.internal ? { persistSession: false } : {}),
|
||||
// A legacy git/worktreeName worktree creates a fresh workspace, so the
|
||||
// agent belongs to that workspace, not the source one. createdWorkspaceId
|
||||
// is the freshly created worktree's workspace.
|
||||
workspaceId: requireResolvedWorkspaceId(workspaceId),
|
||||
},
|
||||
prompt: hasPromptContent ? prompt : undefined,
|
||||
source: input.source,
|
||||
runOptions,
|
||||
setupContinuation,
|
||||
// Registration commits creation. First-turn failures belong to the created agent.
|
||||
promptFailure: "return-error",
|
||||
background: true,
|
||||
promptFailure: "throw",
|
||||
promptLogger: dependencies.logger.child({
|
||||
clientMessageId: resolveClientMessageId(input.clientMessageId),
|
||||
}),
|
||||
@@ -329,7 +319,6 @@ async function resolveMcpCreateAgent(
|
||||
cwd,
|
||||
worktree: input.worktree,
|
||||
initialPrompt: input.initialPrompt ?? "",
|
||||
callerWorkspaceId: parentAgent?.workspaceId,
|
||||
});
|
||||
if (createdWorktree) input.onWorktreeCreated?.(createdWorktree);
|
||||
|
||||
@@ -344,12 +333,7 @@ async function resolveMcpCreateAgent(
|
||||
resolveWorkspace: async (workspaceId) => ({ workspaceId, cwd: resolvedCwd }),
|
||||
createWorkspace: async () => ({
|
||||
workspaceId: requireResolvedWorkspaceId(
|
||||
await ensureWorkspaceForMcpCreate(
|
||||
dependencies,
|
||||
resolvedCwd,
|
||||
input.initialPrompt ?? "",
|
||||
parentAgent?.workspaceId,
|
||||
),
|
||||
await ensureWorkspaceForMcpCreate(dependencies, resolvedCwd, input.initialPrompt ?? ""),
|
||||
),
|
||||
cwd: resolvedCwd,
|
||||
}),
|
||||
@@ -380,11 +364,9 @@ async function resolveMcpCreateAgent(
|
||||
env: input.env,
|
||||
},
|
||||
prompt: trimmedPrompt ? trimmedPrompt : undefined,
|
||||
source: input.callerAgentId
|
||||
? { kind: "agent-message", agentId: input.callerAgentId }
|
||||
: undefined,
|
||||
setupContinuation,
|
||||
createdWorktree,
|
||||
background: input.background,
|
||||
promptFailure: input.promptFailure ?? "log",
|
||||
};
|
||||
}
|
||||
@@ -459,16 +441,11 @@ async function ensureWorkspaceForMcpCreate(
|
||||
dependencies: CreateAgentCommandDependencies,
|
||||
cwd: string,
|
||||
initialPrompt: string,
|
||||
callerWorkspaceId?: string,
|
||||
): Promise<string | undefined> {
|
||||
if (!dependencies.ensureWorkspaceForCreate) {
|
||||
return undefined;
|
||||
}
|
||||
return dependencies.ensureWorkspaceForCreate(
|
||||
cwd,
|
||||
{ prompt: initialPrompt },
|
||||
{ callerWorkspaceId },
|
||||
);
|
||||
return dependencies.ensureWorkspaceForCreate(cwd, { prompt: initialPrompt });
|
||||
}
|
||||
|
||||
async function sendInitialPrompt(
|
||||
@@ -482,12 +459,10 @@ async function sendInitialPrompt(
|
||||
return { started: false, liveSnapshot: snapshot };
|
||||
}
|
||||
const liveSnapshot = await startCreatedAgentInitialPrompt({
|
||||
agentStorage: dependencies.agentStorage,
|
||||
agentManager: dependencies.agentManager,
|
||||
agentId: snapshot.id,
|
||||
snapshot,
|
||||
prompt,
|
||||
source: resolved.source,
|
||||
runOptions: resolved.runOptions,
|
||||
logger: resolved.promptLogger ?? dependencies.logger,
|
||||
});
|
||||
@@ -497,11 +472,7 @@ async function sendInitialPrompt(
|
||||
throw error;
|
||||
}
|
||||
if (resolved.promptFailure === "return-error") {
|
||||
return {
|
||||
started: false,
|
||||
liveSnapshot: dependencies.agentManager.getAgent(snapshot.id) ?? snapshot,
|
||||
error,
|
||||
};
|
||||
return { started: false, liveSnapshot: snapshot, error };
|
||||
}
|
||||
dependencies.logger.error({ err: error, agentId: snapshot.id }, "Failed to run initial prompt");
|
||||
return { started: false, liveSnapshot: snapshot };
|
||||
@@ -539,7 +510,6 @@ async function resolveMcpCwd(params: {
|
||||
dependencies: CreateAgentCommandDependencies;
|
||||
cwd: string;
|
||||
initialPrompt: string;
|
||||
callerWorkspaceId?: string;
|
||||
worktree: CreateAgentFromMcpInput["worktree"];
|
||||
}): Promise<{
|
||||
resolvedCwd: string;
|
||||
@@ -570,7 +540,6 @@ async function resolveMcpCwd(params: {
|
||||
const createdWorktree = await createMcpWorktree({
|
||||
input: {
|
||||
cwd: params.cwd,
|
||||
callerWorkspaceId: params.callerWorkspaceId,
|
||||
worktreeSlug: worktree.worktreeName,
|
||||
branchName: worktree.branchName,
|
||||
refName: worktree.refName,
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { AgentSnapshotPayload } from "../messages.js";
|
||||
import type { WorkspaceRegistry } from "../workspace-registry.js";
|
||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||
import type { AgentStorage, StoredAgentRecord } from "./agent-storage.js";
|
||||
|
||||
/** Public agent discovery owns workspace visibility for live and durable records. */
|
||||
export class AgentDirectory {
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
manager: AgentManager;
|
||||
storage: AgentStorage;
|
||||
workspaces: Pick<WorkspaceRegistry, "get" | "list">;
|
||||
projectLive(agent: ManagedAgent): Promise<AgentSnapshotPayload>;
|
||||
projectStored(record: StoredAgentRecord): AgentSnapshotPayload;
|
||||
isProviderVisible(provider: string): boolean;
|
||||
isStoredProviderAvailable(record: StoredAgentRecord): boolean;
|
||||
},
|
||||
) {}
|
||||
|
||||
async includes(
|
||||
agent: Pick<AgentSnapshotPayload, "workspaceId" | "internal">,
|
||||
includeBackground = false,
|
||||
): Promise<boolean> {
|
||||
if (agent.internal) return false;
|
||||
if (includeBackground || !agent.workspaceId) return true;
|
||||
return !(await this.deps.workspaces.get(agent.workspaceId))?.background;
|
||||
}
|
||||
|
||||
async list(filter?: {
|
||||
labels?: Record<string, string>;
|
||||
includeArchived?: boolean;
|
||||
includeBackground?: boolean;
|
||||
includeUnavailablePersisted?: boolean;
|
||||
}): Promise<AgentSnapshotPayload[]> {
|
||||
const live = this.deps.manager.listAgents();
|
||||
const liveIds = new Set(live.map((agent) => agent.id));
|
||||
const labels = Object.entries(filter?.labels ?? {});
|
||||
const backgroundIds = new Set(
|
||||
filter?.includeBackground
|
||||
? []
|
||||
: (await this.deps.workspaces.list())
|
||||
.filter((workspace) => workspace.background)
|
||||
.map((workspace) => workspace.workspaceId),
|
||||
);
|
||||
const matches = (agent: {
|
||||
archivedAt?: string | null;
|
||||
workspaceId?: string;
|
||||
labels?: Record<string, string>;
|
||||
}) =>
|
||||
(filter?.includeArchived || !agent.archivedAt) &&
|
||||
(filter?.includeBackground || !agent.workspaceId || !backgroundIds.has(agent.workspaceId)) &&
|
||||
labels.every(([key, value]) => agent.labels?.[key] === value);
|
||||
const stored = (await this.deps.storage.list())
|
||||
.filter((record) => !record.internal && !liveIds.has(record.id) && matches(record))
|
||||
.filter(
|
||||
(record) =>
|
||||
filter?.includeUnavailablePersisted || this.deps.isStoredProviderAvailable(record),
|
||||
)
|
||||
.map((record) => this.deps.projectStored(record));
|
||||
const active = await Promise.all(
|
||||
live.filter(matches).map((agent) => this.deps.projectLive(agent)),
|
||||
);
|
||||
return [...active, ...stored].filter((agent) => this.deps.isProviderVisible(agent.provider));
|
||||
}
|
||||
}
|
||||
@@ -219,25 +219,6 @@ describe("agent lifecycle commands", () => {
|
||||
expect(manager.archivedAgentIds).toEqual(["agent-1"]);
|
||||
});
|
||||
|
||||
test("archives a live internal agent without touching storage", async () => {
|
||||
const storage = new FakeLifecycleAgentStorage();
|
||||
const manager = new FakeLifecycleAgentManager(storage);
|
||||
manager.liveAgents.set("agent-1", { ...managedAgent("agent-1", "idle"), internal: true });
|
||||
|
||||
const result = await archiveAgentCommand(
|
||||
{ agentManager: manager, agentStorage: storage, logger },
|
||||
"agent-1",
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
agentId: "agent-1",
|
||||
archivedAt: "2026-05-10T10:00:00.000Z",
|
||||
record: null,
|
||||
});
|
||||
expect(manager.archivedAgentIds).toEqual(["agent-1"]);
|
||||
expect(storage.upserts).toEqual([]);
|
||||
});
|
||||
|
||||
test("archives a live agent when its graceful cancellation is rejected", async () => {
|
||||
const storage = new FakeLifecycleAgentStorage();
|
||||
const manager = new FakeLifecycleAgentManager(storage);
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
import type { AgentProviderNotice } from "./agent-sdk-types.js";
|
||||
|
||||
export type LifecycleAgentSnapshot = Pick<ManagedAgent, "id" | "cwd" | "lifecycle" | "internal">;
|
||||
export type LifecycleAgentSnapshot = Pick<ManagedAgent, "id" | "cwd" | "lifecycle">;
|
||||
|
||||
export interface LifecycleAgentManager {
|
||||
getAgent(agentId: string): LifecycleAgentSnapshot | null;
|
||||
@@ -112,8 +112,7 @@ export async function cancelAgentRunCommand(
|
||||
export interface ArchiveAgentResult {
|
||||
agentId: string;
|
||||
archivedAt: string;
|
||||
/** Null for an internal agent, which is closed and leaves no record behind. */
|
||||
record: StoredAgentRecord | null;
|
||||
record: StoredAgentRecord;
|
||||
}
|
||||
|
||||
export async function archiveAgentCommand(
|
||||
@@ -125,10 +124,7 @@ export async function archiveAgentCommand(
|
||||
if (liveAgent) {
|
||||
await requestAgentRunCancellation(dependencies, agentId);
|
||||
await dependencies.agentManager.clearAgentAttention(agentId).catch(() => undefined);
|
||||
const archived = await dependencies.agentManager.archiveAgent(agentId);
|
||||
if (liveAgent.internal) {
|
||||
return { agentId, archivedAt: archived.archivedAt, record: null };
|
||||
}
|
||||
await dependencies.agentManager.archiveAgent(agentId);
|
||||
record = await dependencies.agentStorage.get(agentId);
|
||||
} else {
|
||||
record = await archiveStoredAgent(dependencies, agentId);
|
||||
|
||||
@@ -215,6 +215,7 @@ async function createTopLevelAgent(args?: Partial<StructuredContent>): Promise<s
|
||||
provider: "claude/claude-test-model",
|
||||
initialPrompt: "say done and stop",
|
||||
settings: { modeId: "bypassPermissions" },
|
||||
background: true,
|
||||
...rest,
|
||||
});
|
||||
return str(payload.agentId);
|
||||
@@ -266,6 +267,28 @@ async function killTerminalIfPresent(terminalId: string | null | undefined): Pro
|
||||
}
|
||||
}
|
||||
|
||||
async function archiveWorktreeIfPresent(params: {
|
||||
cwd: string;
|
||||
worktreePath?: string | null;
|
||||
worktreeSlug?: string | null;
|
||||
}): Promise<void> {
|
||||
if (!params.worktreePath && !params.worktreeSlug) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await topLevelClient.callTool({
|
||||
name: "archive_worktree",
|
||||
args: {
|
||||
cwd: params.cwd,
|
||||
...(params.worktreePath ? { worktreePath: params.worktreePath } : {}),
|
||||
...(params.worktreeSlug ? { worktreeSlug: params.worktreeSlug } : {}),
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
tempRoot = await mkdtemp(path.join(os.tmpdir(), "mcp-parity-e2e-"));
|
||||
parentAgentCwd = await makeCwd("parent-agent-cwd");
|
||||
@@ -284,6 +307,7 @@ beforeAll(async () => {
|
||||
provider: "claude/claude-test-model",
|
||||
initialPrompt: "say done and stop",
|
||||
settings: { modeId: "bypassPermissions" },
|
||||
background: true,
|
||||
});
|
||||
parentAgentId = str(parentPayload.agentId);
|
||||
|
||||
@@ -821,107 +845,117 @@ describe("Suite D: Provider Tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Suite E: Workspace Tools", () => {
|
||||
test("background worktree creation, discovery and archive use ordinary workspace ownership", async () => {
|
||||
const created = await callToolStructured(topLevelClient, "create_workspace", {
|
||||
isolation: "worktree",
|
||||
path: worktreeRepoCwd,
|
||||
baseBranch: "main",
|
||||
branchName: `parity-background-${Date.now()}`,
|
||||
background: true,
|
||||
describe("Suite E: Worktree Tools", () => {
|
||||
test("list_worktrees on empty repo", async () => {
|
||||
const payload = await callToolStructured(topLevelClient, "list_worktrees", {
|
||||
cwd: worktreeRepoCwd,
|
||||
});
|
||||
const workspaceId = str(created.workspaceId);
|
||||
expect(payload.worktrees).toEqual([]);
|
||||
});
|
||||
|
||||
test("create_worktree and list_worktrees", async () => {
|
||||
let worktreePath: string | null = null;
|
||||
const branchName = `parity-create-${Date.now()}`;
|
||||
try {
|
||||
expect(created.background).toBe(true);
|
||||
const ordinary = await callToolStructured(topLevelClient, "list_workspaces", {});
|
||||
expect(
|
||||
recordArr(ordinary.workspaces).map((workspace) => workspace.workspaceId),
|
||||
).not.toContain(workspaceId);
|
||||
const inclusive = await callToolStructured(topLevelClient, "list_workspaces", {
|
||||
includeBackground: true,
|
||||
const created = await callToolStructured(topLevelClient, "create_worktree", {
|
||||
cwd: worktreeRepoCwd,
|
||||
target: {
|
||||
kind: "branch-off",
|
||||
worktreeSlug: branchName,
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
expect(recordArr(inclusive.workspaces)).toContainEqual(
|
||||
expect.objectContaining({ workspaceId, background: true }),
|
||||
worktreePath = str(created.worktreePath);
|
||||
|
||||
const listed = await callToolStructured(topLevelClient, "list_worktrees", {
|
||||
cwd: worktreeRepoCwd,
|
||||
});
|
||||
const worktrees = recordArr(listed.worktrees);
|
||||
expect(worktrees).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: worktreePath,
|
||||
branchName,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const child = await callToolStructured(topLevelClient, "create_agent", {
|
||||
workspaceId,
|
||||
title: "Background worker",
|
||||
provider: "claude/claude-test-model",
|
||||
initialPrompt: "Say done.",
|
||||
});
|
||||
const agentId = str(child.agentId);
|
||||
const workerClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${agentId}`,
|
||||
);
|
||||
let terminalId: string;
|
||||
try {
|
||||
const terminal = await callToolStructured(workerClient, "create_terminal", {
|
||||
name: "Background terminal",
|
||||
});
|
||||
terminalId = str(terminal.id);
|
||||
expect(terminal.cwd).toBe(created.cwd);
|
||||
} finally {
|
||||
await workerClient.close();
|
||||
}
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
expect((status.snapshot as StructuredContent).workspaceId).toBe(workspaceId);
|
||||
const archived = await callToolStructured(topLevelClient, "archive_workspace", {
|
||||
workspaceId,
|
||||
});
|
||||
expect(archived.archivedAgentIds).toContain(agentId);
|
||||
const terminals = await callToolStructured(topLevelClient, "list_terminals", { all: true });
|
||||
expect(recordArr(terminals.terminals).map((terminal) => terminal.id)).not.toContain(
|
||||
terminalId,
|
||||
);
|
||||
const remaining = await callToolStructured(topLevelClient, "list_workspaces", {
|
||||
includeBackground: true,
|
||||
});
|
||||
expect(
|
||||
recordArr(remaining.workspaces).map((workspace) => workspace.workspaceId),
|
||||
).not.toContain(workspaceId);
|
||||
} finally {
|
||||
await topLevelClient
|
||||
.callTool({ name: "archive_workspace", args: { workspaceId } })
|
||||
.catch(() => undefined);
|
||||
await archiveWorktreeIfPresent({ cwd: worktreeRepoCwd, worktreePath });
|
||||
}
|
||||
});
|
||||
|
||||
test("agent-scoped workspace creation inherits visibility and permits an explicit false override", async () => {
|
||||
const parentWorkspace = await callToolStructured(topLevelClient, "create_workspace", {
|
||||
isolation: "local",
|
||||
path: worktreeRepoCwd,
|
||||
background: true,
|
||||
});
|
||||
const parentWorkspaceId = str(parentWorkspace.workspaceId);
|
||||
let scoped: McpClient | null = null;
|
||||
const ownedWorkspaces: string[] = [parentWorkspaceId];
|
||||
test("archive_worktree removes worktree", async () => {
|
||||
let worktreePath: string | null = null;
|
||||
const branchName = `parity-archive-${Date.now()}`;
|
||||
try {
|
||||
const parent = await callToolStructured(topLevelClient, "create_agent", {
|
||||
workspaceId: parentWorkspaceId,
|
||||
title: "Background parent",
|
||||
provider: "claude/claude-test-model",
|
||||
initialPrompt: "Say done.",
|
||||
const created = await callToolStructured(topLevelClient, "create_worktree", {
|
||||
cwd: worktreeRepoCwd,
|
||||
target: {
|
||||
kind: "branch-off",
|
||||
worktreeSlug: branchName,
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${str(parent.agentId)}`,
|
||||
);
|
||||
const inherited = await callToolStructured(scoped, "create_workspace", {
|
||||
isolation: "local",
|
||||
worktreePath = str(created.worktreePath);
|
||||
|
||||
await callToolStructured(topLevelClient, "archive_worktree", {
|
||||
cwd: worktreeRepoCwd,
|
||||
worktreePath,
|
||||
});
|
||||
ownedWorkspaces.push(str(inherited.workspaceId));
|
||||
expect(inherited.background).toBe(true);
|
||||
const visible = await callToolStructured(scoped, "create_workspace", {
|
||||
isolation: "local",
|
||||
background: false,
|
||||
worktreePath = null;
|
||||
|
||||
const listed = await callToolStructured(topLevelClient, "list_worktrees", {
|
||||
cwd: worktreeRepoCwd,
|
||||
});
|
||||
ownedWorkspaces.push(str(visible.workspaceId));
|
||||
expect(visible.background).toBe(false);
|
||||
const worktrees = recordArr(listed.worktrees);
|
||||
expect(worktrees.some((worktree) => worktree.path === created.worktreePath)).toBe(false);
|
||||
} finally {
|
||||
await scoped?.close();
|
||||
for (const workspaceId of ownedWorkspaces.toReversed())
|
||||
await topLevelClient
|
||||
.callTool({ name: "archive_workspace", args: { workspaceId } })
|
||||
.catch(() => undefined);
|
||||
await archiveWorktreeIfPresent({ cwd: worktreeRepoCwd, worktreePath });
|
||||
}
|
||||
});
|
||||
|
||||
test("archive_worktree succeeds when caller cwd is inside the archived worktree", async () => {
|
||||
let worktreePath: string | null = null;
|
||||
let worktreeAgentId: string | null = null;
|
||||
let worktreeScopedClient: McpClient | null = null;
|
||||
const branchName = `parity-archive-self-cwd-${Date.now()}`;
|
||||
|
||||
try {
|
||||
const created = await callToolStructured(topLevelClient, "create_worktree", {
|
||||
cwd: worktreeRepoCwd,
|
||||
target: {
|
||||
kind: "branch-off",
|
||||
worktreeSlug: branchName,
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
worktreePath = str(created.worktreePath);
|
||||
worktreeAgentId = await createTopLevelAgent({
|
||||
cwd: worktreePath,
|
||||
title: "Worktree scoped parity agent",
|
||||
});
|
||||
worktreeScopedClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${encodeURIComponent(
|
||||
worktreeAgentId,
|
||||
)}`,
|
||||
);
|
||||
|
||||
const archived = await callToolStructured(worktreeScopedClient, "archive_worktree", {
|
||||
worktreePath,
|
||||
});
|
||||
expect(archived).toEqual({ success: true });
|
||||
worktreePath = null;
|
||||
worktreeAgentId = null;
|
||||
|
||||
const listed = await callToolStructured(topLevelClient, "list_worktrees", {
|
||||
cwd: worktreeRepoCwd,
|
||||
});
|
||||
const worktrees = recordArr(listed.worktrees);
|
||||
expect(worktrees.map((worktree) => worktree.path)).not.toContain(created.worktreePath);
|
||||
} finally {
|
||||
await worktreeScopedClient?.close();
|
||||
await archiveAgentIfPresent(worktreeAgentId);
|
||||
await archiveWorktreeIfPresent({ cwd: worktreeRepoCwd, worktreePath });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { parseAgentMessage } from "./agent-messages/index.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
@@ -11,7 +10,7 @@ import { tmpdir } from "node:os";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js";
|
||||
import { createAgentMcpServer } from "./mcp-server.js";
|
||||
import { AgentManager, type ManagedAgent } from "./agent-manager.js";
|
||||
import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
@@ -833,14 +832,6 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
};
|
||||
}
|
||||
|
||||
// Typed in-memory workspace port for catalogue tests without workspace setup.
|
||||
function createAgentMcpServer(options: Parameters<typeof createAgentMcpServerWithDependencies>[0]) {
|
||||
return createAgentMcpServerWithDependencies({
|
||||
workspaceRegistry: { get: async () => null, list: async () => [], upsert: async () => {} },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
describe("browser MCP tools", () => {
|
||||
const logger = createTestLogger();
|
||||
|
||||
@@ -1335,13 +1326,10 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Top-level agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Do work",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(ensureWorkspace).toHaveBeenCalledWith(
|
||||
existingCwd,
|
||||
{ prompt: "Do work" },
|
||||
{ callerWorkspaceId: undefined },
|
||||
);
|
||||
expect(ensureWorkspace).toHaveBeenCalledWith(existingCwd, { prompt: "Do work" });
|
||||
expect(spies.agentManager.createAgent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: existingCwd }),
|
||||
undefined,
|
||||
@@ -1349,32 +1337,6 @@ describe("create_agent MCP tool", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects public internal helpers and the old top-level execution background option", async () => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-public-helper-removal-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const agentManager = new AgentManager({
|
||||
clients: createTestAgentClients(),
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const tool = registeredTool(server, "create_agent");
|
||||
const input = { title: "Helper", provider: "codex/gpt-5.4", initialPrompt: "Summarize" };
|
||||
await expect(tool.handler({ ...input, internal: true })).rejects.toThrow(/Unrecognized key/);
|
||||
await expect(tool.handler({ ...input, background: true })).rejects.toThrow(
|
||||
/Unrecognized key/,
|
||||
);
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects partial explicit workspace shape", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const server = await createAgentMcpServer({
|
||||
@@ -1432,7 +1394,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
provider: "codex",
|
||||
currentModeId: "full-access",
|
||||
@@ -1483,6 +1444,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Existing workspace",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Do work",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(response.structuredContent.workspaceId).toBe("wks_existing");
|
||||
@@ -1519,7 +1481,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Feature test",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Do work",
|
||||
|
||||
background: true,
|
||||
settings: { features: { fast_mode: true } },
|
||||
};
|
||||
|
||||
@@ -1572,6 +1534,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Mode test",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Do work",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(response.structuredContent).toEqual(
|
||||
@@ -1897,6 +1860,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Worktree agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Do work",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(broadcasts).toHaveLength(1);
|
||||
@@ -1984,6 +1948,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Worktree agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Fix workspace creation naming",
|
||||
background: true,
|
||||
});
|
||||
|
||||
const agentCwd = z.string().parse(spies.agentManager.createAgent.mock.calls[0]?.[0].cwd);
|
||||
@@ -2064,6 +2029,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Agent title",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Build a workspace auto title flow",
|
||||
background: true,
|
||||
});
|
||||
const workspaceId = z.string().parse(createdWorkspaceIds[0]);
|
||||
await waitForWorkspaceTitle(workspaceRecords, workspaceId, "Workspace Auto Title Flow");
|
||||
@@ -2165,6 +2131,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Agent title",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Keep the manually renamed workspace title",
|
||||
background: true,
|
||||
});
|
||||
const renameWorkspaceTool = registeredTool(server, "rename_workspace");
|
||||
await renameWorkspaceTool.handler({
|
||||
@@ -2254,6 +2221,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Explicit Agent Title",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Generate the workspace title anyway",
|
||||
background: true,
|
||||
});
|
||||
const workspaceId = z.string().parse(createdWorkspaceIds[0]);
|
||||
await waitForWorkspaceTitle(workspaceRecords, workspaceId, "Generated Workspace Title");
|
||||
@@ -2360,6 +2328,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Directory agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Name a directory workspace from the prompt",
|
||||
background: true,
|
||||
});
|
||||
await waitForWorkspaceTitle(
|
||||
workspaceRecords,
|
||||
@@ -2466,6 +2435,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "Checkout agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Rename this checkout from the prompt",
|
||||
background: true,
|
||||
});
|
||||
|
||||
const agentCwd = z.string().parse(spies.agentManager.createAgent.mock.calls[0]?.[0].cwd);
|
||||
@@ -2572,6 +2542,7 @@ describe("create_agent MCP tool", () => {
|
||||
title: "PR agent",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Rename this PR branch from prompt",
|
||||
background: true,
|
||||
});
|
||||
|
||||
expect(createPaseoWorktree).toHaveBeenCalledWith(
|
||||
@@ -3083,47 +3054,6 @@ describe("create_agent MCP tool", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates an background local workspace and leaves it out of list_workspaces", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const createCalls: Array<{ cwd: string; context: { background?: boolean } | undefined }> = [];
|
||||
const backgroundWorkspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-background",
|
||||
projectId: "project-1",
|
||||
cwd: process.cwd(),
|
||||
kind: "directory",
|
||||
displayName: "helper",
|
||||
createdAt: "2026-07-17T00:00:00.000Z",
|
||||
updatedAt: "2026-07-17T00:00:00.000Z",
|
||||
background: true,
|
||||
});
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
workspaceRegistry: {
|
||||
get: vi.fn(async () => backgroundWorkspace),
|
||||
list: vi.fn(async () => [backgroundWorkspace]),
|
||||
upsert: vi.fn(async () => undefined),
|
||||
},
|
||||
createDirectoryWorkspace: async (cwd, _title, _projectId, context) => {
|
||||
createCalls.push({ cwd, context });
|
||||
return backgroundWorkspace;
|
||||
},
|
||||
logger,
|
||||
});
|
||||
|
||||
const created = await invokeToolWithParsedInput(registeredTool(server, "create_workspace"), {
|
||||
isolation: "local",
|
||||
path: process.cwd(),
|
||||
background: true,
|
||||
});
|
||||
expect(created.structuredContent.workspaceId).toBe("ws-background");
|
||||
expect(createCalls).toEqual([{ cwd: process.cwd(), context: { background: true } }]);
|
||||
|
||||
const listed = await registeredTool(server, "list_workspaces").handler({});
|
||||
expect(listed.structuredContent.workspaces).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts custom provider IDs in create_agent input validation", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const server = await createAgentMcpServer({
|
||||
@@ -3152,7 +3082,6 @@ describe("create_agent MCP tool", () => {
|
||||
await mkdir(subdir, { recursive: true });
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "voice-agent",
|
||||
config: { title: "Voice" },
|
||||
cwd: baseDir,
|
||||
workspaceId: "wks_voice",
|
||||
provider: "codex",
|
||||
@@ -3207,7 +3136,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "codex",
|
||||
@@ -3254,7 +3182,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const parentAgent = {
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "codex",
|
||||
@@ -3300,7 +3227,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "codex",
|
||||
@@ -3353,7 +3279,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "claude",
|
||||
@@ -3668,7 +3593,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const parentAgent = {
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "claude",
|
||||
@@ -3721,7 +3645,6 @@ describe("create_agent MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "claude",
|
||||
@@ -3781,7 +3704,6 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
private readonly subscribers = new Set<(event: AgentStreamEvent) => void>();
|
||||
private activeTurnId: string | null = null;
|
||||
private turnStartGate: Promise<void> | null = null;
|
||||
private nextStartError: Error | null = null;
|
||||
|
||||
constructor(
|
||||
readonly provider: AgentProvider,
|
||||
@@ -3801,37 +3723,12 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
return { sessionId: this.id, finalText: "", timeline: [] };
|
||||
}
|
||||
|
||||
rejectNextTurnStart(error: Error): void {
|
||||
this.nextStartError = error;
|
||||
}
|
||||
|
||||
tryHandleOutOfBand(prompt: AgentPromptInput) {
|
||||
const text = typeof prompt === "string" ? (parseAgentMessage(prompt)?.text ?? prompt) : null;
|
||||
return text === "/side-command" ? { run: async () => {} } : null;
|
||||
}
|
||||
|
||||
async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
|
||||
this.prompts.push(typeof prompt === "string" ? prompt : JSON.stringify(prompt));
|
||||
await this.turnStartGate;
|
||||
if (this.nextStartError) {
|
||||
const error = this.nextStartError;
|
||||
this.nextStartError = null;
|
||||
throw error;
|
||||
}
|
||||
const turnId = randomUUID();
|
||||
this.activeTurnId = turnId;
|
||||
this.pushEvent({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: typeof prompt === "string" ? prompt : JSON.stringify(prompt),
|
||||
messageId: randomUUID(),
|
||||
},
|
||||
});
|
||||
setTimeout(() => {
|
||||
if (this.activeTurnId !== turnId) return;
|
||||
this.pushEvent({ type: "turn_started", provider: this.provider, turnId });
|
||||
if (!this.holdTurns && this.activeTurnId === turnId) {
|
||||
this.finishTurn();
|
||||
@@ -3840,29 +3737,15 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
return { turnId };
|
||||
}
|
||||
|
||||
finishTurn(finalText?: string): void {
|
||||
finishTurn(): void {
|
||||
const turnId = this.activeTurnId;
|
||||
if (!turnId) {
|
||||
throw new Error("No held turn to finish");
|
||||
}
|
||||
this.activeTurnId = null;
|
||||
if (finalText)
|
||||
this.pushEvent({
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
item: { type: "assistant_message", text: finalText },
|
||||
});
|
||||
this.pushEvent({ type: "turn_completed", provider: this.provider, turnId });
|
||||
}
|
||||
|
||||
failTurn(error: string): void {
|
||||
const turnId = this.activeTurnId;
|
||||
if (!turnId) throw new Error("No held turn to fail");
|
||||
this.activeTurnId = null;
|
||||
this.pushEvent({ type: "turn_failed", provider: this.provider, error, turnId });
|
||||
}
|
||||
|
||||
subscribe(callback: (event: AgentStreamEvent) => void): () => void {
|
||||
this.subscribers.add(callback);
|
||||
return () => {
|
||||
@@ -3955,7 +3838,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const parentAgent = {
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "codex",
|
||||
@@ -3993,6 +3875,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
throw new Error("Expected caller send_agent_prompt input to parse");
|
||||
}
|
||||
expect(parsed.data).toMatchObject({
|
||||
background: true,
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
|
||||
@@ -4005,7 +3888,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("acknowledges top-level prompts without a completion wait", async () => {
|
||||
it("keeps top-level prompts blocking by default", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
spies.agentManager.getAgent.mockReturnValue({
|
||||
id: "child-agent",
|
||||
@@ -4033,20 +3916,23 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
throw new Error("Expected top-level send_agent_prompt input to parse");
|
||||
}
|
||||
expect(parsed.data).toMatchObject({
|
||||
background: false,
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
|
||||
await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).toHaveBeenCalledWith(
|
||||
"child-agent",
|
||||
expect.objectContaining({ waitForActive: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it("allows agent-scoped callers to opt out of finish notifications", async () => {
|
||||
it("does not arm a finish notification for blocking agent-scoped prompts", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const parentAgent = {
|
||||
id: "parent-agent",
|
||||
config: {},
|
||||
cwd: existingCwd,
|
||||
workspaceId: "wks_parent",
|
||||
provider: "codex",
|
||||
@@ -4078,175 +3964,17 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
agentId: "child-agent",
|
||||
prompt: "Follow up",
|
||||
notifyOnFinish: false,
|
||||
background: false,
|
||||
});
|
||||
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).toHaveBeenCalledWith(
|
||||
"child-agent",
|
||||
expect.objectContaining({ waitForActive: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ immediateFinish: false, failure: false },
|
||||
{ immediateFinish: true, failure: false },
|
||||
{ immediateFinish: false, failure: true },
|
||||
])(
|
||||
"notifies the retry outcome rather than the prior failed turn (immediate: $immediateFinish, failure: $failure)",
|
||||
async ({ immediateFinish, failure }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-retry-notification-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
const childClient = new HeldTurnAgentClient("codex", true);
|
||||
const agentManager = new AgentManager({
|
||||
clients: { claude: parentClient, codex: childClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const child = await agentManager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd, title: "Retry child" },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const tool = registeredTool(server, "send_agent_prompt");
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Old task",
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
childClient.sessions[0]!.failTurn("Old task failed");
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("error"));
|
||||
const unsubscribe = agentManager.subscribe(
|
||||
(event) => {
|
||||
if (
|
||||
immediateFinish &&
|
||||
event.type === "agent_state" &&
|
||||
event.agent.lifecycle === "running"
|
||||
) {
|
||||
childClient.sessions[0]!.finishTurn("Retry done");
|
||||
}
|
||||
},
|
||||
{ agentId: child.id, replayState: false },
|
||||
);
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Retry now",
|
||||
});
|
||||
unsubscribe();
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
disposition: "turn_started",
|
||||
});
|
||||
if (!immediateFinish) {
|
||||
expect(response.structuredContent.status).toBe("running");
|
||||
if (failure) childClient.sessions[0]!.failTurn("Retry failed");
|
||||
else childClient.sessions[0]!.finishTurn("Retry done");
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
expect(parentClient.sessions[0]!.prompts[0]).toContain(
|
||||
`Agent ${child.id} (Retry child) ${failure ? "errored" : "finished"}.`,
|
||||
);
|
||||
expect(parentClient.sessions[0]!.prompts[0]).not.toContain("Old task failed");
|
||||
});
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(parent.id)?.lifecycle).toBe("idle"));
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["out_of_band", "startup_failure"] as const)(
|
||||
"preserves %s dispatch notification semantics",
|
||||
async (scenario) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-dispatch-notification-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
const childClient = new HeldTurnAgentClient("codex", true);
|
||||
const agentManager = new AgentManager({
|
||||
clients: { claude: parentClient, codex: childClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const child = await agentManager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const tool = registeredTool(server, "send_agent_prompt");
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Ongoing task",
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
if (scenario === "out_of_band") {
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
disposition: "out_of_band",
|
||||
status: "running",
|
||||
});
|
||||
expect(childClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
expect(parseAgentMessage(childClient.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-message", agentId: parent.id },
|
||||
text: "Ongoing task",
|
||||
});
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
|
||||
childClient.sessions[0]!.finishTurn("Ongoing task done");
|
||||
await vi.waitFor(() => {
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
expect(parentClient.sessions[0]!.prompts[0]).toContain("finished.");
|
||||
});
|
||||
} else {
|
||||
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
|
||||
await expect(
|
||||
invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }),
|
||||
).rejects.toThrow("Requested turn could not start");
|
||||
// A later real turn must not inherit a subscription from the rejected dispatch.
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Recovery",
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
childClient.sessions[0]!.finishTurn("Recovered");
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle"));
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
|
||||
}
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("acknowledges a pending agent-scoped turn and notifies its completion", async () => {
|
||||
it("notifies the caller when a blocking agent-scoped prompt outlasts the wait", async () => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-blocking-send-timeout-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
@@ -4277,19 +4005,24 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
});
|
||||
const tool = registeredTool(server, "send_agent_prompt");
|
||||
|
||||
vi.useFakeTimers();
|
||||
const pending = invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Follow up",
|
||||
background: false,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(31_000);
|
||||
const response = await pending;
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
status: "running",
|
||||
guidance:
|
||||
"You will get notified when the prompted agent finishes, errors, or needs permission. Do not poll for status; continue with other work until the notification arrives.",
|
||||
});
|
||||
expect(response.structuredContent).not.toHaveProperty("lastMessage");
|
||||
expect(response.structuredContent.lastMessage).toContain("timed out after 30s");
|
||||
|
||||
childClient.sessions[0]!.finishTurn();
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
vi.useRealTimers();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const parentPrompts = parentClient.sessions[0]!.prompts;
|
||||
@@ -4348,7 +4081,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const childSession = childClient.sessions[0]!;
|
||||
await vi.waitFor(() => expect(childSession.prompts).toHaveLength(2));
|
||||
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
|
||||
childSession.finishTurn();
|
||||
|
||||
function finishNotifications() {
|
||||
@@ -4401,12 +4133,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentId: child.id,
|
||||
prompt: "Follow up",
|
||||
});
|
||||
await vi.waitFor(() => expect(childSession.prompts).toHaveLength(1));
|
||||
expect(parseAgentMessage(childSession.prompts[0])).toEqual({
|
||||
id: expect.any(String),
|
||||
source: { kind: "agent-message", agentId: parent.id },
|
||||
text: "Follow up",
|
||||
});
|
||||
await vi.waitFor(() => expect(childSession.prompts).toEqual(["Follow up"]));
|
||||
acknowledgeTurnStart();
|
||||
const response = await pending;
|
||||
|
||||
@@ -4478,11 +4205,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
},
|
||||
);
|
||||
unsubscribe();
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
disposition: "turn_started",
|
||||
});
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle"));
|
||||
expect(response.structuredContent).toMatchObject({ success: true, status: "idle" });
|
||||
await vi.waitFor(() => {
|
||||
const parentPrompts = parentClient.sessions[0]!.prompts;
|
||||
expect(parentPrompts).toHaveLength(1);
|
||||
|
||||
@@ -426,14 +426,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
try {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
discoverModels: async () => [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
],
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
resolveVersion: async () => "2.1.219",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: emptyConfigDir } },
|
||||
@@ -446,7 +438,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
|
||||
expect(models.map((m) => m.id)).toEqual([
|
||||
"claude-opus-5",
|
||||
"claude-mythos-5-1",
|
||||
"claude-fable-5-1",
|
||||
"claude-fable-5",
|
||||
"claude-fable-5[1m]",
|
||||
@@ -481,14 +472,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
try {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
discoverModels: async () => [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
],
|
||||
resolveVersion: async () => {
|
||||
throw new Error("unrecognized version output");
|
||||
},
|
||||
@@ -512,14 +495,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
try {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
discoverModels: async () => [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
],
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
resolveVersion: async () => "2.1.293",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: emptyConfigDir } },
|
||||
@@ -534,14 +509,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
};
|
||||
|
||||
expect(getThinkingIds("claude-opus-5")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-mythos-5-1")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"ultracode",
|
||||
]);
|
||||
expect(getThinkingIds("claude-fable-5-1")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-fable-5")).toContain("ultracode");
|
||||
expect(getThinkingIds("claude-opus-4-8[1m]")).toContain("ultracode");
|
||||
@@ -1265,7 +1232,6 @@ describe("ClaudeAgentSession features", () => {
|
||||
|
||||
test.each([
|
||||
["supported model", "claude-opus-4-8", { type: "disabled" }, undefined],
|
||||
["Mythos 5.1", "claude-mythos-5-1", { type: "adaptive", display: "summarized" }, "high"],
|
||||
["Haiku 5.5", "claude-haiku-5-5", { type: "disabled" }, undefined],
|
||||
["unsupported model", "claude-fable-5", { type: "adaptive", display: "summarized" }, "high"],
|
||||
["custom model", "openrouter/anthropic/claude-opus-4-8", undefined, undefined],
|
||||
|
||||
@@ -76,7 +76,6 @@ import {
|
||||
type ClaudeProviderOptions,
|
||||
} from "./options.js";
|
||||
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
|
||||
import { discoverClaudeModels } from "./model-discovery.js";
|
||||
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
|
||||
import {
|
||||
realClaudeRewindSdk,
|
||||
@@ -413,7 +412,6 @@ export interface ClaudeContentChunk {
|
||||
}
|
||||
|
||||
interface ClaudeAgentClientOptions {
|
||||
discoverModels?: typeof discoverClaudeModels;
|
||||
defaults?: { agents?: Record<string, AgentDefinition> };
|
||||
logger: Logger;
|
||||
runtimeSettings?: ProviderRuntimeSettings;
|
||||
@@ -1516,7 +1514,6 @@ export function readEventIdentifiers(message: SDKMessage): EventIdentifiers {
|
||||
}
|
||||
|
||||
export class ClaudeAgentClient implements AgentClient {
|
||||
private readonly discoverModels: typeof discoverClaudeModels;
|
||||
readonly provider = "claude" as const;
|
||||
readonly capabilities = CLAUDE_CAPABILITIES;
|
||||
|
||||
@@ -1529,7 +1526,6 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
private readonly rewindSdk: ClaudeRewindSdk;
|
||||
|
||||
constructor(options: ClaudeAgentClientOptions) {
|
||||
this.discoverModels = options.discoverModels ?? discoverClaudeModels;
|
||||
this.defaults = options.defaults;
|
||||
this.logger = options.logger.child({ module: "agent", provider: "claude" });
|
||||
this.runtimeSettings = options.runtimeSettings;
|
||||
@@ -1612,35 +1608,8 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
this.logger.warn({ err: error }, "Failed to resolve Claude Code version for model catalog");
|
||||
}
|
||||
const env = this.buildProviderEnv();
|
||||
let discoveredModelIds = new Set<string>();
|
||||
try {
|
||||
const advertisedModels = await runProviderRefreshActivity(context, "models", () =>
|
||||
this.discoverModels({
|
||||
resolveBinary: this.resolveBinary,
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
env,
|
||||
signal: context?.signal,
|
||||
}),
|
||||
);
|
||||
discoveredModelIds = new Set(
|
||||
advertisedModels
|
||||
.map((model) => normalizeClaudeRuntimeModelId(model.resolvedModel ?? model.value))
|
||||
.filter((id): id is string => id !== null),
|
||||
);
|
||||
} catch (error) {
|
||||
context?.signal.throwIfAborted();
|
||||
this.logger.warn(
|
||||
{ err: error },
|
||||
"Claude model discovery failed; omitting discovery-required models",
|
||||
);
|
||||
}
|
||||
const models = await runProviderRefreshActivity(context, "settings", () =>
|
||||
getClaudeModelsWithSettings(
|
||||
this.logger,
|
||||
claudeConfigDir(env),
|
||||
claudeCodeVersion,
|
||||
discoveredModelIds,
|
||||
),
|
||||
getClaudeModelsWithSettings(this.logger, claudeConfigDir(env), claudeCodeVersion),
|
||||
);
|
||||
const modeCatalog = claudeModeCatalog(env);
|
||||
return {
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import os from "node:os";
|
||||
import type { ModelInfo, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { raceProviderRefreshAbort } from "../../provider-refresh-deadline.js";
|
||||
import type { ProviderRuntimeSettings } from "../../provider-launch-config.js";
|
||||
import { terminateWithTreeKill } from "../../../../utils/tree-kill.js";
|
||||
import { claudeQuery, type ClaudeQueryInput, type ClaudeQueryContext } from "./query.js";
|
||||
|
||||
interface ClaudeModelDiscoveryOptions {
|
||||
resolveBinary: () => Promise<string>;
|
||||
runtimeSettings?: ProviderRuntimeSettings;
|
||||
env: NodeJS.ProcessEnv;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
type OpenDiscoveryQuery = (
|
||||
input: ClaudeQueryInput,
|
||||
context: ClaudeQueryContext,
|
||||
) => Pick<Query, "supportedModels" | "close">;
|
||||
|
||||
// The curated catalog survives a failed or slow probe. This process never receives
|
||||
// a prompt and must not persist a session or launch user MCP servers/hooks.
|
||||
export async function discoverClaudeModels(
|
||||
options: ClaudeModelDiscoveryOptions,
|
||||
openQuery: OpenDiscoveryQuery = claudeQuery,
|
||||
): Promise<ModelInfo[]> {
|
||||
const controller = new AbortController();
|
||||
const signal = options.signal
|
||||
? AbortSignal.any([options.signal, controller.signal])
|
||||
: controller.signal;
|
||||
const timer = setTimeout(
|
||||
() => controller.abort(new Error("Claude model discovery timed out")),
|
||||
5_000,
|
||||
);
|
||||
let endInput!: () => void;
|
||||
const ended = new Promise<void>((resolve) => {
|
||||
endInput = resolve;
|
||||
});
|
||||
const input: AsyncIterable<SDKUserMessage> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
next: async () => {
|
||||
await ended;
|
||||
return { done: true, value: undefined };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
let query: ReturnType<OpenDiscoveryQuery> | undefined;
|
||||
let child: ChildProcess | undefined;
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const binary = await raceProviderRefreshAbort(signal, options.resolveBinary());
|
||||
query = openQuery(
|
||||
{
|
||||
prompt: input,
|
||||
options: {
|
||||
pathToClaudeCodeExecutable: binary,
|
||||
cwd: os.homedir(),
|
||||
env: options.env,
|
||||
persistSession: false,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
strictMcpConfig: true,
|
||||
settingSources: ["user"],
|
||||
settings: { disableAllHooks: true },
|
||||
abortController: controller,
|
||||
},
|
||||
},
|
||||
{
|
||||
runtimeSettings: options.runtimeSettings,
|
||||
onChildProcess: (process) => {
|
||||
child = process;
|
||||
},
|
||||
},
|
||||
);
|
||||
return await raceProviderRefreshAbort(signal, query.supportedModels());
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
endInput();
|
||||
try {
|
||||
query?.close();
|
||||
} finally {
|
||||
if (child) {
|
||||
await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ interface ClaudeModelManifestEntry {
|
||||
description: string;
|
||||
defaultPriority?: number;
|
||||
minimumClaudeCodeVersion?: string;
|
||||
requiresDiscovery?: boolean;
|
||||
contextWindowMaxTokens?: number;
|
||||
effortLevels?: readonly ClaudeEffortLevel[];
|
||||
defaultThinkingOptionId?: ClaudeEffortLevel;
|
||||
@@ -58,14 +57,6 @@ export const CLAUDE_MODEL_MANIFEST = [
|
||||
supportsThinkingDisabled: true,
|
||||
supportsFastMode: true,
|
||||
},
|
||||
{
|
||||
id: "claude-mythos-5-1",
|
||||
label: "Mythos 5.1",
|
||||
requiresDiscovery: true,
|
||||
description: "Mythos 5.1 · Requires verified access",
|
||||
contextWindowMaxTokens: 1_000_000,
|
||||
effortLevels: CLAUDE_EFFORT_LEVELS.xhigh,
|
||||
},
|
||||
{
|
||||
id: "claude-fable-5-1",
|
||||
label: "Fable 5.1",
|
||||
@@ -226,16 +217,9 @@ function buildThinkingOptions(
|
||||
return options;
|
||||
}
|
||||
|
||||
export function getClaudeManifestModels(
|
||||
claudeCodeVersion?: string,
|
||||
discoveredModelIds?: ReadonlySet<string>,
|
||||
): AgentModelDefinition[] {
|
||||
export function getClaudeManifestModels(claudeCodeVersion?: string): AgentModelDefinition[] {
|
||||
const availableModels: readonly ClaudeModelManifestEntry[] = CLAUDE_MODEL_MANIFEST.filter(
|
||||
(model) =>
|
||||
isModelAvailableInClaudeCode(model, claudeCodeVersion) &&
|
||||
(discoveredModelIds === undefined ||
|
||||
!("requiresDiscovery" in model && model.requiresDiscovery) ||
|
||||
discoveredModelIds.has(model.id)),
|
||||
(model) => isModelAvailableInClaudeCode(model, claudeCodeVersion),
|
||||
);
|
||||
const defaultModel = availableModels.reduce<ClaudeModelManifestEntry | undefined>(
|
||||
(selected, candidate) =>
|
||||
@@ -375,7 +359,7 @@ export function normalizeClaudeManifestModelId(value: string | null | undefined)
|
||||
}
|
||||
|
||||
const singleSegmentMatch = trimmed.match(
|
||||
/^(?:claude[-_ ])?(mythos|fable|opus|sonnet|haiku)[-_ ]+(\d+)(?:\[1m\])?(?:[-_ ]+\d{8})?(?:\[1m\])?$/i,
|
||||
/^(?:claude[-_ ])?(fable|opus|sonnet|haiku)[-_ ]+(\d+)(?:\[1m\])?(?:[-_ ]+\d{8})?(?:\[1m\])?$/i,
|
||||
);
|
||||
if (singleSegmentMatch) {
|
||||
return normalizeSingleSegmentClaudeModelId(
|
||||
@@ -386,7 +370,7 @@ export function normalizeClaudeManifestModelId(value: string | null | undefined)
|
||||
}
|
||||
|
||||
const runtimeMatch = trimmed.match(
|
||||
/^(?:claude[-_ ])?(mythos|fable|opus|sonnet|haiku)[-_ ]+(\d+)[-.](\d+)(?:\[1m\])?(?:[-_ ]+\d{8})?(?:\[1m\])?$/i,
|
||||
/^(?:claude[-_ ])?(fable|opus|sonnet|haiku)[-_ ]+(\d+)[-.](\d+)(?:\[1m\])?(?:[-_ ]+\d{8})?(?:\[1m\])?$/i,
|
||||
);
|
||||
if (!runtimeMatch) {
|
||||
return null;
|
||||
@@ -419,7 +403,7 @@ export function normalizeClaudeRuntimeModelId(value: string | null | undefined):
|
||||
}
|
||||
|
||||
const runtimeMatch = trimmed.match(
|
||||
/claude[-_ ](mythos|fable|opus|sonnet|haiku)[-_ ]+(\d+)[-.](\d+)(\[1m\])?/i,
|
||||
/claude[-_ ](fable|opus|sonnet|haiku)[-_ ]+(\d+)[-.](\d+)(\[1m\])?/i,
|
||||
);
|
||||
if (runtimeMatch) {
|
||||
const normalizedModelId = normalizeMajorMinorClaudeModelId(
|
||||
@@ -434,7 +418,7 @@ export function normalizeClaudeRuntimeModelId(value: string | null | undefined):
|
||||
}
|
||||
|
||||
const singleSegmentMatch = trimmed.match(
|
||||
/claude[-_ ](mythos|fable|opus|sonnet|haiku)[-_ ]+(\d+)(\[1m\])?/i,
|
||||
/claude[-_ ](fable|opus|sonnet|haiku)[-_ ]+(\d+)(\[1m\])?/i,
|
||||
);
|
||||
if (!singleSegmentMatch) {
|
||||
return null;
|
||||
|
||||
@@ -13,8 +13,6 @@ import {
|
||||
parseClaudeCodeVersion,
|
||||
resolveClaudeDisabledThinkingForModel,
|
||||
} from "./model-manifest.js";
|
||||
import { discoverClaudeModels } from "./model-discovery.js";
|
||||
import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { findClaudeModel, getClaudeModels, normalizeClaudeRuntimeModelId } from "./models.js";
|
||||
|
||||
const createdClaudeConfigDirs: string[] = [];
|
||||
@@ -45,14 +43,6 @@ function createCatalogClient(claudeCodeVersion = "2.1.293"): ClaudeAgentClient {
|
||||
return new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => claudeCodeVersion,
|
||||
discoverModels: async () => [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -62,7 +52,6 @@ describe("getClaudeModels", () => {
|
||||
expect(models.map((m) => m.id)).toEqual([
|
||||
"claude-opus-5-5",
|
||||
"claude-opus-5",
|
||||
"claude-mythos-5-1",
|
||||
"claude-fable-5-1",
|
||||
"claude-fable-5",
|
||||
"claude-fable-5[1m]",
|
||||
@@ -98,7 +87,6 @@ describe("getClaudeModels", () => {
|
||||
new Map([
|
||||
["claude-opus-5-5", 1_000_000],
|
||||
["claude-opus-5", 1_000_000],
|
||||
["claude-mythos-5-1", 1_000_000],
|
||||
["claude-fable-5-1", 1_000_000],
|
||||
["claude-fable-5", 1_000_000],
|
||||
["claude-fable-5[1m]", 1_000_000],
|
||||
@@ -233,118 +221,6 @@ describe("getClaudeModels", () => {
|
||||
});
|
||||
|
||||
describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
it.each([
|
||||
{ value: "mythos", resolvedModel: "claude-mythos-5-1", expected: true },
|
||||
{ value: "claude-mythos-5-1", expected: true },
|
||||
{ value: "claude-mythos-5-1[1m]", expected: true },
|
||||
{ value: "global.anthropic.claude-mythos-5-1", expected: true },
|
||||
{ value: "mythos", expected: false },
|
||||
{ value: "mythos", resolvedModel: "claude-mythos-5-2", expected: false },
|
||||
{ value: "claude-mythos-5-1", resolvedModel: "claude-fable-5-1", expected: false },
|
||||
])(
|
||||
"uses advertised identity $value / $resolvedModel to gate Mythos",
|
||||
async ({ value, resolvedModel, expected }) => {
|
||||
const configDir = await createClaudeConfigDir({});
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => "2.1.293",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: configDir } },
|
||||
discoverModels: async () => [
|
||||
{ value, resolvedModel, displayName: "Untrusted label", description: "" },
|
||||
],
|
||||
});
|
||||
const { models } = await client.fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: configDir,
|
||||
force: false,
|
||||
});
|
||||
expect(models.find((model) => model.id === "claude-mythos-5-1")).toEqual(
|
||||
expected ? findClaudeModel("claude-mythos-5-1") : undefined,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the curated catalog and explicitly configured models after discovery failure", async () => {
|
||||
const configDir = await createClaudeConfigDir({ model: "claude-mythos-5-1" });
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => "2.1.293",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: configDir } },
|
||||
discoverModels: async () => {
|
||||
throw new Error("discovery unavailable");
|
||||
},
|
||||
});
|
||||
const { models } = await client.fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: configDir,
|
||||
force: false,
|
||||
});
|
||||
expect(models.filter((model) => model.id !== "claude-mythos-5-1")).toEqual(
|
||||
getClaudeModels("2.1.293").filter((model) => model.id !== "claude-mythos-5-1"),
|
||||
);
|
||||
expect(models.find((model) => model.id === "claude-mythos-5-1")).toEqual({
|
||||
...findClaudeModel("claude-mythos-5-1"),
|
||||
label: "claude-mythos-5-1",
|
||||
description: "From Claude settings.json model",
|
||||
});
|
||||
});
|
||||
|
||||
it("omits unconfirmed Mythos after a failed probe and retries on refresh", async () => {
|
||||
const configDir = await createClaudeConfigDir({});
|
||||
let fail = true;
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => "2.1.293",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: configDir } },
|
||||
discoverModels: async () => {
|
||||
if (fail) throw new Error("discovery unavailable");
|
||||
return [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
const options = { scope: "workspace" as const, cwd: configDir, force: true };
|
||||
expect(
|
||||
(await client.fetchCatalog(options)).models.some((model) => model.id === "claude-mythos-5-1"),
|
||||
).toBe(false);
|
||||
fail = false;
|
||||
expect(
|
||||
(await client.fetchCatalog(options)).models.find((model) => model.id === "claude-mythos-5-1"),
|
||||
).toEqual(findClaudeModel("claude-mythos-5-1"));
|
||||
});
|
||||
|
||||
it("keeps the curated catalog when discovery does not advertise Mythos", async () => {
|
||||
const configDir = await createClaudeConfigDir({});
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => "2.1.293",
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: configDir } },
|
||||
discoverModels: async () => [
|
||||
{
|
||||
value: "opus",
|
||||
resolvedModel: "claude-opus-5-5",
|
||||
displayName: "Opus",
|
||||
description: "Latest",
|
||||
},
|
||||
],
|
||||
});
|
||||
const { models } = await client.fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: configDir,
|
||||
force: false,
|
||||
});
|
||||
expect(models.map((model) => model.id)).toEqual(
|
||||
getClaudeModels("2.1.293")
|
||||
.filter((model) => model.id !== "claude-mythos-5-1")
|
||||
.map((model) => model.id),
|
||||
);
|
||||
});
|
||||
|
||||
it("appends concrete models from Claude settings.json", async () => {
|
||||
const configDir = await createClaudeConfigDir({
|
||||
model: "us.anthropic.claude-opus-4-7[1m]",
|
||||
@@ -422,7 +298,6 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveVersion: async () => "2.1.280",
|
||||
discoverModels: async () => [],
|
||||
runtimeSettings: { env: { CLAUDE_CONFIG_DIR: providerConfigDir } },
|
||||
});
|
||||
|
||||
@@ -849,124 +724,3 @@ describe("claudeManifestModelSupportsFastMode", () => {
|
||||
expect(claudeManifestModelSupportsFastMode("claude-fable-5-1")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Claude Mythos 5.1 catalog", () => {
|
||||
it("offers one 1M model with high default effort and always-on thinking", () => {
|
||||
const models = getClaudeModels().filter((model) => model.id.startsWith("claude-mythos"));
|
||||
expect(models).toHaveLength(1);
|
||||
expect(models[0]).toMatchObject({
|
||||
id: "claude-mythos-5-1",
|
||||
label: "Mythos 5.1",
|
||||
contextWindowMaxTokens: 1_000_000,
|
||||
defaultThinkingOptionId: "high",
|
||||
});
|
||||
expect(models[0].thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
|
||||
]);
|
||||
expect(
|
||||
models[0].thinkingOptions?.filter((option) => option.isDefault).map((option) => option.id),
|
||||
).toEqual(["high"]);
|
||||
expect(resolveClaudeDisabledThinkingForModel("claude-mythos-5-1")).toEqual({
|
||||
supported: false,
|
||||
fallbackThinkingOptionId: "high",
|
||||
});
|
||||
expect(claudeManifestModelSupportsFastMode("claude-mythos-5-1")).toBe(false);
|
||||
expect(getClaudeModels().find((model) => model.isDefault)?.id).toBe("claude-opus-5-5");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"claude-mythos-5-1[1m]",
|
||||
"claude-mythos-5-1-20260901",
|
||||
"claude-mythos-5-1-20260901[1m]",
|
||||
"Mythos 5.1",
|
||||
])("resolves %s to the single catalog entry", (id) => {
|
||||
expect(findClaudeModel(id)?.id).toBe("claude-mythos-5-1");
|
||||
});
|
||||
|
||||
it.each(["anthropic/claude-mythos-5-1", "us.anthropic.claude-mythos-5-1-v1:0"])(
|
||||
"normalizes runtime identity without granting first-party capabilities: %s",
|
||||
(id) => {
|
||||
expect(normalizeClaudeRuntimeModelId(id)).toBe("claude-mythos-5-1");
|
||||
expect(normalizeClaudeManifestModelId(id)).toBeNull();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Claude model discovery process", () => {
|
||||
it("does not send a prompt or persist a session and closes after discovery", async () => {
|
||||
let closed = false;
|
||||
let promptEnded: Promise<IteratorResult<unknown>> | undefined;
|
||||
const advertised: ModelInfo[] = [
|
||||
{
|
||||
value: "mythos",
|
||||
resolvedModel: "claude-mythos-5-1",
|
||||
displayName: "Mythos",
|
||||
description: "",
|
||||
},
|
||||
];
|
||||
const models = await discoverClaudeModels(
|
||||
{ resolveBinary: async () => "/claude", env: { CLAUDE_CONFIG_DIR: "/provider-config" } },
|
||||
(input) => {
|
||||
expect(input.options).toMatchObject({
|
||||
pathToClaudeCodeExecutable: "/claude",
|
||||
env: { CLAUDE_CONFIG_DIR: "/provider-config" },
|
||||
persistSession: false,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
strictMcpConfig: true,
|
||||
settingSources: ["user"],
|
||||
settings: { disableAllHooks: true },
|
||||
});
|
||||
if (typeof input.prompt === "string") throw new Error("unexpected inference prompt");
|
||||
promptEnded = input.prompt[Symbol.asyncIterator]().next();
|
||||
return {
|
||||
supportedModels: async () => advertised,
|
||||
close: () => {
|
||||
closed = true;
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
expect(models).toEqual(advertised);
|
||||
expect(closed).toBe(true);
|
||||
await expect(promptEnded).resolves.toEqual({ done: true, value: undefined });
|
||||
});
|
||||
|
||||
it("times out and closes an unresponsive discovery process", async () => {
|
||||
let closed = false;
|
||||
await expect(
|
||||
discoverClaudeModels({ resolveBinary: async () => "/claude", env: {} }, () => ({
|
||||
supportedModels: () => new Promise(() => {}),
|
||||
close: () => {
|
||||
closed = true;
|
||||
},
|
||||
})),
|
||||
).rejects.toThrow("Claude model discovery timed out");
|
||||
expect(closed).toBe(true);
|
||||
}, 10_000);
|
||||
|
||||
it("closes a stalled probe when its refresh is canceled", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new Error("refresh canceled");
|
||||
let closed = false;
|
||||
const result = discoverClaudeModels(
|
||||
{ resolveBinary: async () => "/claude", env: {}, signal: controller.signal },
|
||||
() => ({
|
||||
supportedModels: () => {
|
||||
controller.abort(failure);
|
||||
return new Promise(() => {});
|
||||
},
|
||||
close: () => {
|
||||
closed = true;
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(result).rejects.toBe(failure);
|
||||
expect(closed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,9 +52,8 @@ export async function getClaudeModelsWithSettings(
|
||||
logger: Logger,
|
||||
configDir: string,
|
||||
claudeCodeVersion?: string,
|
||||
discoveredModelIds: ReadonlySet<string> = new Set(),
|
||||
): Promise<AgentModelDefinition[]> {
|
||||
const hardcodedModels = getClaudeManifestModels(claudeCodeVersion, discoveredModelIds);
|
||||
const hardcodedModels = getClaudeModels(claudeCodeVersion);
|
||||
const settingsModels = await readClaudeSettingsModels(logger, configDir);
|
||||
if (settingsModels.length === 0) {
|
||||
return hardcodedModels;
|
||||
@@ -71,10 +70,7 @@ export async function getClaudeModelsWithSettings(
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const manifestModel = getClaudeModels(claudeCodeVersion).find(
|
||||
(candidate) => candidate.id === model.id,
|
||||
);
|
||||
models.push({ ...manifestModel, ...model });
|
||||
models.push(model);
|
||||
}
|
||||
|
||||
return models;
|
||||
|
||||
@@ -300,82 +300,6 @@ describe("OpenCodeBridge", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("v2 plugin returns a tool image as OpenCode file content", async () => {
|
||||
const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-v2-image-"));
|
||||
temporaryDirectories.push(paseoHome);
|
||||
const png =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
const screenshot = {
|
||||
name: "browser_screenshot",
|
||||
title: "Browser screenshot",
|
||||
description: "Captures the page.",
|
||||
inputSchema: {},
|
||||
async handler() {
|
||||
return {
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot." },
|
||||
{ type: "image", data: png, mimeType: "image/png" },
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
const tools = new Map([[screenshot.name, screenshot]]);
|
||||
const catalog: PaseoToolCatalog = {
|
||||
tools,
|
||||
getTool: (name) => tools.get(name),
|
||||
executeTool: async (name, input, context) =>
|
||||
await tools.get(name)!.handler(input, context ?? {}),
|
||||
};
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
bridge.setManifestCatalog(catalog);
|
||||
await bridge.start();
|
||||
const release = bridge.bindSession({ sessionId: "session", env: {}, tools: catalog });
|
||||
try {
|
||||
const env = await bridge.decorateV2ServerEnv({});
|
||||
const plugin = z
|
||||
.object({
|
||||
plugins: z.array(
|
||||
z.object({
|
||||
package: z.string(),
|
||||
options: z.object({ baseUrl: z.string(), token: z.string() }),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.parse(JSON.parse(env.OPENCODE_CONFIG_CONTENT)).plugins[0]!;
|
||||
const pluginTools = new Map<string, V2TestTool>();
|
||||
const module: {
|
||||
default: { setup(context: V2TestPluginContext): Promise<() => Promise<void>> };
|
||||
} = await import(pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href);
|
||||
const dispose = await module.default.setup({
|
||||
options: plugin.options,
|
||||
tool: {
|
||||
transform: async (transform) => {
|
||||
transform({ add: (tool) => pluginTools.set(tool.name, tool) });
|
||||
return { dispose: async () => undefined };
|
||||
},
|
||||
},
|
||||
session: {
|
||||
context: async () => [],
|
||||
get: async () => ({ parentID: undefined }),
|
||||
hook: async () => ({ dispose: async () => undefined }),
|
||||
},
|
||||
});
|
||||
const result = await pluginTools
|
||||
.get("paseo_browser_screenshot")!
|
||||
.execute({}, { sessionID: "session" });
|
||||
expect(result).toMatchObject({
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot." },
|
||||
{ type: "file", mime: "image/png", uri: `data:image/png;base64,${png}` },
|
||||
],
|
||||
});
|
||||
await dispose();
|
||||
} finally {
|
||||
release();
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("v2 structured output validates values and clears its tool on ordinary turns", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-v2-structured-"));
|
||||
temporaryDirectories.push(root);
|
||||
|
||||
@@ -45,10 +45,7 @@ export default {
|
||||
`/sessions/${encodeURIComponent(binding.sessionID)}/tools/${encodeURIComponent(definition.name)}`,
|
||||
input,
|
||||
);
|
||||
return {
|
||||
content: result.content.map(toOpenCodeContent),
|
||||
metadata: { paseoTool: definition.name },
|
||||
};
|
||||
return { content: result.content, metadata: { paseoTool: definition.name } };
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -68,11 +65,3 @@ export default {
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// OpenCode tool content is text or a file; MCP images arrive as base64 data.
|
||||
function toOpenCodeContent(part) {
|
||||
if (part.type === "image") {
|
||||
return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType };
|
||||
}
|
||||
return part;
|
||||
}
|
||||
|
||||
@@ -54,44 +54,3 @@ test("a completed edit carries the replaced and replacement text", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("a tool's image output is shown as an image, not as base64 in the tool output", () => {
|
||||
const png =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";
|
||||
const screenshot = assistant([
|
||||
{
|
||||
type: "tool",
|
||||
id: "call-screenshot",
|
||||
name: "paseo_browser_screenshot",
|
||||
executed: false,
|
||||
state: {
|
||||
status: "completed",
|
||||
input: {},
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot (1x1)." },
|
||||
{ type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png" },
|
||||
],
|
||||
metadata: {},
|
||||
},
|
||||
time: { created: 2, ran: 2, completed: 2 },
|
||||
},
|
||||
]);
|
||||
const timeline = new V2Timeline();
|
||||
|
||||
const events = timeline.messages([screenshot]);
|
||||
|
||||
expect(JSON.stringify(events)).not.toContain(png);
|
||||
expect(events.map((event) => event.type === "timeline" && event.item)).toMatchObject([
|
||||
{
|
||||
type: "tool_call",
|
||||
name: "paseo_browser_screenshot",
|
||||
status: "completed",
|
||||
detail: { output: "Captured browser screenshot (1x1).\n[image]" },
|
||||
},
|
||||
{
|
||||
type: "assistant_message",
|
||||
text: expect.stringMatching(/^!\[Image\]\(file:\/\/.*paseo-attachments.*\.png\)$/),
|
||||
},
|
||||
]);
|
||||
expect(timeline.messages([screenshot])).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import { mapOpencodeToolCall } from "../tool-call-mapper.js";
|
||||
import {
|
||||
materializeProviderImage,
|
||||
renderProviderImageOutputAsAssistantMarkdown,
|
||||
} from "../../provider-image-output.js";
|
||||
import type { SessionMessageAssistantTool } from "@opencode/client";
|
||||
import { STRUCTURED_OUTPUT_TOOL } from "./structured-output.js";
|
||||
import type { SessionMessageInfo } from "@opencode/client";
|
||||
@@ -162,21 +158,8 @@ export class V2Timeline {
|
||||
const serialized = JSON.stringify(part);
|
||||
if (serialized === this.content.get(key)) return;
|
||||
this.content.set(key, serialized);
|
||||
const { output, images } = splitToolContent(part.state);
|
||||
const item = toolFromV2(part, output);
|
||||
const item = toolFromV2(part);
|
||||
if (item) push(item);
|
||||
// Images follow their tool call as markdown, as Claude and Codex emit them,
|
||||
// so base64 never reaches the tool output.
|
||||
images.forEach((image, index) => {
|
||||
const imageKey = `${key}:image:${index}`;
|
||||
if (this.content.has(imageKey)) return;
|
||||
this.content.set(imageKey, "");
|
||||
const imageItem = renderProviderImageOutputAsAssistantMarkdown(
|
||||
{ url: image.uri, mimeType: image.mime },
|
||||
{ materialize: materializeProviderImage },
|
||||
);
|
||||
if (imageItem) push(imageItem);
|
||||
});
|
||||
}
|
||||
|
||||
private compactionMessage(
|
||||
@@ -204,28 +187,12 @@ interface TextPartIdentity {
|
||||
interface TextPartDelta extends TextPartIdentity {
|
||||
delta: string;
|
||||
}
|
||||
function splitToolContent(state: SessionMessageAssistantTool["state"]): {
|
||||
output: string | undefined;
|
||||
images: { uri: string; mime: string }[];
|
||||
} {
|
||||
if (!("content" in state) || !state.content) return { output: undefined, images: [] };
|
||||
const images: { uri: string; mime: string }[] = [];
|
||||
const output = state.content
|
||||
.map((part) => {
|
||||
if (part.type === "text") return part.text;
|
||||
if (!part.uri.startsWith("data:image/")) return part.uri;
|
||||
images.push(part);
|
||||
return "[image]";
|
||||
})
|
||||
.join("\n");
|
||||
return { output, images };
|
||||
}
|
||||
|
||||
function toolFromV2(
|
||||
tool: SessionMessageAssistantTool,
|
||||
output: string | undefined,
|
||||
): AgentTimelineItem | null {
|
||||
function toolFromV2(tool: SessionMessageAssistantTool): AgentTimelineItem | null {
|
||||
const state = tool.state;
|
||||
const output =
|
||||
"content" in state
|
||||
? state.content?.map((part) => (part.type === "text" ? part.text : part.uri)).join("\n")
|
||||
: undefined;
|
||||
return mapOpencodeToolCall({
|
||||
toolName: tool.name,
|
||||
callId: tool.id,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { AgentDirectory } from "../directory.js";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { z } from "zod";
|
||||
import { ensureValidJson } from "../../json-utils.js";
|
||||
@@ -60,9 +59,9 @@ import {
|
||||
sanitizePermissionRequest,
|
||||
serializeSnapshotWithMetadata,
|
||||
toScheduleSummary,
|
||||
waitForAgentWithTimeout,
|
||||
} from "../mcp-shared.js";
|
||||
import {
|
||||
type PromptDispatchDisposition,
|
||||
sendPromptToAgent,
|
||||
setupFinishNotification,
|
||||
waitForAgentRunStartWithTimeout,
|
||||
@@ -124,7 +123,6 @@ export interface PaseoToolHostDependencies {
|
||||
cwd: string,
|
||||
title?: string | null,
|
||||
projectId?: string,
|
||||
context?: { background?: boolean; callerWorkspaceId?: string },
|
||||
) => Promise<PersistedWorkspaceRecord>;
|
||||
workspaceScripts?: Pick<WorkspaceScriptsService, "list" | "launch" | "stop">;
|
||||
markWorkspaceArchiving?: ArchiveDependencies["markWorkspaceArchiving"];
|
||||
@@ -134,7 +132,6 @@ export interface PaseoToolHostDependencies {
|
||||
ensureWorkspaceForCreate?: (
|
||||
cwd: string,
|
||||
firstAgentContext?: FirstAgentContext,
|
||||
context?: { callerWorkspaceId?: string },
|
||||
) => Promise<string>;
|
||||
browserToolsEnabled?: boolean;
|
||||
browserToolsBroker?: BrowserToolsBroker | null;
|
||||
@@ -192,7 +189,6 @@ const WorkspaceAutomationSummarySchema = z.object({
|
||||
isolation: z.enum(["local", "worktree"]),
|
||||
kind: z.enum(["directory", "local_checkout", "worktree"]),
|
||||
title: z.string().nullable(),
|
||||
background: z.boolean().optional(),
|
||||
});
|
||||
|
||||
function toWorkspaceAutomationSummary(workspace: PersistedWorkspaceRecord) {
|
||||
@@ -203,7 +199,6 @@ function toWorkspaceAutomationSummary(workspace: PersistedWorkspaceRecord) {
|
||||
isolation: workspace.kind === "worktree" ? ("worktree" as const) : ("local" as const),
|
||||
kind: workspace.kind,
|
||||
title: workspace.title,
|
||||
background: workspace.background,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1052,6 +1047,13 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
};
|
||||
const canonicalTopLevelInputSchema = {
|
||||
...canonicalCreateAgentFields,
|
||||
background: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe(
|
||||
"Run agent in background. If false (default), waits for completion or permission request. If true, returns immediately.",
|
||||
),
|
||||
notifyOnFinish: z
|
||||
.boolean()
|
||||
.optional()
|
||||
@@ -1069,6 +1071,7 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
...commonCreateAgentFields,
|
||||
relationship: legacyCreateAgentPlacementFields.relationship.optional(),
|
||||
workspace: legacyCreateAgentPlacementFields.workspace.optional(),
|
||||
background: canonicalTopLevelInputSchema.background,
|
||||
notifyOnFinish: canonicalTopLevelInputSchema.notifyOnFinish,
|
||||
cwd: z
|
||||
.string()
|
||||
@@ -1126,6 +1129,13 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
};
|
||||
const agentToAgentSendAgentPromptInputSchema = {
|
||||
...commonSendAgentPromptInputSchema,
|
||||
background: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(true)
|
||||
.describe(
|
||||
"Run agent in background. Agent-scoped default is true so you can continue until the finish notification arrives. Set false only when you need a blocking response.",
|
||||
),
|
||||
notifyOnFinish: z
|
||||
.boolean()
|
||||
.optional()
|
||||
@@ -1136,6 +1146,13 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
};
|
||||
const topLevelSendAgentPromptInputSchema = {
|
||||
...commonSendAgentPromptInputSchema,
|
||||
background: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe(
|
||||
"Run agent in background. If false (default), waits for completion or permission request. If true, returns immediately.",
|
||||
),
|
||||
notifyOnFinish: z
|
||||
.boolean()
|
||||
.optional()
|
||||
@@ -1232,12 +1249,6 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
),
|
||||
projectId: z.string().optional().describe("Existing project id to own the workspace."),
|
||||
title: z.string().trim().min(1).optional(),
|
||||
background: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"True hides the workspace from default lists and the sidebar while its contents remain durable and accessible; omit background to inherit your current workspace’s value (false without a caller), and override it only when the user explicitly asks.",
|
||||
),
|
||||
mode: z
|
||||
.enum(["branch-off", "checkout-branch", "checkout-pr"])
|
||||
.optional()
|
||||
@@ -1276,7 +1287,6 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
path,
|
||||
projectId,
|
||||
title,
|
||||
background,
|
||||
mode,
|
||||
worktreeSlug,
|
||||
branchName,
|
||||
@@ -1306,10 +1316,7 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
if (!options.createDirectoryWorkspace) {
|
||||
throw new Error("Workspace provisioning is not configured");
|
||||
}
|
||||
workspace = await options.createDirectoryWorkspace(cwd, title, projectId, {
|
||||
background,
|
||||
callerWorkspaceId: resolveCallerAgent()?.workspaceId,
|
||||
});
|
||||
workspace = await options.createDirectoryWorkspace(cwd, title, projectId);
|
||||
} else {
|
||||
let cwd =
|
||||
path !== undefined || !projectId ? resolveScopedCwd(path, { required: true }) : null;
|
||||
@@ -1340,8 +1347,6 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
...(worktreeSlug ? { worktreeSlug } : {}),
|
||||
...worktreeTarget,
|
||||
...(title ? { title } : {}),
|
||||
background,
|
||||
callerWorkspaceId: resolveCallerAgent()?.workspaceId,
|
||||
},
|
||||
);
|
||||
if (!result.ok) {
|
||||
@@ -1362,17 +1367,15 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
{
|
||||
title: "List workspaces",
|
||||
description: "List active workspaces.",
|
||||
inputSchema: { includeBackground: z.boolean().optional().default(false) },
|
||||
inputSchema: {},
|
||||
outputSchema: { workspaces: z.array(WorkspaceAutomationSummarySchema) },
|
||||
},
|
||||
async ({ includeBackground = false }) => {
|
||||
async () => {
|
||||
if (!options.workspaceRegistry) {
|
||||
throw new Error("Workspace registry is not configured");
|
||||
}
|
||||
const workspaces = (await options.workspaceRegistry.list())
|
||||
.filter(
|
||||
(workspace) => !workspace.archivedAt && (includeBackground || !workspace.background),
|
||||
)
|
||||
.filter((workspace) => !workspace.archivedAt)
|
||||
.map(toWorkspaceAutomationSummary);
|
||||
return {
|
||||
content: [],
|
||||
@@ -1439,21 +1442,30 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
workspaceId: z.string().optional(),
|
||||
currentModeId: z.string().nullable(),
|
||||
availableModes: z.array(ProviderModeSchema),
|
||||
lastMessage: z.string().nullable().optional(),
|
||||
permission: AgentPermissionRequestPayloadSchema.nullable().optional(),
|
||||
guidance: z.string().optional(),
|
||||
},
|
||||
},
|
||||
async (args: unknown) => {
|
||||
const resolvedArgs = await resolveCreateAgentToolArgs(args);
|
||||
const { parsedArgs, worktree } = resolvedArgs;
|
||||
let requestedBackground: boolean;
|
||||
let notifyOnFinish: boolean;
|
||||
if (resolvedArgs.kind === "agent-scoped") {
|
||||
requestedBackground = true;
|
||||
notifyOnFinish = parsedArgs.notifyOnFinish;
|
||||
} else {
|
||||
requestedBackground = resolvedArgs.parsedArgs.background;
|
||||
notifyOnFinish = resolvedArgs.parsedArgs.notifyOnFinish ?? false;
|
||||
}
|
||||
const selectedProvider = resolveRequiredProviderModel(parsedArgs.provider).provider;
|
||||
const inheritedConfig = resolveInheritedProviderConfig(selectedProvider);
|
||||
const { snapshot, initialPromptStarted } = await createAgentCommand(
|
||||
const {
|
||||
snapshot,
|
||||
background: createdInBackground,
|
||||
initialPromptStarted,
|
||||
} = await createAgentCommand(
|
||||
{
|
||||
agentManager,
|
||||
agentStorage,
|
||||
@@ -1479,7 +1491,7 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
features: parsedArgs.settings?.features,
|
||||
labels: parsedArgs.labels,
|
||||
mode: parsedArgs.settings?.modeId,
|
||||
promptFailure: "throw",
|
||||
background: requestedBackground,
|
||||
notifyOnFinish,
|
||||
detached: resolvedArgs.detached,
|
||||
callerAgentId,
|
||||
@@ -1488,12 +1500,43 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
if (!createdInBackground && initialPromptStarted) {
|
||||
const result = await waitForAgentWithTimeout(agentManager, snapshot.id, {
|
||||
waitForActive: true,
|
||||
});
|
||||
|
||||
const liveSnapshot = agentManager.getAgent(snapshot.id) ?? snapshot;
|
||||
const responseData = {
|
||||
agentId: snapshot.id,
|
||||
type: snapshot.provider,
|
||||
status: result.status,
|
||||
cwd: liveSnapshot.cwd,
|
||||
...(liveSnapshot.workspaceId ? { workspaceId: liveSnapshot.workspaceId } : {}),
|
||||
currentModeId: liveSnapshot.currentModeId,
|
||||
availableModes: liveSnapshot.availableModes,
|
||||
lastMessage: result.lastMessage,
|
||||
permission: sanitizePermissionRequest(result.permission),
|
||||
};
|
||||
const validJson = ensureValidJson(responseData);
|
||||
|
||||
const response = {
|
||||
content: [],
|
||||
structuredContent: validJson,
|
||||
};
|
||||
return response;
|
||||
}
|
||||
} catch (error) {
|
||||
childLogger.error({ err: error, agentId: snapshot.id }, "Failed to run initial prompt");
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Return immediately for async creation.
|
||||
const currentSnapshot = agentManager.getAgent(snapshot.id) ?? snapshot;
|
||||
const guidance =
|
||||
callerAgentId && notifyOnFinish && initialPromptStarted
|
||||
? "You will get notified when the created agent finishes, errors, or needs permission. Do not poll for status; continue with other work until the notification arrives."
|
||||
: "Creation acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.";
|
||||
: undefined;
|
||||
const response = {
|
||||
content: [],
|
||||
structuredContent: ensureValidJson({
|
||||
@@ -1504,6 +1547,8 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
...(currentSnapshot.workspaceId ? { workspaceId: currentSnapshot.workspaceId } : {}),
|
||||
currentModeId: currentSnapshot.currentModeId,
|
||||
availableModes: currentSnapshot.availableModes,
|
||||
lastMessage: null,
|
||||
permission: null,
|
||||
...(guidance ? { guidance } : {}),
|
||||
}),
|
||||
};
|
||||
@@ -1637,9 +1682,7 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
const cwd = process.cwd();
|
||||
return {
|
||||
cwd,
|
||||
workspaceId: await options.ensureWorkspaceForCreate(cwd, firstAgentContext, {
|
||||
callerWorkspaceId: resolveCallerAgent()?.workspaceId,
|
||||
}),
|
||||
workspaceId: await options.ensureWorkspaceForCreate(cwd, firstAgentContext),
|
||||
};
|
||||
}
|
||||
const caller = resolveCallerAgent();
|
||||
@@ -1807,9 +1850,7 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
}
|
||||
return {
|
||||
cwd,
|
||||
workspaceId: await options.ensureWorkspaceForCreate(cwd, firstAgentContext, {
|
||||
callerWorkspaceId: resolveCallerAgent()?.workspaceId,
|
||||
}),
|
||||
workspaceId: await options.ensureWorkspaceForCreate(cwd, firstAgentContext),
|
||||
worktree: undefined,
|
||||
};
|
||||
}
|
||||
@@ -1856,62 +1897,88 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
{
|
||||
title: "Send agent prompt",
|
||||
description:
|
||||
"Send a task and return after dispatch acknowledgement. Calling agents receive finish notifications by default.",
|
||||
"Send a task to a running agent. Agent-scoped callers run in background by default; top-level callers wait by default.",
|
||||
inputSchema: sendAgentPromptInputSchema,
|
||||
outputSchema: {
|
||||
success: z.boolean(),
|
||||
disposition: z.enum(["turn_started", "out_of_band"]).optional(),
|
||||
status: AgentStatusEnum,
|
||||
lastMessage: z.string().nullable().optional(),
|
||||
permission: AgentPermissionRequestPayloadSchema.nullable().optional(),
|
||||
guidance: z.string().optional(),
|
||||
},
|
||||
},
|
||||
async ({ agentId, prompt, sessionMode, notifyOnFinish = Boolean(callerAgentId) }) => {
|
||||
let stopNotification: (() => void) | undefined;
|
||||
function armFinishNotification(disposition: PromptDispatchDisposition): void {
|
||||
async ({
|
||||
agentId,
|
||||
prompt,
|
||||
sessionMode,
|
||||
background = Boolean(callerAgentId),
|
||||
notifyOnFinish = Boolean(callerAgentId),
|
||||
}) => {
|
||||
function armFinishNotification(): boolean {
|
||||
if (!callerAgentId || !notifyOnFinish) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
stopNotification = setupFinishNotification({
|
||||
setupFinishNotification({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
childAgentId: agentId,
|
||||
callerAgentId,
|
||||
waitForTurnStart: disposition === "turn_started",
|
||||
logger: childLogger,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const notifying = Boolean(callerAgentId && notifyOnFinish);
|
||||
const { disposition } = await sendPromptToAgent({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
agentId,
|
||||
prompt,
|
||||
source: callerAgentId ? { kind: "agent-message", agentId: callerAgentId } : undefined,
|
||||
sessionMode,
|
||||
onDispatch: armFinishNotification,
|
||||
logger: childLogger,
|
||||
}).catch((error) => {
|
||||
stopNotification?.();
|
||||
throw error;
|
||||
});
|
||||
|
||||
// If not running in background, wait for completion
|
||||
if (!background) {
|
||||
const result = await waitForAgentWithTimeout(agentManager, agentId, {
|
||||
waitForActive: true,
|
||||
});
|
||||
// The wait ran out while the agent keeps working, so its result arrives as a
|
||||
// finish notification instead of in this response.
|
||||
const notifying =
|
||||
result.timedOut &&
|
||||
agentManager.getAgent(agentId)?.lifecycle === "running" &&
|
||||
armFinishNotification();
|
||||
|
||||
const responseData = {
|
||||
success: true,
|
||||
status: result.status,
|
||||
lastMessage: result.lastMessage,
|
||||
permission: sanitizePermissionRequest(result.permission),
|
||||
...(notifying ? { guidance: PROMPTED_AGENT_NOTIFICATION_GUIDANCE } : {}),
|
||||
};
|
||||
const validJson = ensureValidJson(responseData);
|
||||
|
||||
const response = {
|
||||
content: [],
|
||||
structuredContent: validJson,
|
||||
};
|
||||
return response;
|
||||
}
|
||||
|
||||
const notifying = armFinishNotification();
|
||||
|
||||
// Return once the provider has accepted the turn, so the status reports it running.
|
||||
if (disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => {
|
||||
stopNotification?.();
|
||||
throw error;
|
||||
});
|
||||
await waitForAgentRunStartWithTimeout(agentManager, agentId);
|
||||
}
|
||||
const currentSnapshot = agentManager.getAgent(agentId);
|
||||
|
||||
const responseData = {
|
||||
success: true,
|
||||
disposition,
|
||||
status: currentSnapshot?.lifecycle ?? "idle",
|
||||
guidance: notifying
|
||||
? PROMPTED_AGENT_NOTIFICATION_GUIDANCE
|
||||
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
|
||||
lastMessage: null,
|
||||
permission: null,
|
||||
...(notifying ? { guidance: PROMPTED_AGENT_NOTIFICATION_GUIDANCE } : {}),
|
||||
};
|
||||
const validJson = ensureValidJson(responseData);
|
||||
|
||||
@@ -1979,7 +2046,6 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
title: "List agents",
|
||||
description: "List recent agents as compact metadata.",
|
||||
inputSchema: {
|
||||
includeBackground: z.boolean().optional().default(false),
|
||||
includeArchived: z.boolean().optional().default(false),
|
||||
cwd: z.string().optional(),
|
||||
sinceHours: z
|
||||
@@ -1996,38 +2062,29 @@ export function createPaseoToolCatalog(options: PaseoToolHostDependencies): Pase
|
||||
agents: z.array(AgentListItemPayloadSchema),
|
||||
},
|
||||
},
|
||||
async ({
|
||||
includeBackground = false,
|
||||
includeArchived = false,
|
||||
cwd,
|
||||
sinceHours = 48,
|
||||
statuses,
|
||||
limit = 50,
|
||||
}) => {
|
||||
async ({ includeArchived = false, cwd, sinceHours = 48, statuses, limit = 50 }) => {
|
||||
const callerCwd = callerAgentId ? resolveCallerAgent()?.cwd : undefined;
|
||||
const requestedCwd = cwd?.trim() ? expandUserPath(cwd) : callerCwd;
|
||||
const statusFilter = statuses && statuses.length > 0 ? new Set(statuses) : null;
|
||||
const sinceMs = Date.now() - sinceHours * 60 * 60 * 1000;
|
||||
if (!options.workspaceRegistry) throw new Error("Workspace registry is not configured");
|
||||
const directory = new AgentDirectory({
|
||||
manager: agentManager,
|
||||
storage: agentStorage,
|
||||
workspaces: options.workspaceRegistry,
|
||||
projectLive: (snapshot) =>
|
||||
const liveSnapshots = agentManager.listAgents();
|
||||
const liveAgents = await Promise.all(
|
||||
liveSnapshots.map((snapshot) =>
|
||||
serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger),
|
||||
projectStored: (record) =>
|
||||
buildStoredAgentPayload(
|
||||
record,
|
||||
new Set(providerSnapshotManager.listRegisteredProviderIds()),
|
||||
),
|
||||
isProviderVisible: () => true,
|
||||
isStoredProviderAvailable: (record) =>
|
||||
isStoredAgentProviderAvailable(
|
||||
record,
|
||||
new Set(providerSnapshotManager.listRegisteredProviderIds()),
|
||||
),
|
||||
});
|
||||
const agents = (await directory.list({ includeBackground, includeArchived }))
|
||||
),
|
||||
);
|
||||
const liveIds = new Set(liveSnapshots.map((snapshot) => snapshot.id));
|
||||
const storedRecords = await agentStorage.list();
|
||||
const registeredProviderIds = new Set(providerSnapshotManager.listRegisteredProviderIds());
|
||||
const storedAgents = storedRecords
|
||||
.filter((record) => !record.internal && !liveIds.has(record.id))
|
||||
.filter((record) => includeArchived || !record.archivedAt)
|
||||
.filter(
|
||||
(record) =>
|
||||
includeArchived || isStoredAgentProviderAvailable(record, registeredProviderIds),
|
||||
)
|
||||
.map((record) => buildStoredAgentPayload(record, registeredProviderIds));
|
||||
const agents = [...liveAgents, ...storedAgents]
|
||||
.map(toAgentListItemPayload)
|
||||
.filter((agent) => !requestedCwd || isSameOrDescendantPath(requestedCwd, agent.cwd))
|
||||
.filter((agent) => !statusFilter || statusFilter.has(agent.status))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user