Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 878a89b10e test(android): build panel edge tests on the shared mounting context
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:33:28 +00:00
paseo-bot[bot]andClaude Opus 5.5 e167602ac5 chore: update panel scrolling branch from main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:12:16 +00:00
965e28e3d6 feat(highlight): add diff/patch and zero-dependency legacy-mode syntax highlighting (#11026)
* feat(highlight): highlight diff and patch fences and files

Register CodeMirror's legacy diff mode for .diff and .patch files and diff/patch code fences, mapping inserted/deleted tokens to diffAddition/diffDeletion roles and stripping legacy trailing-whitespace error prefixes so CodeMirror emits no unknown-tag warnings.

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>

* feat(highlight): add Ruby syntax highlighting

Register @codemirror/legacy-modes ruby via StreamLanguage for rb, rbw, rake,
gemspec, ru, jbuilder, podspec and thor, plus extensionless Ruby files
(Gemfile, Rakefile, Guardfile, Capfile, Podfile, Vagrantfile, ...).

* feat(highlight): add Kotlin syntax highlighting for .kt/.kts files

Kotlin files previously rendered as plain text in diffs, the read-only
source panel, and the editor because the extension map in
@getpaseo/highlight had no entry for kt/kts. Register the kotlin stream
parser from @codemirror/legacy-modes/mode/clike, the same package already
used for Swift and Dart.

* test(highlight): assert Kotlin token styles in highlightCode

Follow-up to review feedback: the parsers tests only checked that
kt/kts are registered. Add a Kotlin case to the highlightCode suite,
mirroring the Swift and Dart cases, asserting keyword ('class', 'val'),
type ('String'), and string token styles. Fails on main without the
parser registration, passes with it.

* feat(highlight): add TOML syntax highlighting

* feat(highlight): add remaining legacy-mode languages and fence aliases

Register SQL, Lua, Protobuf, PowerShell, Groovy/Gradle, Scala, CMake (including CMakeLists.txt), Properties/INI, R, Perl, and LaTeX/TeX from @codemirror/legacy-modes, and add fence alias parity (including shell, ruby, kotlin, powershell/pwsh, protobuf, perl, and latex) in HighlightedCodeBlock.

Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>

* fix(highlight): unify diff token colors and support binary diff frames

Append diffAddition and diffDeletion to DIFF_HIGHLIGHT_STYLES so Changes panel binary diff frames preserve diff colors for .diff/.patch files while older clients safely decode unknown indices as null. Unify syntaxTokenStyles onto theme.colors.syntax and tune light syntax theme diff colors to >=4.0:1 contrast on code surfaces.

---------

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>
Co-authored-by: Karol Bąk <kukicola@gmail.com>
Co-authored-by: Anton Prokhorov <anton.prokhorov@jetbrains.com>
Co-authored-by: chandlerok <chandleroking@gmail.com>
Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>
2026-11-27 15:31:57 +07:00
Mohamed Boudra 690f6970c3 fix(app): focus composer when dropping attachments (#11022)
Workspace file drops already called focusInput(), but raster image drops went directly to addImages() and generic file drops only uploaded without focusing. Focus the composer when dropped images attach and as soon as dropped files are accepted for upload, so users can type right away without waiting for uploads to finish.
2026-11-27 14:33:30 +07:00
paseo-bot[bot] bcb0097344 test(terminal): accept socket-overflow output that arrives after the replay (#11016)
The PTY child finishing its write does not mean the worker has parsed those
bytes. On Windows, ConPTY renders before the worker reads, so the reconnect
snapshot can be cut before the last marker; that marker then reaches the
viewer as live output. Wait for it across the replay and the live output
that follows the replay end.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 06:59:00 +00:00
Mohamed Boudra 9eab3b278f Stop client plugins from crashing iOS when importing react-native (#11011)
* fix(plugins): prevent iOS PushNotificationIOS crash when plugins import react-native

Filter unsupported throwing getters (PushNotificationIOS, AsyncStorage, ImagePickerIOS, ProgressViewIOS, DatePickerIOS, Slider) and raw default from the react-native runtime exposed to client plugins, while preserving lazy property descriptors on safe exports.

Also replace eager Hermes CommonJS interop evaluation (value: from[key]) with per-key lazy getter closures (get: ((k) => () => from[k])(key)) in the server plugin compiler so namespace imports no longer evaluate unrelated host module getters.

Closes #10978

* fix(plugins): allowlist safe react-native exports for client plugins

Replace the react-native denylist in evaluate.ts with an explicit allowlist of cross-platform UI, layout, and animation exports (PLUGIN_REACT_NATIVE_EXPORTS) while preserving lazy property descriptors.

Add a wiring test verifying require('react-native') returns the allowlisted runtime object rather than the raw ReactNative namespace, plus a contract test verifying every allowlisted key exists as a non-deprecated, non-throwing getter in react-native/index.js.

* fix(plugins): retain SafeAreaView and InteractionManager in react-native allowlist

Keep SafeAreaView and InteractionManager in PLUGIN_REACT_NATIVE_EXPORTS so existing published plugins that import them from react-native (e.g. SafeAreaView insets and InteractionManager.runAfterInteractions) keep working on iOS, Android, and web. Both exports are safe cross-platform getters on iOS and react-native-web and remain lazy under the compiler's per-key getter interop.

Also harden the react-native/index.js getter contract test to assert the parser matched getters and that PushNotificationIOS stays excluded.

* fix(plugins): omit only PushNotificationIOS and default from plugin react-native runtime

Replace the 46-key react-native allowlist with copying all own enumerable descriptors from Object.keys(source) lazily while skipping only PushNotificationIOS and default. An audit of published plugins showed 14 plugins rely on react-native exports outside the allowlist (TurboModuleRegistry, NativeModules, UIManager, DeviceEventEmitter, AppRegistry, Clipboard, Settings, and RN-web render).

Keep the lazy per-key Hermes interop fix in compiler-build.ts, the require('react-native') wiring test, and the react-native/index.js enumerable getter contract test.
2026-11-27 13:49:51 +07:00
Mohamed Boudra fcfcdf156a Make ACP catalog probing respectful and clean up Antigravity ACP hygiene (#10992)
* feat(acp): make ACP catalog probing respectful and clean up Antigravity ACP hygiene

* fix(acp): address Windows CI failures and paseo-bot review findings

* refactor(acp): remove manual catalog mode and use on_demand for Antigravity

* fix(server): share Windows WinGet candidate resolution when findExecutable skips probing

* test(server): compare Windows PATHEXT casing case-insensitively in executable-resolution test
2026-11-27 13:29:55 +07:00
paseo-bot[bot] f792ac8a4e chore: update panel scrolling branch from main 2026-11-06 07:49:20 +00:00
paseo-bot[bot] e8a9e2d699 chore(android): carry panel scrolling fix onto the current timeline 2026-11-06 07:48:53 +00:00
paseo-bot[bot]andluckxine 5feec6fa35 fix(android): contain nested panel motion in the current timeline
Identify the forward-order timeline by its existing native identity so panel edges stay still while ordinary parents retain Android handoff. Preserve the native content-position corrections.

Co-authored-by: luckxine <91582901+luckxine@users.noreply.github.com>
2026-11-06 07:46:51 +00:00
paseo-bot[bot]andluckxine 138d9d63ab fix(android): keep panel overscroll inside inverted timelines
Android forwards a nested panel’s unconsumed scroll and fling to its inverted parent, moving the timeline in the opposite visual direction. Keep that motion inside the panel while preserving ordinary parent scrolling and nested-scroll registration.

Co-authored-by: luckxine <91582901+luckxine@users.noreply.github.com>
2026-11-01 14:32:01 +00:00
54 changed files with 3216 additions and 212 deletions
+11 -2
View File
@@ -202,8 +202,17 @@ This is the Android counterpart of the iOS local-simulator flow in [development.
`modules/paseo-scroll` replaces React Native's vertical scroll view with `PaseoScrollView`, which
keeps React Native's scroll manager interface and corrects how the chat timeline holds its position.
[agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) lists the
corrections and the React Native issues they work around. Its instrumentation tests run the scroll
view in a real window, mounting through React Native's own mounting manager and injecting touches:
corrections and the React Native issues they work around.
The timeline's `nativeID` (`agent-chat-scroll-native-virtualized`) also identifies it to the native
scroll owner: a nested panel's edge overshoot and unconsumed fling must leave the timeline still.
Ordinary scroll parents retain Android's handoff. Keep that identity in sync with
`agent-stream/strategy-native.tsx`; the end pin is absent while reading history, so it cannot
identify the timeline for this rule.
Its instrumentation tests run the scroll view in a real window, mounting through React Native's own
mounting manager and injecting touches. `PanelEdgeTest` covers both panel edges, flings,
interior/direct scrolling, and ordinary-parent handoff:
```bash
cd packages/app/android
@@ -12,9 +12,12 @@ import {
openImageLightbox,
closeImageLightbox,
pressInterruptShortcut,
blurComposerInput,
expectComposerDraft,
expectComposerDisabled,
expectComposerEditable,
expectComposerFocused,
expectComposerNotFocused,
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
@@ -175,8 +178,19 @@ test.describe("Composer attachments", () => {
await test.step("remove the image and attach a dropped file", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_IMAGE);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
});
@@ -198,9 +212,12 @@ test.describe("Composer attachments", () => {
projectDisplayName: workspace.projectDisplayName,
});
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
} finally {
await workspace.cleanup();
}
@@ -0,0 +1,235 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import {
openFileExplorer,
openFileFromExplorer,
expectFileTabOpen,
} from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const APP_SETTINGS_KEY = "@paseo:app-settings";
const DIFF_FIXTURE = [
"Here is a diff block:",
"",
"```diff",
"diff --git a/src/greet.ts b/src/greet.ts",
"--- a/src/greet.ts",
"+++ b/src/greet.ts",
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
" const prefix = 'Hello';",
"- return `${prefix}, ${name}`;",
"+ const trimmed = name.trim();",
"+ return `${prefix}, ${trimmed}!`;",
"```",
"",
"And a patch block:",
"",
"```patch",
"--- a/README.md",
"+++ b/README.md",
"@@ -1,2 +1,2 @@",
" # Paseo",
"-Old description",
"+New description",
"```",
"",
"Plus Ruby, Kotlin, TOML, and SQL:",
"",
"```ruby",
"class Greeter",
' def hi(name) = "Hello #{name}"',
"end",
"```",
"",
"```kotlin",
'val message: String = "Kotlin ready"',
"```",
"",
"```toml",
"[server]",
'host = "localhost"',
"```",
"",
"```sql",
"SELECT id, name FROM users WHERE active = TRUE;",
"```",
].join("\n");
const FILE_DIFF_CONTENT = [
"diff --git a/app.py b/app.py",
"index 1111111..2222222 100644",
"--- a/app.py",
"+++ b/app.py",
"@@ -1,3 +1,3 @@ def greet():",
" print('hello')",
"-old_value = 1",
"+new_value = 2",
].join("\n");
async function saveScreenshot(page: Page, name: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR;
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, name), fullPage: true });
}
function assistantMessages(page: Page) {
return page.locator("[data-message-id]").filter({ has: page.getByTestId("assistant-message") });
}
test.describe("diff and patch syntax highlighting", () => {
for (const theme of ["dark", "light"] as const) {
test(`highlights diff and patch fences in chat (${theme} theme)`, async ({ page }) => {
await page.addInitScript(
({ key, mode }) => {
localStorage.setItem(key, JSON.stringify({ theme: mode }));
},
{ key: APP_SETTINGS_KEY, mode: theme },
);
const agent = await seedMockAgentWorkspace({
repoPrefix: `diff-chat-${theme}-`,
title: `Diff highlight (${theme})`,
initialPrompt: "Show me the diff and patch.",
featureValues: { mockAssistantResponse: DIFF_FIXTURE },
});
try {
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const message = assistantMessages(page);
const expectedColors =
theme === "dark"
? {
addition: "rgb(152, 195, 121)",
deletion: "rgb(224, 108, 117)",
meta: "rgb(92, 99, 112)",
}
: {
addition: "rgb(52, 130, 51)",
deletion: "rgb(214, 59, 47)",
meta: "rgb(160, 161, 167)",
};
const diffAdd = message.getByText("+ const trimmed = name.trim();", { exact: true });
const diffDel = message.getByText("- return `${prefix}, ${name}`;", { exact: true });
const diffMeta = message.getByText(
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
{
exact: true,
},
);
const patchAdd = message.getByText("+New description", { exact: true });
const patchDel = message.getByText("-Old description", { exact: true });
await expect(diffAdd).toBeVisible({ timeout: 30_000 });
await expect(diffAdd).toHaveCSS("color", expectedColors.addition);
await expect(diffDel).toHaveCSS("color", expectedColors.deletion);
await expect(diffMeta).toHaveCSS("color", expectedColors.meta);
await expect(patchAdd).toHaveCSS("color", expectedColors.addition);
await expect(patchDel).toHaveCSS("color", expectedColors.deletion);
const rubyDef = message.getByText("def", { exact: true });
const kotlinVal = message.getByText("val", { exact: true });
const tomlHost = message.getByText("host", { exact: true });
const sqlSelect = message.getByText("SELECT", { exact: true });
const expectedKeyword = theme === "dark" ? "rgb(198, 120, 221)" : "rgb(166, 38, 164)";
const expectedProperty = theme === "dark" ? "rgb(209, 154, 102)" : "rgb(152, 104, 1)";
await expect(rubyDef).toHaveCSS("color", expectedKeyword);
await expect(kotlinVal).toHaveCSS("color", expectedKeyword);
await expect(tomlHost).toHaveCSS("color", expectedProperty);
await expect(sqlSelect).toHaveCSS("color", expectedKeyword);
await saveScreenshot(page, `chat-diff-patch-${theme}.png`);
} finally {
await agent.cleanup();
}
});
}
test("highlights a .diff file in the Files viewer", async ({ page, withWorkspace }) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "dark" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "diff-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "changes.diff"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "changes.diff");
await expectFileTabOpen(page, "changes.diff");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(152, 195, 121)");
await expect(delLine).toHaveCSS("color", "rgb(224, 108, 117)");
await expect(metaLine).toHaveCSS("color", "rgb(92, 99, 112)");
await saveScreenshot(page, "files-viewer-diff-dark.png");
});
test("highlights a .patch file in the Files viewer (light theme)", async ({
page,
withWorkspace,
}) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "light" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "patch-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "fix.patch"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "fix.patch");
await expectFileTabOpen(page, "fix.patch");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(52, 130, 51)");
await expect(delLine).toHaveCSS("color", "rgb(214, 59, 47)");
await expect(metaLine).toHaveCSS("color", "rgb(160, 161, 167)");
await saveScreenshot(page, "files-viewer-patch-light.png");
});
});
@@ -0,0 +1,158 @@
package sh.paseo.scroll
import android.app.Activity
import android.content.Intent
import android.os.SystemClock
import android.view.View
import android.widget.FrameLayout
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.scroll.ReactScrollView
import com.facebook.react.views.scroll.ReactScrollViewManager
import com.facebook.react.views.view.ReactViewGroup
import com.facebook.soloader.SoLoader
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/** Forward-order parent, as used by the current Android timeline, and a nested panel at its edge. */
@RunWith(AndroidJUnit4::class)
class PanelEdgeTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private var activity: Activity? = null
private lateinit var manager: ReactScrollViewManager
@After fun finish() {
instrumentation.runOnMainSync { activity?.finish() }
}
@Test fun panelBottomEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its bottom", 600, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelTopEdgeLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 0)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, -100, null)
child.stopNestedScroll()
assertEquals("Panel stays at its top", 0, child.scrollY)
assertEquals("Panel overshoot must leave timeline still", 400, parent.scrollY)
}
}
@Test fun panelFlingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync {
assertEquals("Panel fling must leave timeline still", 400, parent.scrollY)
}
}
@Test fun disablingChildNestedScrollPreventsHandoff() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.isNestedScrollingEnabled = false
assertEquals(false, child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
assertEquals(400, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesNestedOvershoot() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedScroll(0, 0, 0, 100, null)
child.stopNestedScroll()
assertEquals("Ordinary parent retains framework handoff", 500, parent.scrollY)
}
}
@Test fun ordinaryParentStillConsumesUnconsumedFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
manager.setNativeId(parent, "ordinary-scroll-parent")
child.scrollTo(0, 600)
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
child.dispatchNestedFling(0f, 1500f, false)
child.stopNestedScroll()
}
SystemClock.sleep(500)
instrumentation.runOnMainSync { assertTrue(parent.scrollY > 400) }
}
@Test fun consumedPanelFlingDoesNotStartParentFling() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
assertTrue(child.startNestedScroll(View.SCROLL_AXIS_VERTICAL))
assertEquals(false, child.dispatchNestedFling(0f, 1500f, true))
child.stopNestedScroll()
assertEquals(400, parent.scrollY)
}
}
@Test fun panelInteriorScrollingLeavesTimelineStill() {
val (parent, child) = openPanel()
instrumentation.runOnMainSync {
child.scrollTo(0, 100)
assertEquals(100, child.scrollY)
assertEquals(400, parent.scrollY)
parent.scrollTo(0, 500)
assertEquals("Direct timeline scrolling remains available", 500, parent.scrollY)
}
}
private fun openPanel(): Pair<ReactScrollView, ReactScrollView> {
val started = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = started
lateinit var parent: ReactScrollView
lateinit var child: ReactScrollView
instrumentation.runOnMainSync {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(started)
SoLoader.init(started, OpenSourceMergedSoMapping)
val react = MountingReactContext(started.applicationContext)
val context = ThemedReactContext(react, started)
manager = PaseoScrollPackage().createViewManager(react, ReactScrollViewManager.REACT_CLASS) as ReactScrollViewManager
parent = manager.createViewInstance(context)
manager.setNativeId(parent, "agent-chat-scroll-native-virtualized")
child = manager.createViewInstance(context)
child.isNestedScrollingEnabled = true
val content = ReactViewGroup(context)
content.addView(child, FrameLayout.LayoutParams(300, 200).apply { topMargin = 400 })
parent.addView(content)
val childContent = ReactViewGroup(context)
child.addView(childContent)
started.setContentView(FrameLayout(started).apply { addView(parent, FrameLayout.LayoutParams(300, 400)) })
parent.layout(0, 0, 300, 400)
content.layout(0, 0, 300, 2000)
child.layout(0, 400, 300, 600)
childContent.layout(0, 0, 300, 800)
parent.scrollTo(0, 400)
}
return Pair(parent, child)
}
}
@@ -14,10 +14,13 @@ import com.facebook.react.views.scroll.ReactScrollView;
import com.facebook.react.views.scroll.ReactScrollViewHelper;
/**
* React Native's vertical scroll view with five corrections. Java, because the content-position
* React Native's vertical scroll view with six corrections. Java, because the content-position
* config type is internal to React Native's Kotlin module.
*/
final class PaseoScrollView extends ReactScrollView {
// The chat timeline, packages/app/src/agent-stream/strategy-native.tsx.
private static final String TIMELINE_NATIVE_ID = "agent-chat-scroll-native-virtualized";
// The chat timeline's end pin, packages/app/src/agent-stream/native-end-pin.tsx.
private static final String END_PIN_NATIVE_ID = "paseo-end-pin";
@@ -35,6 +38,26 @@ final class PaseoScrollView extends ReactScrollView {
super(context);
}
// A panel owns its gesture through its edges; remaining child motion must not move the chat
// behind it. The timeline's native identity stays present when its end pin is removed for
// reading history. Ordinary parents retain Android's nested-scroll handoff.
@Override
public void onNestedScroll(
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
if (isTimeline()) return;
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (isTimeline() && !consumed) return true;
return super.onNestedFling(target, velocityX, velocityY, consumed);
}
private boolean isTimeline() {
return TIMELINE_NATIVE_ID.equals(getTag(R.id.view_tag_native_id));
}
@Override
public void setMaintainVisibleContentPosition(
@Nullable MaintainVisibleScrollPositionHelper.Config config) {
@@ -775,6 +775,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
extraData={renderHistoryMountedRow}
keyExtractor={keyExtractor}
testID="agent-chat-scroll"
// The Android scroll owner identifies the timeline to contain nested panel gestures.
nativeID="agent-chat-scroll-native-virtualized"
ListHeaderComponent={historyStartContent}
ListFooterComponent={liveAuxiliaryContent ?? undefined}
@@ -61,6 +61,8 @@ export function appearanceStyleBoundaryKey(theme: Theme): string {
theme.colors.syntax.meta,
theme.colors.syntax.heading,
theme.colors.syntax.link,
theme.colors.syntax.diffAddition,
theme.colors.syntax.diffDeletion,
].join("\u0000");
}
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { tokenizeToLines } from "@/utils/highlight-cache";
import { fenceLanguageToExtension } from "./highlighted-code-block";
describe("fenceLanguageToExtension", () => {
it.each([
["shell", "sh"],
["ruby", "rb"],
["kotlin", "kt"],
["powershell", "ps1"],
["pwsh", "ps1"],
["protobuf", "proto"],
["latex", "tex"],
["stex", "tex"],
["diff", "diff"],
["patch", "patch"],
["sql", "sql"],
["lua", "lua"],
["proto", "proto"],
["groovy", "groovy"],
["gradle", "gradle"],
["scala", "scala"],
["cmake", "cmake"],
["properties", "properties"],
["ini", "ini"],
["conf", "conf"],
["r", "r"],
["perl", "pl"],
["toml", "toml"],
])("maps fence info %s to %s", (info, expected) => {
expect(fenceLanguageToExtension(info)).toBe(expected);
});
it("produces syntax tokens for every mapped fence alias", () => {
const samples: Array<[string, string]> = [
["shell", 'export FOO="bar"'],
["ruby", 'def hi\n "ok"\nend'],
["kotlin", 'val x: String = "ok"'],
["powershell", 'function Get-X { "ok" }'],
["pwsh", '$x = "ok"'],
["protobuf", 'syntax = "proto3";'],
["latex", "\\documentclass{article}"],
["perl", 'my $x = "ok";'],
["sql", "SELECT 1;"],
["lua", "local x = 1"],
["gradle", 'id "java"'],
["scala", "val x = 1"],
["cmake", "project(Paseo)"],
["ini", "[section]\nkey = value"],
["r", "x <- function(a) a"],
["toml", '[server]\nhost = "localhost"'],
["diff", "+added"],
["patch", "-removed"],
];
for (const [info, code] of samples) {
const ext = fenceLanguageToExtension(info);
const lines = tokenizeToLines(code, ext);
expect(lines, info).not.toBeNull();
expect(
lines?.flat().some((token) => token.style !== null),
info,
).toBe(true);
}
});
});
@@ -39,9 +39,18 @@ const LANGUAGE_ALIASES: Record<string, string> = {
markdown: "md",
elixir: "ex",
terraform: "tf",
shell: "sh",
ruby: "rb",
kotlin: "kt",
powershell: "ps1",
pwsh: "ps1",
protobuf: "proto",
perl: "pl",
latex: "tex",
stex: "tex",
};
function fenceLanguageToExtension(info: string | null | undefined): string | null {
export function fenceLanguageToExtension(info: string | null | undefined): string | null {
if (!info) return null;
const first = info.trim().split(/\s+/)[0]?.toLowerCase();
if (!first) return null;
+12 -2
View File
@@ -1656,6 +1656,15 @@ function ComposerContentImpl({
});
}, []);
const handleImagesDropped = useCallback(
(images: ImageAttachment[]) => {
if (images.length === 0) return;
addImages(images);
focusInput();
},
[addImages, focusInput],
);
const handleWorkspaceFileDropped = useCallback(
(payload: WorkspaceFileDragPayload) => {
if (!workspaceId) {
@@ -1988,6 +1997,7 @@ function ComposerContentImpl({
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
return;
}
focusInput();
await uploadSelectedFiles(files);
} catch (error) {
console.error("[Composer] Failed to upload dropped files:", error);
@@ -1996,7 +2006,7 @@ function ComposerContentImpl({
);
}
},
[client, isConnected, t, uploadSelectedFiles],
[client, focusInput, isConnected, t, uploadSelectedFiles],
);
const handleRemoveAttachment = useCallback(
@@ -2544,7 +2554,7 @@ function ComposerContentImpl({
// backdrop and rejects the drop atomically, instead of accepting a drop with no feedback.
useFileDrop(
{
onFiles: addImages,
onFiles: handleImagesDropped,
onGenericFiles: handleGenericFilesDropped,
onWorkspaceFile: handleWorkspaceFileDropped,
},
+121 -1
View File
@@ -1,6 +1,15 @@
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
// eslint-disable-next-line no-restricted-imports -- verify plugin runtime does not leak raw ReactNative.
import * as ReactNative from "react-native";
import { describe, expect, it } from "vitest";
import { useRevealedText } from "@/hooks/use-revealed-text";
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
import {
OMITTED_REACT_NATIVE_EXPORTS,
createPluginReactNativeRuntime,
runPluginClientBundle,
type PluginClientRuntime,
} from "./evaluate";
const runtime = {
paseo: {},
@@ -909,6 +918,117 @@ describe("evaluatePluginClientBundle", () => {
),
).toThrow("setup exploded");
});
it("omits PushNotificationIOS, default, and non-enumerable getters while keeping other exports lazy", () => {
let platformReads = 0;
let pushReads = 0;
let nativeModulesReads = 0;
let asyncStorageReads = 0;
const raw = {
get Platform() {
platformReads += 1;
return { OS: "ios" };
},
get PushNotificationIOS() {
pushReads += 1;
throw new Error("`new NativeEventEmitter()` requires a non-null argument.");
},
get NativeModules() {
nativeModulesReads += 1;
return { CustomModule: true };
},
};
const interopNamespace = Object.defineProperties(
{},
{
Platform: Object.getOwnPropertyDescriptor(raw, "Platform")!,
PushNotificationIOS: Object.getOwnPropertyDescriptor(raw, "PushNotificationIOS")!,
NativeModules: Object.getOwnPropertyDescriptor(raw, "NativeModules")!,
AsyncStorage: {
configurable: true,
enumerable: false,
get() {
asyncStorageReads += 1;
throw new Error("AsyncStorage has been removed from react-native core.");
},
},
default: { enumerable: true, value: raw },
},
);
const safe = createPluginReactNativeRuntime(interopNamespace);
expect(platformReads).toBe(0);
expect(pushReads).toBe(0);
expect(nativeModulesReads).toBe(0);
expect(asyncStorageReads).toBe(0);
expect(Object.getOwnPropertyNames(safe)).toEqual(["Platform", "NativeModules"]);
expect("PushNotificationIOS" in safe).toBe(false);
expect("AsyncStorage" in safe).toBe(false);
expect("default" in safe).toBe(false);
expect(Object.assign({}, safe)).toEqual({
Platform: { OS: "ios" },
NativeModules: { CustomModule: true },
});
expect(platformReads).toBe(1);
expect(nativeModulesReads).toBe(1);
expect(pushReads).toBe(0);
expect(asyncStorageReads).toBe(0);
});
it("wires require('react-native') to the filtered runtime instead of the raw namespace", () => {
let exposed: Record<string, unknown> | undefined;
const plugin = evaluatePluginClientBundle(
"rn-safe",
`(function(require) {
const rn = require("react-native");
return {
default: function(plugin) {
plugin.addSurface("probe", function() { return null; });
globalThis.__testPluginRn = rn;
return function() {};
},
};
})`,
);
exposed = (globalThis as Record<string, unknown>).__testPluginRn as
| Record<string, unknown>
| undefined;
delete (globalThis as Record<string, unknown>).__testPluginRn;
expect(plugin.id).toBe("rn-safe");
expect(exposed).toBeDefined();
expect(exposed).not.toBe(ReactNative);
const expectedKeys = Object.keys(ReactNative)
.filter((key) => !OMITTED_REACT_NATIVE_EXPORTS.has(key))
.sort();
expect(Object.getOwnPropertyNames(exposed!).sort()).toEqual(expectedKeys);
expect("PushNotificationIOS" in exposed!).toBe(false);
expect("default" in exposed!).toBe(false);
expect(exposed!.Platform).toBe(ReactNative.Platform);
expect(exposed!.NativeModules).toBe(ReactNative.NativeModules);
});
it("excludes PushNotificationIOS and checks enumerable react-native/index.js getters for invariant throws", () => {
const require = createRequire(import.meta.url);
const rnIndexPath = require.resolve("react-native/index.js");
const rnIndexSource = readFileSync(rnIndexPath, "utf8");
const getterBodies = new Map<string, string>();
const getterPattern = /get\s+([A-Za-z0-9_$]+)\s*\(\)\s*\{([\s\S]*?)\n\s*\},/g;
for (const match of rnIndexSource.matchAll(getterPattern)) {
getterBodies.set(match[1]!, match[2]!);
}
expect(getterBodies.size).toBeGreaterThan(0);
expect(getterBodies.has("PushNotificationIOS")).toBe(true);
expect(OMITTED_REACT_NATIVE_EXPORTS.has("PushNotificationIOS")).toBe(true);
for (const [name, body] of getterBodies) {
if (OMITTED_REACT_NATIVE_EXPORTS.has(name)) continue;
expect(body, `throwing enumerable getter ${name} in react-native/index.js`).not.toContain(
"invariant(",
);
}
});
});
it("binds imported getters to each originating installation across delayed callbacks", async () => {
+24 -1
View File
@@ -123,6 +123,29 @@ export type PluginClientRuntime = Pick<
// The 0.12 entry exposed the reveal hook as well as UI components.
const pluginReactNativeCompatRuntime = { ...pluginUiRuntime, useRevealedText };
// PushNotificationIOS crashes iOS fatally via Metro's guardedLoadModule ->
// RCTExceptionsManager.reportFatal because RCTPushNotificationManager is not linked
// in Expo builds, bypassing PluginRegistry's try/catch. Omit it and raw `default`
// while preserving all other enumerable react-native exports as lazy descriptors.
export const OMITTED_REACT_NATIVE_EXPORTS = new Set(["PushNotificationIOS", "default"]);
export function createPluginReactNativeRuntime(
source: Record<string, unknown>,
): Record<string, unknown> {
const runtime: Record<string, unknown> = {};
for (const key of Object.keys(source)) {
if (OMITTED_REACT_NATIVE_EXPORTS.has(key)) continue;
const descriptor = Object.getOwnPropertyDescriptor(source, key);
if (!descriptor) continue;
Object.defineProperty(runtime, key, descriptor);
}
return runtime;
}
const pluginReactNativeRuntime = createPluginReactNativeRuntime(
ReactNative as unknown as Record<string, unknown>,
);
export function runPluginClientBundle(
id: string,
bundle: string,
@@ -588,7 +611,7 @@ export function runPluginClientBundle(
if (name === "@getpaseo/plugin/client/ui") return pluginUiRuntime;
if (name === "react") return React;
if (name === "react/jsx-runtime") return ReactJsxRuntime;
if (name === "react-native") return ReactNative;
if (name === "react-native") return pluginReactNativeRuntime;
if (name === "@getpaseo/plugin") return pluginSharedRuntime;
if (name === "@getpaseo/plugin/client")
return {
@@ -0,0 +1,73 @@
import { lightHighlightColors, type HighlightStyle } from "@getpaseo/highlight";
import { describe, expect, it } from "vitest";
import { appearanceStyleBoundaryKey } from "@/components/appearance-style-boundary";
import { lightTheme } from "./theme";
import { syntaxTokenStyleFor, syntaxTokenStyles } from "./syntax-token-styles";
describe("syntaxTokenStyleFor", () => {
it("maps diffAddition, diffDeletion, and meta to distinct token colors", () => {
expect(syntaxTokenStyleFor("diffAddition")).toEqual({
color: lightHighlightColors.diffAddition,
});
expect(syntaxTokenStyleFor("diffDeletion")).toEqual({
color: lightHighlightColors.diffDeletion,
});
expect(syntaxTokenStyleFor("meta")).toEqual({ color: lightHighlightColors.meta });
});
it("resolves every HighlightStyle without falling back to base", () => {
const styles: HighlightStyle[] = [
"keyword",
"comment",
"string",
"number",
"literal",
"function",
"definition",
"class",
"type",
"tag",
"attribute",
"property",
"variable",
"operator",
"punctuation",
"regexp",
"escape",
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
];
for (const style of styles) {
expect(syntaxTokenStyleFor(style)).toBe(syntaxTokenStyles[style]);
}
expect(syntaxTokenStyleFor(null)).toBe(syntaxTokenStyles.base);
expect(syntaxTokenStyleFor("unknown")).toBe(syntaxTokenStyles.base);
});
it("tracks diffAddition and diffDeletion in appearanceStyleBoundaryKey", () => {
const changedAddition = {
...lightTheme,
colors: {
...lightTheme.colors,
syntax: { ...lightTheme.colors.syntax, diffAddition: "#00ff00" },
},
};
const changedDeletion = {
...lightTheme,
colors: {
...lightTheme.colors,
syntax: { ...lightTheme.colors.syntax, diffDeletion: "#ff0000" },
},
};
expect(appearanceStyleBoundaryKey(changedAddition)).not.toBe(
appearanceStyleBoundaryKey(lightTheme),
);
expect(appearanceStyleBoundaryKey(changedDeletion)).not.toBe(
appearanceStyleBoundaryKey(lightTheme),
);
});
});
@@ -26,6 +26,8 @@ export const syntaxTokenStyles = StyleSheet.create((theme) => ({
meta: { color: theme.colors.syntax.meta },
heading: { color: theme.colors.syntax.heading },
link: { color: theme.colors.syntax.link },
diffAddition: { color: theme.colors.syntax.diffAddition },
diffDeletion: { color: theme.colors.syntax.diffDeletion },
}));
type SyntaxTokenStyleValue = (typeof syntaxTokenStyles)["base"];
@@ -9,6 +9,17 @@ describe("tokenizeToLines", () => {
expect(lines?.[0].some((token) => token.style === "keyword")).toBe(true);
});
it.each(["diff", "patch"])("tokenizes %s fences with diff roles", (lang) => {
const lines = tokenizeToLines("--- a/f.ts\n+++ b/f.ts\n@@ -1 +1 @@\n-old\n+new", lang);
expect(lines).toEqual([
[{ text: "--- a/f.ts", style: "diffDeletion" }],
[{ text: "+++ b/f.ts", style: "diffAddition" }],
[{ text: "@@ -1 +1 @@", style: "meta" }],
[{ text: "-old", style: "diffDeletion" }],
[{ text: "+new", style: "diffAddition" }],
]);
});
it("returns null when there is no filename", () => {
expect(tokenizeToLines("whatever", null)).toBeNull();
});
@@ -23,6 +23,8 @@ const allStyles: HighlightStyle[] = [
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
];
describe("darkHighlightColors", () => {
@@ -1,4 +1,4 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { setImmediate } from "node:timers/promises";
import { highlightCodeWithBudget, HIGHLIGHT_MAX_SOURCE_BYTES } from "../budgeted-highlighter.js";
import type { HighlightToken } from "../types.js";
@@ -49,6 +49,35 @@ describe("highlightCode", () => {
},
);
it("highlights Ruby code", () => {
const code = [
"class Greeter < Base",
" # say hello",
" def greet(name)",
' puts "hello #{name}" if name',
" end",
"end",
].join("\n");
const result = highlightCode(code, "greeter.rb");
expect(result).toHaveLength(6);
expect(result[0].find((t) => t.text === "class")?.style).toBe("keyword");
expect(result[1].find((t) => t.text.includes("say hello"))?.style).toBe("comment");
expect(result[2].find((t) => t.text === "def")?.style).toBe("keyword");
expect(result[3].find((t) => t.text.includes("hello"))?.style).toBe("string");
expect(result[3].find((t) => t.text === "if")?.style).toBe("keyword");
});
it("highlights extensionless Ruby files by name", () => {
const code = 'source "https://rubygems.org"\n\ngem "rails", "~> 7.1"';
for (const filename of ["Gemfile", "app/Gemfile", "tasks.rake", "app.gemspec"]) {
const result = highlightCode(code, filename);
expect(result).toHaveLength(3);
expect(result[0].find((t) => t.text.includes("rubygems"))?.style).toBe("string");
expect(result[2].find((t) => t.text.includes("rails"))?.style).toBe("string");
}
});
it("highlights Swift code", () => {
const code = 'struct Greeter {\n let message = "hello"\n}';
const result = highlightCode(code, "test.swift");
@@ -81,6 +110,236 @@ describe("highlightCode", () => {
expect(stringToken?.style).toBe("string");
});
it.each(["changes.diff", "bug.patch", "diff", "patch"])(
"highlights unified diffs for %s without trailing-whitespace warnings",
(target) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const code = [
"diff --git a/app.py b/app.py",
"index 1111111..2222222 100644",
"--- a/app.py",
"+++ b/app.py",
"@@ -1,3 +1,3 @@ def greet():",
" print('hello')",
" ",
"-old = 1 ",
"+new = 2 ",
].join("\n");
const result = highlightCode(code, target);
expect(result).toHaveLength(9);
expect(result[0]).toEqual([{ text: "diff --git a/app.py b/app.py", style: null }]);
expect(result[1]).toEqual([{ text: "index 1111111..2222222 100644", style: null }]);
expect(result[2]).toEqual([{ text: "--- a/app.py", style: "diffDeletion" }]);
expect(result[3]).toEqual([{ text: "+++ b/app.py", style: "diffAddition" }]);
expect(result[4]).toEqual([{ text: "@@ -1,3 +1,3 @@ def greet():", style: "meta" }]);
expect(result[5]).toEqual([{ text: " print('hello')", style: null }]);
expect(result[6]).toEqual([{ text: " ", style: null }]);
expect(result[7]).toEqual([{ text: "-old = 1 ", style: "diffDeletion" }]);
expect(result[8]).toEqual([{ text: "+new = 2 ", style: "diffAddition" }]);
expect(warn).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
}
},
);
it("highlights Kotlin code", () => {
const code = 'class Greeter {\n val message: String = "hello"\n}';
const result = highlightCode(code, "test.kt");
expect(result).toHaveLength(3);
const classToken = result[0].find((t) => t.text === "class");
expect(classToken?.style).toBe("keyword");
const valToken = result[1].find((t) => t.text === "val");
expect(valToken?.style).toBe("keyword");
const typeToken = result[1].find((t) => t.text === "String");
expect(typeToken?.style).toBe("type");
const stringToken = result[1].find((t) => t.text.includes("hello"));
expect(stringToken?.style).toBe("string");
});
it("highlights TOML code", () => {
const code = [
"[server]",
'host = "localhost"',
"port = 8080",
"enabled = true",
"born = 1979-05-27T07:32:00Z",
].join("\n");
const result = highlightCode(code, "config.toml");
expect(result).toHaveLength(5);
expect(result[0].find((t) => t.text === "[server]")?.style).toBe("keyword");
expect(result[1].find((t) => t.text === "host")?.style).toBe("property");
expect(result[1].find((t) => t.text === '"localhost"')?.style).toBe("string");
expect(result[2].find((t) => t.text === "port")?.style).toBe("property");
expect(result[2].find((t) => t.text === "8080")?.style).toBe("number");
expect(result[3].find((t) => t.text === "enabled")?.style).toBe("property");
expect(result[3].find((t) => t.text === "true")?.style).toBe("keyword");
expect(result[4].find((t) => t.text === "born")?.style).toBe("property");
expect(result[4].find((t) => t.text === "1979-05-27T07:32:00Z")?.style).toBe("keyword");
});
it("highlights SQL code", () => {
const code =
"-- Fetch active users\nSELECT id, name FROM users WHERE active = TRUE AND age > 18;";
const result = highlightCode(code, "query.sql");
expect(result[0][0]).toEqual({ text: "-- Fetch active users", style: "comment" });
expect(result[1]).toContainEqual({ text: "SELECT", style: "keyword" });
expect(result[1]).toContainEqual({ text: "FROM", style: "keyword" });
expect(result[1]).toContainEqual({ text: "WHERE", style: "keyword" });
});
it("highlights Lua code", () => {
const code = '-- Greeting\nlocal function greet(name)\n return "hi " .. name\nend';
const result = highlightCode(code, "script.lua");
expect(result[0][0]).toEqual({ text: "-- Greeting", style: "comment" });
expect(result[1]).toContainEqual({ text: "local", style: "keyword" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
expect(result[2].find((t) => t.text.includes("hi"))?.style).toBe("string");
});
it("highlights Protobuf definitions", () => {
const code = 'syntax = "proto3";\nmessage User {\n string id = 1;\n}';
const result = highlightCode(code, "schema.proto");
expect(result[0]).toContainEqual({ text: "syntax", style: "keyword" });
expect(result[0]).toContainEqual({ text: '"proto3"', style: "string" });
expect(result[1]).toContainEqual({ text: "message", style: "keyword" });
expect(result[2]).toContainEqual({ text: "string", style: "keyword" });
});
it.each(["deploy.ps1", "module.psm1", "manifest.psd1"])(
"highlights PowerShell in %s",
(filename) => {
const code = '# Greet\nfunction Get-Name {\n $msg = "hello"\n return $msg\n}';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Greet", style: "comment" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
expect(result[2].find((t) => t.text.includes("hello"))?.style).toBe("string");
},
);
it.each(["build.groovy", "build.gradle"])("highlights Groovy/Gradle in %s", (filename) => {
const code = '// Build\ndef version = "1.0"\nplugins {\n id "java"\n}';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "// Build", style: "comment" });
expect(result[1]).toContainEqual({ text: "def", style: "keyword" });
expect(result[1]).toContainEqual({ text: '"1.0"', style: "string" });
expect(result[3]).toContainEqual({ text: '"java"', style: "string" });
});
it.each(["Main.scala", "script.sc"])("highlights Scala in %s", (filename) => {
const code = 'case class User(name: String)\nobject Main { val msg = "hi" }';
const result = highlightCode(code, filename);
expect(result[0]).toContainEqual({ text: "case", style: "keyword" });
expect(result[0]).toContainEqual({ text: "class", style: "keyword" });
expect(result[0]).toContainEqual({ text: "String", style: "type" });
expect(result[1]).toContainEqual({ text: "object", style: "keyword" });
expect(result[1]).toContainEqual({ text: '"hi"', style: "string" });
});
it.each(["CMakeLists.txt", "app/CMakeLists.txt", "toolchain.cmake"])(
"highlights CMake in %s",
(filename) => {
const code = "# Build\ncmake_minimum_required(VERSION 3.20)\nproject(Paseo)";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Build", style: "comment" });
expect(result[1]).toContainEqual({ text: "cmake_minimum_required", style: "definition" });
expect(result[2]).toContainEqual({ text: "project", style: "definition" });
},
);
it.each(["app.properties", "config.ini", "service.conf"])(
"highlights properties/INI in %s",
(filename) => {
const code = "# Settings\n[database]\nhost = localhost";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Settings", style: "comment" });
expect(result[1]).toContainEqual({ text: "[database]", style: "heading" });
expect(result[2].some((t) => t.style !== null)).toBe(true);
},
);
it.each(["analysis.r", "analysis.R"])("highlights R in %s", (filename) => {
const code = "# Compute mean\nmean_val <- function(x) {\n return(mean(x))\n}";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Compute mean", style: "comment" });
expect(result[1]).toContainEqual({ text: "<-", style: "operator" });
expect(result[1]).toContainEqual({ text: "function", style: "keyword" });
});
it.each(["script.pl", "Module.pm"])("highlights Perl in %s", (filename) => {
const code = '# Greet\nuse strict;\nmy $name = "world";';
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "# Greet", style: "comment" });
expect(result[1]).toContainEqual({ text: "use", style: "keyword" });
expect(result[2]).toContainEqual({ text: "my", style: "definition" });
expect(result[2]).toContainEqual({ text: '"world"', style: "string" });
});
it.each(["paper.tex", "style.sty", "article.cls"])("highlights LaTeX in %s", (filename) => {
const code =
"% Header\n\\documentclass{article}\n\\begin{document}\nHello $x^2$.\n\\end{document}";
const result = highlightCode(code, filename);
expect(result[0][0]).toEqual({ text: "% Header", style: "comment" });
expect(result[1]).toContainEqual({ text: "\\documentclass", style: "tag" });
expect(result[2]).toContainEqual({ text: "\\begin", style: "tag" });
});
it.each([
"changes.diff",
"bug.patch",
"greeter.rb",
"Gemfile",
"test.kt",
"config.toml",
"query.sql",
"script.lua",
"schema.proto",
"deploy.ps1",
"build.gradle",
"Main.scala",
"CMakeLists.txt",
"config.ini",
"analysis.R",
"script.pl",
"paper.tex",
])("handles empty input and long lines cleanly in %s", (filename) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
expect(highlightCode("", filename)).toEqual([[{ text: "", style: null }]]);
const longLine = "x".repeat(5000);
const result = highlightCode(longLine, filename);
expect(result).toHaveLength(1);
expect(result[0].map((t) => t.text).join("")).toBe(longLine);
expect(warn).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
}
});
it("highlights C# code", () => {
const code = 'class Greeter {\n string message = "hello";\n}';
const result = highlightCode(code, "test.cs");
@@ -346,6 +605,8 @@ const title = "Hello";
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
null,
]);
@@ -20,11 +20,43 @@ describe("isLanguageSupported", () => {
expect(isLanguageSupported("test.java")).toBe(true);
expect(isLanguageSupported("test.swift")).toBe(true);
expect(isLanguageSupported("test.dart")).toBe(true);
expect(isLanguageSupported("changes.diff")).toBe(true);
expect(isLanguageSupported("bug.patch")).toBe(true);
expect(isLanguageSupported("diff")).toBe(true);
expect(isLanguageSupported("patch")).toBe(true);
expect(isLanguageSupported("test.kt")).toBe(true);
expect(isLanguageSupported("test.kts")).toBe(true);
expect(isLanguageSupported("test.toml")).toBe(true);
expect(isLanguageSupported("test.cs")).toBe(true);
expect(isLanguageSupported("test.nix")).toBe(true);
expect(isLanguageSupported("main.tf")).toBe(true);
expect(isLanguageSupported("prod.tfvars")).toBe(true);
expect(isLanguageSupported("terragrunt.hcl")).toBe(true);
expect(isLanguageSupported("test.rb")).toBe(true);
expect(isLanguageSupported("tasks.rake")).toBe(true);
expect(isLanguageSupported("paseo.gemspec")).toBe(true);
expect(isLanguageSupported("config.ru")).toBe(true);
expect(isLanguageSupported("query.sql")).toBe(true);
expect(isLanguageSupported("script.lua")).toBe(true);
expect(isLanguageSupported("schema.proto")).toBe(true);
expect(isLanguageSupported("deploy.ps1")).toBe(true);
expect(isLanguageSupported("module.psm1")).toBe(true);
expect(isLanguageSupported("manifest.psd1")).toBe(true);
expect(isLanguageSupported("build.groovy")).toBe(true);
expect(isLanguageSupported("build.gradle")).toBe(true);
expect(isLanguageSupported("Main.scala")).toBe(true);
expect(isLanguageSupported("script.sc")).toBe(true);
expect(isLanguageSupported("toolchain.cmake")).toBe(true);
expect(isLanguageSupported("app.properties")).toBe(true);
expect(isLanguageSupported("config.ini")).toBe(true);
expect(isLanguageSupported("service.conf")).toBe(true);
expect(isLanguageSupported("analysis.r")).toBe(true);
expect(isLanguageSupported("analysis.R")).toBe(true);
expect(isLanguageSupported("script.pl")).toBe(true);
expect(isLanguageSupported("Module.pm")).toBe(true);
expect(isLanguageSupported("paper.tex")).toBe(true);
expect(isLanguageSupported("style.sty")).toBe(true);
expect(isLanguageSupported("article.cls")).toBe(true);
expect(isLanguageSupported("test.ex")).toBe(true);
expect(isLanguageSupported("Counter.svelte")).toBe(true);
expect(isLanguageSupported("Page.astro")).toBe(true);
@@ -43,6 +75,26 @@ describe("isLanguageSupported", () => {
expect(isLanguageSupported("bin/bash")).toBe(false);
});
it("recognizes Ruby files identified by their whole name", () => {
for (const name of ["Gemfile", "Rakefile", "Guardfile", "Capfile", "Podfile", "Vagrantfile"]) {
expect(isLanguageSupported(name)).toBe(true);
expect(isLanguageSupported(`app/${name}`)).toBe(true);
expect(isLanguageSupported(`dir.with.dots/${name}`)).toBe(true);
}
expect(getLanguageForFile("Gemfile")).toBe(getLanguageForFile("app.rb"));
// Names are case-sensitive, and a lockfile is not Ruby.
expect(isLanguageSupported("gemfile")).toBe(false);
expect(isLanguageSupported("Gemfile.lock")).toBe(false);
});
it("recognizes CMakeLists.txt by exact basename", () => {
expect(isLanguageSupported("CMakeLists.txt")).toBe(true);
expect(isLanguageSupported("app/CMakeLists.txt")).toBe(true);
expect(isLanguageSupported("dir.with.dots/CMakeLists.txt")).toBe(true);
expect(getLanguageForFile("CMakeLists.txt")).toBe(getLanguageForFile("toolchain.cmake"));
expect(isLanguageSupported("cmakelists.txt")).toBe(false);
});
it("handles nested paths", () => {
expect(isLanguageSupported("src/utils/test.ts")).toBe(true);
expect(isLanguageSupported("deep/nested/path/file.py")).toBe(true);
@@ -68,11 +120,40 @@ describe("getSupportedExtensions", () => {
expect(extensions).toContain("rs");
expect(extensions).toContain("swift");
expect(extensions).toContain("dart");
expect(extensions).toContain("diff");
expect(extensions).toContain("patch");
expect(extensions).toContain("kt");
expect(extensions).toContain("kts");
expect(extensions).toContain("toml");
expect(extensions).toContain("cs");
expect(extensions).toContain("nix");
expect(extensions).toContain("tf");
expect(extensions).toContain("tfvars");
expect(extensions).toContain("hcl");
expect(extensions).toContain("rb");
expect(extensions).toContain("rake");
expect(extensions).toContain("gemspec");
expect(extensions).toContain("ru");
expect(extensions).toContain("sql");
expect(extensions).toContain("lua");
expect(extensions).toContain("proto");
expect(extensions).toContain("ps1");
expect(extensions).toContain("psm1");
expect(extensions).toContain("psd1");
expect(extensions).toContain("groovy");
expect(extensions).toContain("gradle");
expect(extensions).toContain("scala");
expect(extensions).toContain("sc");
expect(extensions).toContain("cmake");
expect(extensions).toContain("properties");
expect(extensions).toContain("ini");
expect(extensions).toContain("conf");
expect(extensions).toContain("r");
expect(extensions).toContain("pl");
expect(extensions).toContain("pm");
expect(extensions).toContain("tex");
expect(extensions).toContain("sty");
expect(extensions).toContain("cls");
expect(extensions).toContain("json");
expect(extensions).toContain("svelte");
expect(extensions).toContain("astro");
@@ -24,6 +24,8 @@ const allStyles: HighlightStyle[] = [
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
];
const colorSchemes: ("light" | "dark")[] = ["light", "dark"];
+4
View File
@@ -21,6 +21,8 @@ export const darkHighlightColors: Record<HighlightStyle, string> = {
meta: "#8b949e",
heading: "#79c0ff",
link: "#a5d6ff",
diffAddition: "#3fb950",
diffDeletion: "#f85149",
};
export const lightHighlightColors: Record<HighlightStyle, string> = {
@@ -44,4 +46,6 @@ export const lightHighlightColors: Record<HighlightStyle, string> = {
meta: "#6e7781",
heading: "#0550ae",
link: "#0a3069",
diffAddition: "#1a7f37",
diffDeletion: "#cf222e",
};
+102 -1
View File
@@ -1,8 +1,21 @@
import { defineLanguageFacet, Language, StreamLanguage } from "@codemirror/language";
import { dart } from "@codemirror/legacy-modes/mode/clike";
import { dart, kotlin, scala } from "@codemirror/legacy-modes/mode/clike";
import { cmake } from "@codemirror/legacy-modes/mode/cmake";
import { diff } from "@codemirror/legacy-modes/mode/diff";
import { dockerFile } from "@codemirror/legacy-modes/mode/dockerfile";
import { groovy } from "@codemirror/legacy-modes/mode/groovy";
import { lua } from "@codemirror/legacy-modes/mode/lua";
import { perl } from "@codemirror/legacy-modes/mode/perl";
import { powerShell } from "@codemirror/legacy-modes/mode/powershell";
import { properties } from "@codemirror/legacy-modes/mode/properties";
import { protobuf } from "@codemirror/legacy-modes/mode/protobuf";
import { r } from "@codemirror/legacy-modes/mode/r";
import { ruby } from "@codemirror/legacy-modes/mode/ruby";
import { shell } from "@codemirror/legacy-modes/mode/shell";
import { standardSQL } from "@codemirror/legacy-modes/mode/sql";
import { stex } from "@codemirror/legacy-modes/mode/stex";
import { swift } from "@codemirror/legacy-modes/mode/swift";
import { toml } from "@codemirror/legacy-modes/mode/toml";
import { parser as jsParser } from "@lezer/javascript";
import { parser as jsonParser } from "@lezer/json";
import { parser as cssParser } from "@lezer/css";
@@ -32,6 +45,25 @@ function language(parser: Parser): Language {
const shellLanguage = StreamLanguage.define(shell);
const dockerfileLanguage = StreamLanguage.define(dockerFile);
const diffLanguage = StreamLanguage.define({
...diff,
token(stream, state) {
const token = diff.token?.(stream, state) ?? null;
if (!token || token === "error") return null;
// Legacy diff mode prefixes trailing-whitespace tokens with "error ", which triggers
// CodeMirror's "Unknown highlighting tag error" warning on compound tokens.
return token.startsWith("error ") ? token.slice("error ".length) : token;
},
});
const rubyLanguage = StreamLanguage.define(ruby);
const kotlinLanguage = StreamLanguage.define(kotlin);
const scalaLanguage = StreamLanguage.define(scala);
const powerShellLanguage = StreamLanguage.define(powerShell);
const groovyLanguage = StreamLanguage.define(groovy);
const cmakeLanguage = StreamLanguage.define(cmake);
const propertiesLanguage = StreamLanguage.define(properties);
const perlLanguage = StreamLanguage.define(perl);
const stexLanguage = StreamLanguage.define(stex);
const languagesByExtension: Record<string, Language> = {
// JavaScript/TypeScript
@@ -90,6 +122,54 @@ const languagesByExtension: Record<string, Language> = {
swift: StreamLanguage.define(swift),
// Dart
dart: StreamLanguage.define(dart),
// Diff / patch (unified diff format)
diff: diffLanguage,
patch: diffLanguage,
// Ruby
rb: rubyLanguage,
rbw: rubyLanguage,
rake: rubyLanguage,
gemspec: rubyLanguage,
ru: rubyLanguage,
jbuilder: rubyLanguage,
podspec: rubyLanguage,
thor: rubyLanguage,
// Kotlin
kt: kotlinLanguage,
kts: kotlinLanguage,
// Scala
scala: scalaLanguage,
sc: scalaLanguage,
// TOML
toml: StreamLanguage.define(toml),
// SQL
sql: StreamLanguage.define(standardSQL),
// Lua
lua: StreamLanguage.define(lua),
// Protobuf
proto: StreamLanguage.define(protobuf),
// PowerShell
ps1: powerShellLanguage,
psm1: powerShellLanguage,
psd1: powerShellLanguage,
// Groovy / Gradle
groovy: groovyLanguage,
gradle: groovyLanguage,
// CMake
cmake: cmakeLanguage,
// Properties / INI
properties: propertiesLanguage,
ini: propertiesLanguage,
conf: propertiesLanguage,
// R
r: StreamLanguage.define(r),
// Perl
pl: perlLanguage,
pm: perlLanguage,
// LaTeX / TeX
tex: stexLanguage,
sty: stexLanguage,
cls: stexLanguage,
// C#
cs: csharpLanguage,
// Nix
@@ -106,11 +186,32 @@ const languagesByExtension: Record<string, Language> = {
mdx: language(markdownParser),
};
/** Exact-basename files whose whole name identifies the language, matched case-sensitively. */
const languagesByFilename = new Map<string, Language>([
// Ruby
["Gemfile", rubyLanguage],
["Rakefile", rubyLanguage],
["Guardfile", rubyLanguage],
["Capfile", rubyLanguage],
["Podfile", rubyLanguage],
["Vagrantfile", rubyLanguage],
["Brewfile", rubyLanguage],
["Berksfile", rubyLanguage],
["Thorfile", rubyLanguage],
["Fastfile", rubyLanguage],
["Appfile", rubyLanguage],
["Dangerfile", rubyLanguage],
// CMake
["CMakeLists.txt", cmakeLanguage],
]);
export function getLanguageForFile(filename: string): Language | null {
const basename = filename.slice(
Math.max(filename.lastIndexOf("/"), filename.lastIndexOf("\\")) + 1,
);
if (basename.toLowerCase() === "dockerfile") return dockerfileLanguage;
const byFilename = languagesByFilename.get(basename);
if (byFilename) return byFilename;
const dot = basename.lastIndexOf(".");
// Callers also pass bare language keys for code fences.
+2
View File
@@ -44,6 +44,8 @@ export const syntaxRoleTags: ReadonlyArray<{ tag: Tag; role: HighlightStyle }> =
{ tag: tags.heading, role: "heading" },
{ tag: tags.link, role: "link" },
{ tag: tags.url, role: "link" },
{ tag: tags.inserted, role: "diffAddition" },
{ tag: tags.deleted, role: "diffDeletion" },
];
export const staticSyntaxHighlighter = tagHighlighter(
+31 -1
View File
@@ -47,7 +47,7 @@ export const SYNTAX_THEME_OPTIONS: readonly SyntaxThemeOption[] = [
export type SyntaxColors = Record<HighlightStyle, string>;
// A compact per-theme role palette. `expandRolePalette` maps these roles onto
// all 20 HighlightStyle tokens, so every theme stays complete and internally
// all 22 HighlightStyle tokens, so every theme stays complete and internally
// consistent. GitHub keeps its own hand-tuned maps (colors.ts) for exactness
// and byte-for-byte back-compat with the previous default.
interface RolePalette {
@@ -61,6 +61,8 @@ interface RolePalette {
tag: string;
attribute: string; // attributes, properties
operator: string;
diffAddition: string;
diffDeletion: string;
}
function expandRolePalette(r: RolePalette): SyntaxColors {
@@ -85,6 +87,8 @@ function expandRolePalette(r: RolePalette): SyntaxColors {
meta: r.comment,
heading: r.function,
link: r.string,
diffAddition: r.diffAddition,
diffDeletion: r.diffDeletion,
};
}
@@ -100,6 +104,8 @@ const catppuccinLatte: RolePalette = {
tag: "#8839ef",
attribute: "#df8e1d",
operator: "#04a5e5",
diffAddition: "#348921",
diffDeletion: "#d20f39",
};
const catppuccinMocha: RolePalette = {
base: "#cdd6f4",
@@ -112,6 +118,8 @@ const catppuccinMocha: RolePalette = {
tag: "#cba6f7",
attribute: "#f9e2af",
operator: "#89dceb",
diffAddition: "#a6e3a1",
diffDeletion: "#e78284",
};
// --- Dracula (dark only) -------------------------------------------------
@@ -126,6 +134,8 @@ const dracula: RolePalette = {
tag: "#ff79c6",
attribute: "#50fa7b",
operator: "#ff79c6",
diffAddition: "#50fa7b",
diffDeletion: "#ff5555",
};
// --- Tokyo Night (Day light / Night dark) --------------------------------
@@ -140,6 +150,8 @@ const tokyoDay: RolePalette = {
tag: "#f52a65",
attribute: "#8c6c3e",
operator: "#006a83",
diffAddition: "#4a6b2b",
diffDeletion: "#d91c54",
};
const tokyoNight: RolePalette = {
base: "#c0caf5",
@@ -152,6 +164,8 @@ const tokyoNight: RolePalette = {
tag: "#f7768e",
attribute: "#e0af68",
operator: "#89ddff",
diffAddition: "#9ece6a",
diffDeletion: "#f7768e",
};
// --- One (One Light / One Dark) ------------------------------------------
@@ -166,6 +180,8 @@ const oneLight: RolePalette = {
tag: "#e45649",
attribute: "#986801",
operator: "#0184bc",
diffAddition: "#348233",
diffDeletion: "#d63b2f",
};
const oneDark: RolePalette = {
base: "#abb2bf",
@@ -178,6 +194,8 @@ const oneDark: RolePalette = {
tag: "#e06c75",
attribute: "#d19a66",
operator: "#56b6c2",
diffAddition: "#98c379",
diffDeletion: "#e06c75",
};
// --- Nord (Snow Storm light / Polar Night dark) ---------------------------
@@ -192,6 +210,8 @@ const nordLight: RolePalette = {
tag: "#5e81ac",
attribute: "#8f5e91",
operator: "#5e81ac",
diffAddition: "#4f6f3a",
diffDeletion: "#b54953",
};
const nordDark: RolePalette = {
base: "#d8dee9",
@@ -204,6 +224,8 @@ const nordDark: RolePalette = {
tag: "#81a1c1",
attribute: "#8fbcbb",
operator: "#81a1c1",
diffAddition: "#a3be8c",
diffDeletion: "#bf616a",
};
// --- Gruvbox (Light / Dark) ----------------------------------------------
@@ -218,6 +240,8 @@ const gruvboxLight: RolePalette = {
tag: "#076678",
attribute: "#b57614",
operator: "#af3a03",
diffAddition: "#79740e",
diffDeletion: "#9d0006",
};
const gruvboxDark: RolePalette = {
base: "#ebdbb2",
@@ -230,6 +254,8 @@ const gruvboxDark: RolePalette = {
tag: "#83a598",
attribute: "#fabd2f",
operator: "#fe8019",
diffAddition: "#b8bb26",
diffDeletion: "#fb4934",
};
// --- Solarized (Light / Dark — shared accents, different base/comment) ----
@@ -244,6 +270,8 @@ const solarizedLight: RolePalette = {
tag: "#268bd2",
attribute: "#b58900",
operator: "#859900",
diffAddition: "#6c7c00",
diffDeletion: "#dc322f",
};
const solarizedDark: RolePalette = {
base: "#839496",
@@ -256,6 +284,8 @@ const solarizedDark: RolePalette = {
tag: "#268bd2",
attribute: "#b58900",
operator: "#859900",
diffAddition: "#859900",
diffDeletion: "#dc322f",
};
export function isSyntaxThemeId(value: string): value is SyntaxThemeId {
+3 -1
View File
@@ -18,7 +18,9 @@ export type HighlightStyle =
| "escape"
| "meta"
| "heading"
| "link";
| "link"
| "diffAddition"
| "diffDeletion";
export interface HighlightToken {
text: string;
@@ -1,4 +1,5 @@
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { readFileSync } from "node:fs";
import { spawnProcess, terminateProcess } from "../process.js";
import { Readable, Writable } from "node:stream";
import {
@@ -41,6 +42,7 @@ import {
requireProviderCapabilities,
type ProviderCatalog,
type ProviderCapability,
type ProviderClientInfo,
type ProviderCommand,
type ProviderConfigState,
type ProviderConnectRequest,
@@ -66,6 +68,28 @@ const ADAPTER_CAPABILITIES = [
"request.cancel",
] as const;
const WARM_PROBE_IDLE_MS = 5_000;
function readPluginPackageVersion(): string {
try {
const manifest = JSON.parse(
readFileSync(new URL("../../../package.json", import.meta.url), "utf8"),
) as { version?: unknown };
if (typeof manifest.version === "string" && manifest.version.trim().length > 0) {
return manifest.version.trim();
}
} catch {
// Bundled or standalone callers without adjacent package.json fall back below.
}
return "0.0.0";
}
const DEFAULT_CLIENT_INFO: ProviderClientInfo = {
name: "paseo",
title: "Paseo",
version: readPluginPackageVersion(),
};
interface AcpBoundarySession {
runtime: AcpRuntime;
capabilities: readonly ProviderCapability[];
@@ -79,9 +103,11 @@ export async function createAcpProviderConnection(
if (!request.versions.includes(PROVIDER_PROTOCOL_VERSION)) {
throw new Error(`ACP adapter requires provider protocol ${PROVIDER_PROTOCOL_VERSION}`);
}
const clientInfo = request.clientInfo ?? DEFAULT_CLIENT_INFO;
const probe = await AcpRuntime.start({
options,
launch: request.launch,
clientInfo,
boundarySessionId: "capability-probe",
env: {},
emit: () => undefined,
@@ -101,7 +127,6 @@ export async function createAcpProviderConnection(
if (options.acpOptions?.deferTurnOnRunningTools) {
supportedCapabilities.push("prompt.steer");
}
await probe.close();
const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities);
const listeners = new Set<(event: ProviderEvent) => void>();
const sessions = new Map<string, AcpBoundarySession>();
@@ -110,6 +135,42 @@ export async function createAcpProviderConnection(
const cancellable = new Map<string, AbortController>();
let closed = false;
let closePromise: Promise<void> | null = null;
// Keep the initialized capability probe briefly so an immediate global catalog/sessions
// request reuses the already-initialized process instead of spawning a second one.
let warmProbe: { runtime: AcpRuntime; timer: ReturnType<typeof setTimeout> } | null = null;
let warmProbeClose: Promise<void> | null = null;
const disposeWarmProbe = (): Promise<void> => {
if (warmProbe) {
const { runtime, timer } = warmProbe;
warmProbe = null;
clearTimeout(timer);
warmProbeClose = runtime.close().catch(() => undefined);
}
return warmProbeClose ?? Promise.resolve();
};
const discardWarmProbe = (): void => {
void disposeWarmProbe();
};
const claimWarmProbe = (binding: {
boundarySessionId: string;
emit: (event: ProviderEvent) => void;
}): AcpRuntime | null => {
if (!warmProbe) return null;
const { runtime, timer } = warmProbe;
warmProbe = null;
clearTimeout(timer);
if (!runtime.isUsable()) {
warmProbeClose = runtime.close().catch(() => undefined);
return null;
}
runtime.rebindRequest(binding);
return runtime;
};
const warmProbeTimer = setTimeout(discardWarmProbe, WARM_PROBE_IDLE_MS);
warmProbeTimer.unref?.();
warmProbe = { runtime: probe, timer: warmProbeTimer };
const emit = (event: ProviderEvent) => {
if (closed) return;
const parsed = ProviderEventSchema.parse(event);
@@ -118,10 +179,13 @@ export async function createAcpProviderConnection(
const state: AcpConnectionState = {
options,
launch: request.launch,
clientInfo,
capabilities,
sessions,
emit,
isClosed: () => closed,
claimWarmProbe,
discardWarmProbe,
};
return {
@@ -165,13 +229,17 @@ export async function createAcpProviderConnection(
if (closePromise) return closePromise;
closed = true;
closePromise = (async () => {
const closingWarmProbe = disposeWarmProbe();
for (const controller of cancellable.values()) {
controller.abort(new Error("ACP provider connection closed"));
}
await Promise.all(inFlight);
const active = [...sessions.values()];
sessions.clear();
await Promise.all(active.map(({ runtime }) => runtime.closeSession()));
await Promise.all([
closingWarmProbe,
...active.map(({ runtime }) => runtime.closeSession()),
]);
listeners.clear();
})();
return closePromise;
@@ -181,11 +249,17 @@ export async function createAcpProviderConnection(
interface AcpConnectionState {
launch?: ProviderLaunch;
clientInfo: ProviderClientInfo;
options: RunAcpProviderOptions;
capabilities: readonly ProviderCapability[];
sessions: Map<string, AcpBoundarySession>;
emit(event: ProviderEvent): void;
isClosed(): boolean;
claimWarmProbe(binding: {
boundarySessionId: string;
emit: (event: ProviderEvent) => void;
}): AcpRuntime | null;
discardWarmProbe(): void;
}
function validateAdmission(
@@ -304,9 +378,20 @@ async function withRequestRuntime<Result>(
},
): Promise<void> {
const { signal } = request;
const runtime = await AcpRuntime.start({
signal.throwIfAborted();
let runtime: AcpRuntime | null = null;
if (request.cwd === undefined) {
runtime = state.claimWarmProbe({
boundarySessionId: request.boundarySessionId,
emit: state.emit,
});
} else {
state.discardWarmProbe();
}
runtime ??= await AcpRuntime.start({
options: state.options,
launch: state.launch,
clientInfo: state.clientInfo,
boundarySessionId: request.boundarySessionId,
cwd: request.cwd,
env: {},
@@ -331,6 +416,11 @@ async function discover(
state: AcpConnectionState,
signal: AbortSignal,
): Promise<void> {
if (input.cwd === undefined && state.options.acpOptions?.workspaceOnlyCatalog) {
state.discardWarmProbe();
state.emit({ type: "catalog", requestId: input.requestId, catalog: { models: [], modes: [] } });
return;
}
await withRequestRuntime(state, {
boundarySessionId: "catalog",
cwd: input.cwd,
@@ -387,9 +477,11 @@ async function openSession(
): Promise<void> {
if (state.sessions.has(input.sessionId))
throw new Error(`Session already exists: ${input.sessionId}`);
state.discardWarmProbe();
const runtime = await AcpRuntime.start({
options: state.options,
launch: state.launch,
clientInfo: state.clientInfo,
boundarySessionId: input.sessionId,
cwd: input.config.cwd,
env: input.config.env,
@@ -432,6 +524,7 @@ function requireSession(state: AcpConnectionState, sessionId: string): AcpBounda
interface StartRuntimeOptions {
launch?: ProviderLaunch;
clientInfo?: ProviderClientInfo;
options: RunAcpProviderOptions;
boundarySessionId: string;
cwd?: string;
@@ -594,7 +687,7 @@ class AcpRuntime {
runtime.connection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {},
clientInfo: { name: "paseo", version: "1" },
clientInfo: options.clientInfo ?? DEFAULT_CLIENT_INFO,
}),
),
options.options.acpOptions?.startupTimeoutMs ?? 10_000,
@@ -669,6 +762,21 @@ class AcpRuntime {
});
}
isUsable(): boolean {
if (this.closing || this.processFailed) return false;
if (this.child && (this.child.exitCode !== null || this.child.signalCode !== null))
return false;
return true;
}
rebindRequest(binding: {
boundarySessionId: string;
emit: (event: ProviderEvent) => void;
}): void {
this.options.boundarySessionId = binding.boundarySessionId;
this.emit = binding.emit;
}
async open(
input: Extract<ProviderInput, { type: "session.open" }>,
connectionCapabilities: readonly ProviderCapability[],
@@ -677,14 +785,7 @@ class AcpRuntime {
const mcpServers = toAcpMcpServers(input.config);
this.mcpServerNames = mcpServers.map((server) => server.name);
let nativeSessionId = readNativeSessionId(input.persistence);
const metadata: Record<string, unknown> = {
_paseo: {
systemPrompt: input.config.systemPrompt,
providerOptions: input.config.providerOptions,
toolPolicy: input.config.toolPolicy,
persist: input.config.persist,
},
};
const metadata: Record<string, unknown> = {};
for (const transformer of this.transformers) {
const prepared = transformer.sessionOpen?.({
persistence: input.persistence,
@@ -694,6 +795,7 @@ class AcpRuntime {
nativeSessionId ??= prepared?.sessionId ?? null;
Object.assign(metadata, prepared?.metadata);
}
const meta = Object.keys(metadata).length > 0 ? metadata : undefined;
let response: Pick<NewSessionResponse, "modes" | "configOptions">;
if (nativeSessionId) {
// ACP agents replay the loaded session's updates before session/load resolves,
@@ -705,7 +807,7 @@ class AcpRuntime {
sessionId: nativeSessionId,
cwd: input.config.cwd,
mcpServers,
_meta: metadata,
...(meta ? { _meta: meta } : {}),
}),
);
await this.drainNotifications();
@@ -715,7 +817,7 @@ class AcpRuntime {
this.connection.newSession({
cwd: input.config.cwd,
mcpServers,
_meta: metadata,
...(meta ? { _meta: meta } : {}),
}),
);
response = newSession;
+141 -10
View File
@@ -972,9 +972,9 @@ lines.on("line", (line) => {
}
});
it("still reports initialization failures for workspace-only global discovery", async () => {
it("short-circuits workspace-only global discovery with zero spawns", async () => {
let unavailable = false;
const { connector } = connectorHarness({
const harness = connectorHarness({
handleRequest(instance, request) {
if (unavailable && request.method === "initialize") {
instance.reject(request, "Bridge unavailable");
@@ -986,20 +986,23 @@ lines.on("line", (line) => {
const registration = runAcpProvider({
id: "workspace-acp",
label: "Workspace ACP",
connector,
connector: harness.connector,
acpOptions: { workspaceOnlyCatalog: true },
});
expect(registration.getCatalogCacheKey).toBeUndefined();
const connection = await registration.connect({ versions: [1], capabilities: [] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
unavailable = true;
const spawnsBefore = harness.instances.length;
await connection.send({ type: "catalog", requestId: "global" });
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
expect(await waitForEvent(events, (event) => event.type === "catalog")).toEqual({
type: "catalog",
requestId: "global",
error: { message: expect.stringContaining("Bridge unavailable") },
catalog: { models: [], modes: [] },
});
expect(events.some((event) => event.type === "catalog")).toBe(false);
expect(harness.instances.length).toBe(spawnsBefore);
} finally {
await connection.close();
}
@@ -1227,7 +1230,6 @@ lines.on("line", (line) => {
capabilities: ["prompt.message"],
});
expect(harness.instances).toHaveLength(1);
expect(harness.instances[0]).toMatchObject({ readsCanceled: true, writesClosed: true });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
@@ -1236,6 +1238,7 @@ lines.on("line", (line) => {
await connection.close();
expect(harness.instances).toHaveLength(2);
expect(harness.instances[0]).toMatchObject({ readsCanceled: true, writesClosed: true });
expect(harness.instances[1]).toMatchObject({ readsCanceled: true, writesClosed: true });
});
@@ -2973,7 +2976,7 @@ it("sends extension requests from discovery and configure and preserves JSON-RPC
(event) => event.type === "catalog" || event.type === "request.failed",
),
).toMatchObject({ type: "catalog", catalog: { defaultModel: "vendor-model" } });
expect(instances[1].requests).toContainEqual(
expect(instances[0].requests).toContainEqual(
expect.objectContaining({
method: "_example/catalog",
params: { scope: "all" },
@@ -2988,7 +2991,7 @@ it("sends extension requests from discovery and configure and preserves JSON-RPC
(event) => event.type === "session.ready" || event.type === "request.failed",
),
).toMatchObject({ type: "session.ready" });
expect(instances[2].requests).toContainEqual(
expect(instances[1].requests).toContainEqual(
expect.objectContaining({
method: "_example/select",
params: { model: "vendor-model" },
@@ -7431,7 +7434,11 @@ lines.on("line", (line) => {
requestId: "open-one",
error: { message: expect.stringMatching(/ENOENT/u) },
});
expect(spawned.map((child) => child.spawnargs)).toEqual([
// Closing the connection's idle capability probe on Windows spawns taskkill.exe.
const launchedArgs = spawned
.map((child) => child.spawnargs)
.filter((args) => args[0]?.toLowerCase() !== "taskkill.exe");
expect(launchedArgs).toEqual([
[missing, "--profile", "a b", process.execPath, fixture.agent],
]);
// The only start of the agent is the connection's capability probe, before the open.
@@ -7455,3 +7462,127 @@ lines.on("line", (line) => {
await connection.close();
});
});
describe("respectful ACP probing defaults and hygiene", () => {
it("defaults catalogRefresh to on_demand and supplies a global getCatalogCacheKey hashed from launch", async () => {
const registration = runAcpProvider({
id: "default-acp",
label: "Default ACP",
command: ["/usr/bin/agent", "acp"],
});
expect(registration.catalogRefresh).toBe("on_demand");
expect(registration.getCatalogCacheKey).toBeTypeOf("function");
const launchA = { command: "/usr/bin/agent", args: ["acp"], env: { B: "2", A: "1" } };
const launchAReorderedEnv = {
command: "/usr/bin/agent",
args: ["acp"],
env: { A: "1", B: "2" },
};
const launchB = { command: "/usr/bin/agent", args: ["acp", "--v2"], env: { A: "1", B: "2" } };
const launchC = { command: "/usr/bin/agent", args: ["acp"], env: { A: "1", B: "3" } };
const keyGlobal = await registration.getCatalogCacheKey!({
scope: "global",
launch: launchA,
});
const keyWorkspace = await registration.getCatalogCacheKey!({
scope: "workspace",
cwd: "/tmp/ws-1",
launch: launchAReorderedEnv,
});
const keyDifferentArgs = await registration.getCatalogCacheKey!({
scope: "global",
launch: launchB,
});
const keyDifferentEnv = await registration.getCatalogCacheKey!({
scope: "global",
launch: launchC,
});
expect(keyGlobal).toBeTruthy();
expect(keyWorkspace).toBe(keyGlobal);
expect(keyDifferentArgs).not.toBe(keyGlobal);
expect(keyDifferentEnv).not.toBe(keyGlobal);
const background = runAcpProvider({
id: "background-acp",
label: "Background ACP",
command: ["/usr/bin/agent", "acp"],
catalogRefresh: "background",
});
expect(background.catalogRefresh).toBe("background");
});
it("reuses the initialized capability probe for global discover() (1 spawn total) and cleans up on close", async () => {
const harness = connectorHarness();
const registration = runAcpProvider({
id: "warm-probe-acp",
label: "Warm Probe ACP",
connector: harness.connector,
});
const connection = await registration.connect({
versions: [1],
capabilities: [],
clientInfo: { name: "paseo", title: "Paseo", version: "0.17.5" },
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
expect(harness.instances).toHaveLength(1);
await connection.send({ type: "catalog", requestId: "global-catalog" });
expect(await waitForEvent(events, (event) => event.type === "catalog")).toMatchObject({
type: "catalog",
requestId: "global-catalog",
});
// connect() + global discover() shared the single initialized warmProbe instance.
expect(harness.instances).toHaveLength(1);
expect(countRequests(harness.instances[0]!, "initialize")).toBe(1);
expect(countRequests(harness.instances[0]!, "session/new")).toBe(1);
const initReq = harness.instances[0]!.requests.find((req) => req.method === "initialize");
expect(initReq?.params).toMatchObject({
clientInfo: { name: "paseo", title: "Paseo", version: "0.17.5" },
});
expect(harness.instances[0]).toMatchObject({ readsCanceled: true, writesClosed: true });
} finally {
await connection.close();
}
});
it("closes an unused warmProbe when connection.close() runs without discover()", async () => {
const harness = connectorHarness();
const registration = runAcpProvider({
id: "unused-warm-probe",
label: "Unused Warm Probe",
connector: harness.connector,
});
const connection = await registration.connect({ versions: [1], capabilities: [] });
expect(harness.instances).toHaveLength(1);
await connection.close();
expect(harness.instances[0]).toMatchObject({ readsCanceled: true, writesClosed: true });
});
it("omits _meta when no transformer supplies metadata and never sends _meta._paseo", async () => {
const harness = connectorHarness();
const registration = runAcpProvider({
id: "no-paseo-meta",
label: "No Paseo Meta",
connector: harness.connector,
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
const sessionInstance = harness.instances[1]!;
const newSessionReq = sessionInstance.requests.find((req) => req.method === "session/new");
expect(newSessionReq?.params).not.toHaveProperty("_meta");
} finally {
await connection.close();
}
});
});
+22 -1
View File
@@ -1,6 +1,9 @@
import { createHash } from "node:crypto";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type {
ProviderCatalog,
ProviderCatalogOptions,
ProviderCatalogRefreshMode,
ProviderCommand,
ProviderConfigState,
ProviderMode,
@@ -17,6 +20,7 @@ interface RunAcpProviderBaseOptions {
label: string;
description?: string;
icon?: string;
catalogRefresh?: ProviderCatalogRefreshMode;
acpOptions?: AcpOptions;
transformers?: readonly AcpTransformer[];
}
@@ -47,7 +51,7 @@ export type AcpConnector = () => AcpStream | Promise<AcpStream>;
export interface AcpOptions {
protocol?: "auto" | "v1";
startupTimeoutMs?: number;
/** Global discovery initializes ACP but returns an empty catalog without opening a session. */
/** Global discovery returns an empty catalog without spawning a process or opening a session. */
workspaceOnlyCatalog?: boolean;
/**
* For an agent that lists thinking options only for the selected model: discovery selects each
@@ -166,6 +170,14 @@ export interface AcpTransformer {
): AcpToolCallSnapshot;
}
function buildDefaultAcpCatalogCacheKey(options: ProviderCatalogOptions): string {
if (!options.launch) return "acp:connector";
const env = Object.entries(options.launch.env).sort(([a], [b]) => a.localeCompare(b));
return createHash("sha256")
.update(JSON.stringify(["acp:global/1", options.launch.command, options.launch.args, env]))
.digest("hex");
}
export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistration {
const hasCommand = options.command !== undefined;
const hasConnector = options.connector !== undefined;
@@ -175,12 +187,21 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra
if (options.command && (options.command.length === 0 || options.command[0].trim().length === 0)) {
throw new Error("ACP provider command must contain an executable");
}
const workspaceOnlyCatalog = options.acpOptions?.workspaceOnlyCatalog === true;
return {
id: options.id,
label: options.label,
description: options.description,
icon: options.icon,
command: options.command,
catalogRefresh: options.catalogRefresh ?? "on_demand",
...(workspaceOnlyCatalog
? {}
: {
async getCatalogCacheKey(catalogOptions) {
return buildDefaultAcpCatalogCacheKey(catalogOptions);
},
}),
// Each command-based session spawns its own process, so it can run behind that session's wrap.
...(hasCommand ? { launchWrap: true } : {}),
connect(request) {
+21
View File
@@ -29,9 +29,29 @@ export const PROVIDER_CAPABILITIES = [
export type ProviderCapability = (typeof PROVIDER_CAPABILITIES)[number];
export const ProviderCatalogRefreshModeSchema = z.enum(["background", "on_demand"]);
export type ProviderCatalogRefreshMode = z.infer<typeof ProviderCatalogRefreshModeSchema>;
export const ProviderClientInfoSchema = z
.object({
name: z.string().min(1),
title: z.string().min(1).optional(),
version: z.string().min(1),
})
.strip();
export type ProviderClientInfo = z.infer<typeof ProviderClientInfoSchema>;
export interface ProviderRegistration {
/** Activate only while agents.providers contains this provider ID, independently of enabled. */
requiresConfiguration?: boolean;
/**
* How Paseo refreshes this provider's model/mode catalog:
* - `"background"`: refreshes passively on open and on the background timer (default for direct providers).
* - `"on_demand"`: discovers once when uncached or when the binary changes, caches on disk across restarts, and skips the background timer (default for ACP providers).
*/
catalogRefresh?: ProviderCatalogRefreshMode;
/** Equal keys share discovery within this provider. Include effective configuration and execution environment. */
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
@@ -169,6 +189,7 @@ export type ProviderStatus = z.infer<typeof ProviderStatusSchema>;
export interface ProviderConnectRequest {
launch?: ProviderLaunch;
clientInfo?: ProviderClientInfo;
versions: readonly number[];
capabilities: readonly string[];
}
@@ -268,3 +268,37 @@ test.each([true, false])(
expect(decodeDiffFrame(encodeDiffFrame(frame))).toEqual(frame);
},
);
test("roundtrips diffAddition and diffDeletion run styles", () => {
const frame = {
opcode: 0x41 as const,
slot: 0,
revision: 1,
files: [
{
path: "changes.diff",
hunks: [
{
oldStart: 1,
oldCount: 1,
newStart: 1,
newCount: 1,
lines: [
{
type: "remove" as const,
content: "-old",
runs: [{ style: "diffDeletion", length: 4 }],
},
{
type: "add" as const,
content: "+new",
runs: [{ style: "diffAddition", length: 4 }],
},
],
},
],
},
],
};
expect(decodeDiffFrame(encodeDiffFrame(frame))).toEqual(frame);
});
@@ -24,6 +24,8 @@ export const DIFF_HIGHLIGHT_STYLES = [
"meta",
"heading",
"link",
"diffAddition",
"diffDeletion",
] as const;
const CHANGES = ["added", "modified", "deleted", "renamed"] as const;
const CONTENTS = ["text", "binary"] as const;
@@ -18,6 +18,8 @@ export type AgentProviderModeDefinition = Omit<AgentMode, "icon" | "colorTier">
isUnattended?: boolean;
};
export type ProviderCatalogRefreshMode = "background" | "on_demand";
// TODO: `modes` should not be static. Providers (especially ACP) report their
// own modes at runtime via session/new. We should fetch modes from the provider
// as source of truth and enrich with UI metadata (icons, colorTier) on top.
@@ -28,6 +30,7 @@ export interface AgentProviderDefinition {
/** The page that helps users set up and troubleshoot this provider. */
docsUrl?: string;
enabledByDefault?: boolean;
catalogRefresh?: ProviderCatalogRefreshMode;
defaultModeId: string | null;
modes: AgentProviderModeDefinition[];
voice?: {
@@ -228,6 +231,7 @@ export const AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [
label: "Copilot",
description: "GitHub Copilot via Agent Client Protocol with dynamic modes and session support",
docsUrl: "https://paseo.sh/docs/supported-providers/github-copilot",
catalogRefresh: "on_demand",
defaultModeId: "https://agentclientprotocol.com/protocol/session-modes#agent",
modes: COPILOT_MODES,
},
@@ -1,4 +1,12 @@
import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import {
chmodSync,
copyFileSync,
existsSync,
mkdirSync,
mkdtempSync,
rmSync,
writeFileSync,
} from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, test, vi } from "vitest";
@@ -203,6 +211,49 @@ describe("findExecutable", () => {
).resolves.toBeNull();
expect(probeExecutable).not.toHaveBeenCalled();
});
test("probe: false resolves executables without spawning them and preserves Windows WinGet fallback", async () => {
const dir = makeTempDir();
const marker = path.join(dir, "spawned.txt");
const cmdName = "paseo-no-probe-test";
const binPath =
process.platform === "win32" ? path.join(dir, `${cmdName}.cmd`) : path.join(dir, cmdName);
if (process.platform === "win32") {
writeFileSync(binPath, `@echo off\r\necho spawned > "${marker}"\r\n`, "utf8");
} else {
writeFileSync(binPath, `#!/bin/sh\necho spawned > ${JSON.stringify(marker)}\n`, "utf8");
chmodSync(binPath, 0o755);
}
const resolved = await findExecutable(cmdName, { env: { PATH: dir }, probe: false });
if (process.platform === "win32") {
expect(resolved?.toLowerCase()).toBe(binPath.toLowerCase());
} else {
expect(resolved).toBe(binPath);
}
expect(existsSync(marker)).toBe(false);
// Verify Windows WinGet package fallback works when probe: false.
const wingetRoot = makeTempDir();
const emptyPathDir = makeTempDir();
const packageDir = path.join(wingetRoot, "Microsoft", "WinGet", "Packages", "Google.Agy");
mkdirSync(packageDir, { recursive: true });
const wingetExe = path.join(packageDir, "agy.exe");
writeFileSync(wingetExe, "stub", "utf8");
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "win32", writable: true });
try {
await expect(
findExecutable("agy", {
env: { PATH: emptyPathDir, LOCALAPPDATA: wingetRoot },
probe: false,
}),
).resolves.toBe(wingetExe);
} finally {
Object.defineProperty(process, "platform", { value: originalPlatform, writable: true });
}
});
});
describe("executableExists", () => {
@@ -1,4 +1,5 @@
import { existsSync } from "node:fs";
import { constants as fsConstants, existsSync } from "node:fs";
import { access, stat } from "node:fs/promises";
import { delimiter, dirname, isAbsolute, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
@@ -35,7 +36,11 @@ function extractAbsolutePathDirs(rawPath: string | undefined): string[] {
.filter((entry) => entry.length > 0 && isAbsolute(entry));
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
async function enumerateCandidates(
name: string,
env?: ProcessEnvRecord,
probe = true,
): Promise<string[]> {
const rawPath = env?.PATH !== undefined ? env.PATH : process.env.PATH;
const absolutePathDirs = extractAbsolutePathDirs(rawPath);
if (absolutePathDirs.length === 0) {
@@ -47,7 +52,7 @@ async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promis
};
const allowedDirs = new Set(absolutePathDirs.map(normalizeDirectory));
const candidates =
process.platform !== "win32" && existsSync("/usr/bin/which")
probe && process.platform !== "win32" && existsSync("/usr/bin/which")
? await enumerateCandidatesViaSystemWhich(name, filteredEnv)
: await enumerateCandidatesViaLibrary(name, filteredEnv);
return candidates.filter((candidate) => allowedDirs.has(normalizeDirectory(dirname(candidate))));
@@ -172,39 +177,62 @@ export async function findExecutableWithoutProbing(
return candidates[0] ?? null;
}
async function isLocalExecutable(candidate: string): Promise<boolean> {
try {
const info = await stat(candidate);
if (!info.isFile()) return false;
if (process.platform !== "win32") {
await access(candidate, fsConstants.X_OK);
}
return true;
} catch {
return false;
}
}
export interface ExecutableResolutionOptions {
probeTimeoutMs?: number;
env?: ProcessEnvRecord;
/** When false, resolves using the same candidate rules (including Windows WinGet fallback) without spawning `--version`. */
probe?: boolean;
}
export async function findExecutable(
name: string,
options: number | ExecutableResolutionOptions = PROBE_TIMEOUT_MS,
): Promise<string | null> {
const { probeTimeoutMs = PROBE_TIMEOUT_MS, env } =
typeof options === "number" ? { probeTimeoutMs: options } : options;
const {
probeTimeoutMs = PROBE_TIMEOUT_MS,
env,
probe = true,
} = typeof options === "number" ? { probeTimeoutMs: options } : options;
const trimmed = name.trim();
if (!trimmed) {
return null;
}
const checkCandidate = probe
? (command: string, timeout: number) =>
probeExecutable(command, { probeTimeoutMs: timeout, env })
: (command: string) => isLocalExecutable(command);
if (process.platform === "win32") {
return windowsExecutableResolution.find(trimmed, {
enumeratePathCandidates: (command) => enumerateCandidates(command, env),
probeExecutable: (command, timeout) =>
probeExecutable(command, { probeTimeoutMs: timeout, env }),
enumeratePathCandidates: (command) => enumerateCandidates(command, env, probe),
probeExecutable: checkCandidate,
exists: existsSync,
localAppData: env?.LOCALAPPDATA,
probeTimeoutMs,
});
}
if (hasPathSeparator(trimmed)) {
return (await probeExecutable(trimmed, { probeTimeoutMs, env })) ? trimmed : null;
return (await checkCandidate(trimmed, probeTimeoutMs)) ? trimmed : null;
}
const candidates = await enumerateCandidates(trimmed, env);
const candidates = await enumerateCandidates(trimmed, env, probe);
for (const candidate of candidates) {
if (await probeExecutable(candidate, { probeTimeoutMs, env })) {
if (await checkCandidate(candidate, probeTimeoutMs)) {
return candidate;
}
}
@@ -12,6 +12,7 @@ import type {
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { AgentAttachment, ProviderInstallationInspection } from "@getpaseo/protocol/messages";
import type {
ProviderCatalogRefreshMode,
ProviderInspection,
ProviderUpdateCheck,
ProviderUpdateReport,
@@ -886,12 +887,19 @@ export interface AgentClientDiagnosticContext {
inspectInstallation(): Promise<ProviderInstallationInspection | undefined>;
}
export type AgentClientAvailability =
| { status: "available" }
| { status: "unavailable" }
| { status: "error"; message: string };
export interface AgentClient {
resolveUsageLaunch?(): Promise<
import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined
>;
readonly provider: AgentProvider;
readonly capabilities: AgentCapabilityFlags;
/** How ProviderSnapshotManager schedules and caches catalog discovery for this client. */
readonly catalogRefresh?: ProviderCatalogRefreshMode;
/** Sessions honor `AgentLaunchContext.wrap`. The provider registry sets it from the provider contract. */
supportsLaunchWrap?: boolean;
/** Throw unless the live provider runtime can apply a wrap. Plugin providers connect to learn it. */
@@ -917,6 +925,11 @@ export interface AgentClient {
* Include the execution environment and effective configuration; omit to use target identity.
* force must not affect identity. Resolve before every cache lookup. */
getCatalogCacheKey?(options: FetchCatalogOptions): Promise<string | undefined>;
/**
* Optional fingerprint (`mtimeMs:size`) of the resolved provider binary, used to invalidate
* on-disk cached catalogs for `"on_demand"` providers when the CLI changes on disk.
*/
getCatalogBinaryFingerprint?(options: FetchCatalogOptions): Promise<string | undefined>;
/**
* Discover models and modes together. Implementations may use one upstream
* process, separate upstream calls, static modes, or private helpers; callers
@@ -955,6 +968,14 @@ export interface AgentClient {
* Returns true if available, false otherwise.
*/
isAvailable(signal?: AbortSignal, options?: FetchCatalogOptions): Promise<boolean>;
/**
* Detailed availability check distinguishing a missing binary (`"unavailable"`) from an
* installed binary that fails readiness checks (`"error"` with an actionable message).
*/
checkAvailability?(
signal?: AbortSignal,
options?: FetchCatalogOptions,
): Promise<AgentClientAvailability>;
getDiagnostic?(context: AgentClientDiagnosticContext): Promise<{ diagnostic: string }>;
/**
* Installation links and the installed version. The same contract as plugin providers'
@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { PluginSessionHistory } from "./plugin-session-history.js";
import { resolve as resolvePath } from "node:path";
@@ -12,6 +13,8 @@ import {
ProviderEventSchema,
ProviderInputSchema,
ProviderStatusSchema,
type ProviderCatalogRefreshMode,
type ProviderClientInfo,
type ProviderStatus,
type ProviderInspection,
type ProviderUpdateCheck,
@@ -37,6 +40,7 @@ import {
import type {
AgentCapabilityFlags,
AgentClient,
AgentClientAvailability,
AgentClientInstallation,
AgentClientUpdateCheckContext,
AgentClientUpdateContext,
@@ -85,6 +89,29 @@ import { LaunchWrapUnsupportedError, ToolPolicyUnsupportedError } from "./provid
import type { RegisteredProviderDefinition } from "./provider-registry.js";
import { runProviderTurn } from "./providers/provider-runner.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
import { resolveDaemonVersion } from "../daemon-version.js";
let cachedPluginClientInfo: ProviderClientInfo | null = null;
function resolvePluginClientInfo(): ProviderClientInfo {
if (!cachedPluginClientInfo) {
cachedPluginClientInfo = {
name: "paseo",
title: "Paseo",
version: resolveDaemonVersion(import.meta.url),
};
}
return cachedPluginClientInfo;
}
function firstDiagnosticLine(diagnostic: string): string {
return (
diagnostic
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0) ?? diagnostic
);
}
interface Deferred<Value> {
promise: Promise<Value>;
@@ -185,7 +212,7 @@ class ProviderRuntime {
) {}
/** The launch after overrides, and where its executable resolves. */
private async resolveConfiguredLaunch() {
private async resolveConfiguredLaunch(options?: { probe?: boolean }) {
const command = this.registration.command;
if (!command) return undefined;
const launch = await resolveProviderLaunch({
@@ -195,12 +222,18 @@ class ProviderRuntime {
if (launch.source !== "override") launch.args.unshift(...command.slice(1));
const env = createProviderEnv({ runtimeSettings: this.runtimeSettings });
launch.env = env;
return { launch, env, availability: await checkProviderLaunchAvailable(launch) };
return {
launch,
env,
availability: await checkProviderLaunchAvailable(launch, undefined, options),
};
}
/** The effective launch, including when its executable does not resolve. */
private async resolveEffectiveLaunch(): Promise<ProviderInstallationLaunch | undefined> {
const configured = await this.resolveConfiguredLaunch();
private async resolveEffectiveLaunch(options?: {
probe?: boolean;
}): Promise<ProviderInstallationLaunch | undefined> {
const configured = await this.resolveConfiguredLaunch(options);
if (!configured) return undefined;
const { launch, env, availability } = configured;
if (!availability.resolvedPath)
@@ -214,7 +247,9 @@ class ProviderRuntime {
}
private async resolveLaunch(): Promise<ProviderLaunch | undefined> {
const launch = await this.resolveEffectiveLaunch();
const launch = await this.resolveEffectiveLaunch(
this.registration.status ? { probe: false } : undefined,
);
if (!launch) return undefined;
if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`);
return toProviderLaunch(launch);
@@ -268,11 +303,62 @@ class ProviderRuntime {
return rows;
}
async checkAvailability(): Promise<AgentClientAvailability> {
// When the provider owns a custom status() probe, resolve the path without running a separate
// `--version` probe first so availability runs at most one local check.
const launch = await this.resolveEffectiveLaunch(
this.registration.status ? { probe: false } : undefined,
);
if (launch && !launch.resolved) {
return { status: "unavailable" };
}
const providerLaunch = launch ? toProviderLaunch(launch) : undefined;
if (!this.registration.status) {
if (!this.registration.command) {
try {
await this.getConnection();
} catch {
return { status: "unavailable" };
}
}
return { status: "available" };
}
try {
const status = ProviderStatusSchema.parse(
await this.registration.status({ launch: providerLaunch }),
);
if (status.available) return { status: "available" };
return { status: "error", message: firstDiagnosticLine(status.diagnostic) };
} catch (error) {
return {
status: "error",
message: error instanceof Error ? error.message : String(error),
};
}
}
async binaryFingerprint(): Promise<string | undefined> {
const launch = await this.resolveEffectiveLaunch({ probe: false });
if (!launch?.resolved) return undefined;
try {
const info = await stat(launch.command);
return `${info.mtimeMs}:${info.size}`;
} catch {
return undefined;
}
}
async status(): Promise<ProviderStatus> {
try {
const launch = await this.resolveLaunch();
const launch = await this.resolveEffectiveLaunch(
this.registration.status ? { probe: false } : undefined,
);
if (launch && !launch.resolved) throw new Error(`${launch.command} not found on PATH`);
const providerLaunch = launch ? toProviderLaunch(launch) : undefined;
if (this.registration.status)
return ProviderStatusSchema.parse(await this.registration.status({ launch }));
return ProviderStatusSchema.parse(
await this.registration.status({ launch: providerLaunch }),
);
if (!this.registration.command) await this.getConnection();
return { available: true };
} catch (error) {
@@ -286,7 +372,7 @@ class ProviderRuntime {
async catalogCacheKey(options: FetchCatalogOptions): Promise<string | undefined> {
const callback = this.registration.getCatalogCacheKey;
if (!callback) return undefined;
const launch = await this.resolveEffectiveLaunch();
const launch = await this.resolveEffectiveLaunch({ probe: false });
// A missing executable gets its own catalogue, so refresh reports it unavailable instead of
// failing the key or reusing a catalogue cached while it was installed.
if (launch && !launch.resolved) return JSON.stringify(["unresolved", launch.command]);
@@ -501,6 +587,7 @@ class ProviderRuntime {
const launch = await this.resolveLaunch();
const rawConnection = await this.registration.connect({
launch,
clientInfo: resolvePluginClientInfo(),
versions: [PROVIDER_PROTOCOL_VERSION],
capabilities: PROVIDER_CAPABILITIES,
});
@@ -1067,6 +1154,7 @@ function createPluginProviderDefinition(
iconSvg: registration.icon,
docsUrl: registration.docsUrl,
requiresConfiguration: registration.requiresConfiguration,
catalogRefresh: registration.catalogRefresh,
defaultModeId: null,
modes: [],
// Each connection negotiates permission.tool_policy, so the registry lets a policy through and
@@ -1089,6 +1177,7 @@ class PluginAgentClient implements AgentClient {
private readonly rootsBySession = new Map<string, PluginAgentSession>();
private readonly pendingChildren: PendingChild[] = [];
readonly catalogRefresh?: ProviderCatalogRefreshMode;
readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"];
readonly installation?: AgentClientInstallation;
readonly supportsLaunchWrap: boolean;
@@ -1096,6 +1185,7 @@ class PluginAgentClient implements AgentClient {
constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) {
this.provider = registration.id;
this.label = registration.label;
this.catalogRefresh = registration.catalogRefresh;
this.supportsLaunchWrap = registration.launchWrap === true;
this.runtime = new ProviderRuntime(registration, runtimeSettings);
if (registration.getCatalogCacheKey)
@@ -1191,6 +1281,15 @@ class PluginAgentClient implements AgentClient {
return await this.runtime.isAvailable();
}
async checkAvailability(signal?: AbortSignal): Promise<AgentClientAvailability> {
signal?.throwIfAborted();
return await this.runtime.checkAvailability();
}
async getCatalogBinaryFingerprint(): Promise<string | undefined> {
return await this.runtime.binaryFingerprint();
}
async getDiagnostic(context: AgentClientDiagnosticContext): Promise<{ diagnostic: string }> {
const [rows, status] = await Promise.all([
this.runtime.launchDiagnosticRows(context),
@@ -0,0 +1,238 @@
import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import type { Logger } from "pino";
import { z } from "zod";
import type { AgentMode, AgentModelDefinition } from "./agent-sdk-types.js";
const CACHE_VERSION = 1 as const;
const MAX_CACHE_ENTRIES = 64;
const AgentSelectOptionSchema = z
.object({
id: z.string(),
label: z.string(),
description: z.string().optional(),
isDefault: z.boolean().optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
})
.passthrough();
const AgentModelDefinitionSchema = z
.object({
provider: z.string(),
id: z.string(),
aliases: z.array(z.string()).optional(),
isSelectable: z.boolean().optional(),
label: z.string(),
description: z.string().optional(),
isDefault: z.boolean().optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
contextWindowMaxTokens: z.number().optional(),
thinkingOptions: z.array(AgentSelectOptionSchema).optional(),
defaultThinkingOptionId: z.string().optional(),
})
.passthrough();
const AgentModeSchema = z
.object({
id: z.string(),
label: z.string(),
description: z.string().optional(),
icon: z.string().optional(),
colorTier: z.string().optional(),
isUnattended: z.boolean().optional(),
})
.passthrough();
const PersistedEntrySchema = z
.object({
fetchedAt: z.string(),
binaryFingerprint: z.string().optional(),
catalog: z
.object({
models: z.array(AgentModelDefinitionSchema),
modes: z.array(AgentModeSchema),
defaultModeId: z.string().nullable().optional(),
})
.strip(),
})
.strip();
const PersistedProviderCatalogCacheSchema = z
.object({
version: z.literal(CACHE_VERSION),
entries: z.record(z.string(), z.record(z.string(), PersistedEntrySchema)),
})
.strip();
export interface PersistedProviderCatalogEntry {
fetchedAt: string;
binaryFingerprint?: string;
catalog: {
models: AgentModelDefinition[];
modes: AgentMode[];
defaultModeId?: string | null;
};
}
/**
* Best-effort daemon-side disk cache for provider model/mode catalogs.
* Loads asynchronously without blocking the daemon event loop and writes atomically
* (temp file + rename) serialized on a single lane.
*/
export class ProviderCatalogCache {
private readonly entries = new Map<string, Map<string, PersistedProviderCatalogEntry>>();
private readonly deletedProviders = new Set<string>();
private readonly writtenKeys = new Map<string, Set<string>>();
private readonly ready: Promise<void>;
private writeLane: Promise<void> = Promise.resolve();
constructor(
private readonly filePath: string,
private readonly logger: Logger,
) {
this.ready = this.loadFromDisk();
}
async get(provider: string, key: string): Promise<PersistedProviderCatalogEntry | undefined> {
await this.ready;
const entry = this.entries.get(provider)?.get(key);
return entry ? structuredClone(entry) : undefined;
}
set(provider: string, key: string, entry: PersistedProviderCatalogEntry): void {
this.deletedProviders.delete(provider);
let keys = this.writtenKeys.get(provider);
if (!keys) {
keys = new Set();
this.writtenKeys.set(provider, keys);
}
keys.add(key);
let providerEntries = this.entries.get(provider);
if (!providerEntries) {
providerEntries = new Map();
this.entries.set(provider, providerEntries);
}
providerEntries.set(key, structuredClone(entry));
this.prune();
this.scheduleWrite();
}
deleteProvider(provider: string): void {
this.deletedProviders.add(provider);
this.writtenKeys.delete(provider);
this.entries.delete(provider);
this.scheduleWrite();
}
async flush(): Promise<void> {
await this.ready;
await this.writeLane;
}
private async loadFromDisk(): Promise<void> {
let raw: string;
try {
raw = await readFile(this.filePath, "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
this.logger.warn(
{ err: error, filePath: this.filePath },
"Failed to read provider catalog cache; starting empty",
);
}
return;
}
try {
const parsed = PersistedProviderCatalogCacheSchema.safeParse(JSON.parse(raw));
if (!parsed.success) {
this.logger.warn(
{ filePath: this.filePath, issues: parsed.error.issues.length },
"Ignoring invalid provider catalog cache",
);
return;
}
for (const [provider, byKey] of Object.entries(parsed.data.entries)) {
if (this.deletedProviders.has(provider)) continue;
const written = this.writtenKeys.get(provider);
let map = this.entries.get(provider);
for (const [key, value] of Object.entries(byKey)) {
if (written?.has(key)) continue;
if (!map) {
map = new Map();
this.entries.set(provider, map);
}
map.set(key, value as PersistedProviderCatalogEntry);
}
}
this.prune();
} catch (error) {
this.logger.warn(
{ err: error, filePath: this.filePath },
"Failed to parse provider catalog cache; starting empty",
);
}
}
private prune(): void {
const all: Array<{ provider: string; key: string; fetchedAtMs: number }> = [];
for (const [provider, byKey] of this.entries) {
for (const [key, entry] of byKey) {
const parsedMs = Date.parse(entry.fetchedAt);
all.push({
provider,
key,
fetchedAtMs: Number.isFinite(parsedMs) ? parsedMs : 0,
});
}
}
if (all.length <= MAX_CACHE_ENTRIES) return;
all.sort((a, b) => a.fetchedAtMs - b.fetchedAtMs);
const excess = all.length - MAX_CACHE_ENTRIES;
for (let index = 0; index < excess; index += 1) {
const target = all[index]!;
const byKey = this.entries.get(target.provider);
byKey?.delete(target.key);
if (byKey && byKey.size === 0) this.entries.delete(target.provider);
}
}
private snapshotJson(): string {
const entries: Record<string, Record<string, PersistedProviderCatalogEntry>> = {};
for (const [provider, byKey] of this.entries) {
if (byKey.size === 0) continue;
entries[provider] = Object.fromEntries(byKey.entries());
}
return `${JSON.stringify({ version: CACHE_VERSION, entries }, null, 2)}\n`;
}
private scheduleWrite(): void {
this.writeLane = this.writeLane
.then(() => this.ready)
.then(() => this.writeAtomically(this.snapshotJson()))
.catch((error) => {
this.logger.warn(
{ err: error, filePath: this.filePath },
"Failed to persist provider catalog cache",
);
});
}
private async writeAtomically(payload: string): Promise<void> {
const dir = dirname(this.filePath);
await mkdir(dir, { recursive: true });
const tmpPath = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
try {
await writeFile(tmpPath, payload, { encoding: "utf8", mode: 0o600 });
await rename(tmpPath, this.filePath);
} catch (error) {
await unlink(tmpPath).catch(() => undefined);
throw error;
}
}
}
@@ -65,12 +65,16 @@ function normalizeLaunchDefault(
return defaultBinary;
}
async function resolveLaunchPath(command: string, env?: ProcessEnvRecord): Promise<string | null> {
const found = await findExecutable(command, { env });
async function resolveLaunchPath(
command: string,
env?: ProcessEnvRecord,
options?: { probe?: boolean },
): Promise<string | null> {
const found = await findExecutable(command, { env, probe: options?.probe });
if (found) {
return found;
}
if (isAbsolute(command)) {
if (options?.probe !== false && isAbsolute(command)) {
return executableExists(command);
}
return null;
@@ -78,10 +82,11 @@ async function resolveLaunchPath(command: string, env?: ProcessEnvRecord): Promi
async function resolveDefaultLaunchPath(
defaultBinary: ProviderLaunchDefault,
options?: { probe?: boolean },
): Promise<string | null> {
return defaultBinary.resolvePath
? await defaultBinary.resolvePath()
: await resolveLaunchPath(defaultBinary.command);
: await resolveLaunchPath(defaultBinary.command, undefined, options);
}
export interface ResolveProviderLaunchOptions {
@@ -117,11 +122,12 @@ export async function resolveProviderLaunch({
export async function checkProviderLaunchAvailable(
launch: ResolvedProviderLaunch,
defaultBinary?: ProviderLaunchDefault,
options?: { probe?: boolean },
): Promise<ProviderLaunchAvailability> {
const resolvedPath =
defaultBinary && launch.source !== "override"
? await resolveDefaultLaunchPath(defaultBinary)
: await resolveLaunchPath(launch.command, launch.env);
? await resolveDefaultLaunchPath(defaultBinary, options)
: await resolveLaunchPath(launch.command, launch.env, options);
return {
available: resolvedPath !== null,
resolvedPath,
@@ -95,6 +95,18 @@ export interface ProviderDefinition extends AgentProviderDefinition {
client?: AgentClient,
context?: ProviderRefreshContext,
) => Promise<ProviderCatalog>;
/**
* Discovers the provider's raw catalog before applying static config overlays
* (`models`, `additionalModels`, mode icons/colors). `discovered: false` indicates
* the catalog came purely from static config without invoking the provider runtime.
*/
fetchRawCatalog?: (
options: FetchCatalogOptions,
client?: AgentClient,
context?: ProviderRefreshContext,
) => Promise<{ catalog: ProviderCatalog; discovered: boolean }>;
/** Applies static provider config overlays (`models`, `additionalModels`, mode metadata). */
applyCatalogConfig?: (catalog: ProviderCatalog) => ProviderCatalog;
}
/** Provider metadata and an unconfigured factory; the registry owns override application. */
@@ -507,6 +519,25 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
} satisfies ForwardedAgentSession;
}
function bindClientDirectMethods(inner: AgentClient) {
return {
shutdown: inner.shutdown?.bind(inner),
resolveCreateConfig: inner.resolveCreateConfig?.bind(inner),
resolveConfiguredModel: inner.resolveConfiguredModel?.bind(inner),
isCreateConfigUnattended: inner.isCreateConfigUnattended?.bind(inner),
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
requireLaunchWrap: inner.requireLaunchWrap?.bind(inner),
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
getCatalogBinaryFingerprint: inner.getCatalogBinaryFingerprint?.bind(inner),
checkAvailability: inner.checkAvailability?.bind(inner),
getDiagnostic: inner.getDiagnostic?.bind(inner),
};
}
// Maps wrapped registry clients back to their unmerged provider discovery call so
// persistent catalog caches store only discovered entries and apply config overlays on load.
const rawCatalogFetchers = new WeakMap<AgentClient, AgentClient["fetchCatalog"]>();
function wrapClientProvider(
provider: AgentProvider,
inner: AgentClient,
@@ -529,13 +560,14 @@ function wrapClientProvider(
const withDefaults = (own: ProviderOptions | undefined) =>
mergeProviderOptions(configuredDefaults(), own);
return {
const wrapped: AgentClient = {
...bindClientDirectMethods(inner),
provider,
get capabilities() {
return inner.capabilities;
},
catalogRefresh: inner.catalogRefresh,
supportsLaunchWrap,
shutdown: inner.shutdown?.bind(inner),
createSession: async (config, launchContext, options) =>
wrapSessionProvider(
provider,
@@ -591,9 +623,6 @@ function wrapClientProvider(
signal,
})
: undefined,
resolveCreateConfig: inner.resolveCreateConfig?.bind(inner),
resolveConfiguredModel: inner.resolveConfiguredModel?.bind(inner),
isCreateConfigUnattended: inner.isCreateConfigUnattended?.bind(inner),
effectiveOptions: (own) => withDefaults(own) ?? {},
listControls: listControls
? async (config) =>
@@ -643,13 +672,13 @@ function wrapClientProvider(
unarchiveNativeSession: unarchiveNativeSession
? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider })
: undefined,
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
requireLaunchWrap: inner.requireLaunchWrap?.bind(inner),
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
isAvailable: (signal, options) => inner.isAvailable(signal, options),
getDiagnostic: inner.getDiagnostic?.bind(inner),
installation: inner.installation,
};
rawCatalogFetchers.set(wrapped, (options, context) =>
inner.fetchCatalog({ ...options, providerOptions: configuredDefaults() }, context),
);
return wrapped;
}
function createRegistryEntry(
@@ -682,9 +711,63 @@ function createRegistryEntry(
const hasStaticModes = resolved.definition.modes.length > 0;
const applyCatalogConfig = (catalog: ProviderCatalog): ProviderCatalog => {
if (hasReplacementModels) {
return {
...catalog,
models: mergeModelAdditions(provider, replacementModels, additionalModels),
modes: decorateModes(hasStaticModes ? resolved.definition.modes : catalog.modes),
};
}
return {
...catalog,
models: mergeModels(provider, profileModels, additionalModels, catalog.models, {
profileModelsAreAdditive: resolved.profileModelsAreAdditive,
}),
modes: decorateModes(catalog.modes),
};
};
const fetchRawCatalog = async (
options: FetchCatalogOptions,
client?: AgentClient,
context?: ProviderRefreshContext,
): Promise<{ catalog: ProviderCatalog; discovered: boolean }> => {
const catalogClient = client ?? modelClient;
if (hasReplacementModels && hasStaticModes) {
const defaultModeId = await runProviderRefreshActivity(
context,
"default-mode",
async () =>
await catalogClient.resolveDefaultModeId?.({
config: {
provider,
cwd: options.scope === "workspace" ? options.cwd : process.cwd(),
},
signal: context?.signal,
}),
);
return {
discovered: false,
catalog: {
models: [],
modes: resolved.definition.modes,
defaultModeId,
},
};
}
const rawFetch = rawCatalogFetchers.get(catalogClient);
const catalog = rawFetch
? await rawFetch(options, context)
: await catalogClient.fetchCatalog(options, context);
return { discovered: true, catalog };
};
const { createBaseClient: _createBaseClient, contract: _contract, ...configuration } = resolved;
return {
...resolved.definition,
catalogRefresh:
resolved.definition.catalogRefresh ?? modelClient.catalogRefresh ?? "background",
configuration,
enabled: resolved.enabled,
derivedFromProviderId: resolved.derivedFromProviderId,
@@ -706,49 +789,13 @@ function createRegistryEntry(
resolveCreateConfig: modelClient.resolveCreateConfig ?? resolveDefaultAgentCreateConfig,
isCreateConfigUnattended:
modelClient.isCreateConfigUnattended ?? isDefaultAgentCreateConfigUnattended,
applyCatalogConfig,
fetchRawCatalog,
fetchCatalog: async (
options: FetchCatalogOptions,
client?: AgentClient,
context?: ProviderRefreshContext,
) => {
const catalogClient = client ?? modelClient;
if (hasReplacementModels) {
// Replacement models skip runtime model discovery, but additionalModels
// must still be merged on top. If modes are dynamic, probe for modes via
// the single catalog API; otherwise use static/empty modes with no runtime.
const models = mergeModelAdditions(provider, replacementModels, additionalModels);
if (hasStaticModes) {
const defaultModeId = await runProviderRefreshActivity(
context,
"default-mode",
async () =>
await catalogClient.resolveDefaultModeId?.({
config: {
provider,
cwd: options.scope === "workspace" ? options.cwd : process.cwd(),
},
signal: context?.signal,
}),
);
return {
models,
modes: decorateModes(resolved.definition.modes),
defaultModeId,
};
}
const catalog = await catalogClient.fetchCatalog(options, context);
return { ...catalog, models, modes: decorateModes(catalog.modes) };
}
const catalog = await catalogClient.fetchCatalog(options, context);
return {
...catalog,
models: mergeModels(provider, profileModels, additionalModels, catalog.models, {
profileModelsAreAdditive: resolved.profileModelsAreAdditive,
}),
modes: decorateModes(catalog.modes),
};
},
) => applyCatalogConfig((await fetchRawCatalog(options, client, context)).catalog),
};
}
@@ -1,3 +1,4 @@
import { join } from "node:path";
import type { Logger } from "pino";
import {
@@ -31,6 +32,7 @@ export async function createAgentProviderRuntime(
try {
await bridge.start();
const snapshotManager = new ProviderSnapshotManager({
catalogCachePath: join(options.paseoHome, "cache", "provider-catalogs.json"),
...options.snapshotManager,
logger: options.logger.child({ module: "provider-snapshot-manager" }),
openCodeBridge: bridge,
@@ -416,6 +416,47 @@ describe("ProviderSnapshotManager background refresh", () => {
expect(harness.provider("codex").shutdowns).toBe(1);
});
test("skips on_demand providers while keeping background providers scheduled", async () => {
const timers = new FakeRefreshTimers();
const probes: Probe[] = [];
const createTaggedClient = (
provider: AgentProvider,
catalogRefresh?: "background" | "on_demand",
): AgentClient => {
const state: TestProvider = {
models: [model(provider, `${provider}-1`)],
available: true,
forces: [],
shutdowns: 0,
};
return {
...createClient(provider, state, () => probes.push({ minute: timers.minute, provider })),
catalogRefresh,
};
};
const enabled = new Set<AgentProvider>(["claude", "codex", "copilot", "opencode"]);
const providerOverrides = Object.fromEntries(
BUILTIN_PROVIDER_IDS.filter((id) => !enabled.has(id)).map((id) => [id, { enabled: false }]),
);
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides,
extraClients: {
claude: createTaggedClient("claude", "background"),
codex: createTaggedClient("codex"),
copilot: createTaggedClient("copilot", "on_demand"),
opencode: createTaggedClient("opencode", "on_demand"),
},
backgroundRefresh: { intervalMs: INTERVAL_MS, timers },
});
try {
await timers.advanceMinutes(75);
expect(probes.map((probe) => probe.provider)).toEqual(["claude", "codex", "claude", "codex"]);
} finally {
manager.destroy();
}
});
test("destroy and shutdown cancel the scheduled refresh", async () => {
const destroyed = createHarness({ enabled: ["codex"] });
expect(destroyed.timers.pendingCount).toBe(1);
@@ -3734,7 +3734,8 @@ describe("plugin provider overrides and launch", () => {
try {
manager.replacePluginProviders([registration]);
expect(await manager.getProvider({ provider: registration.id, wait: true })).toMatchObject({
status: "unavailable",
status: "error",
error: "Sign in to the provider",
});
expect((await manager.getProviderDiagnostic(registration.id)).diagnostic).toContain(
"Sign in to the provider",
@@ -3792,7 +3793,8 @@ describe("plugin provider overrides and launch", () => {
});
expect(manager.getAgentManagerProviderState().clients[registration.id]).not.toBe(previous);
expect(await manager.getProvider({ provider: registration.id, wait: true })).toMatchObject({
status: "unavailable",
status: "error",
error: "Sign in to the provider",
});
manager.applyMutableProviderConfig({
[registration.id]: {
@@ -13,6 +13,7 @@ import { withTimeout } from "../../utils/promise-timeout.js";
import {
filterSelectableAgentModels,
type AgentClient,
type AgentClientAvailability,
type AgentCreateConfigParent,
type AgentMode,
type AgentModelDefinition,
@@ -20,6 +21,7 @@ import {
type FetchCatalogOptions,
type ProviderSnapshotEntry,
} from "./agent-sdk-types.js";
import { ProviderCatalogCache } from "./provider-catalog-cache.js";
import {
raceProviderRefreshAbort,
runProviderRefreshWithDeadline,
@@ -133,6 +135,8 @@ export interface ProviderSnapshotManagerOptions {
refreshTimeoutMs?: number;
diagnosticTimeoutMs?: number;
openCodeBridge?: OpenCodeBridge;
/** Optional path to persist non-background provider catalogs across daemon restarts. */
catalogCachePath?: string;
/** Refreshes enabled providers in the background; omitted, catalogues refresh only on request. */
backgroundRefresh?: ProviderBackgroundRefreshOptions;
}
@@ -292,10 +296,14 @@ export class ProviderSnapshotManager {
/** Installation links and versions; separate from availability and discovery. */
readonly installations: ProviderInstallations;
private pluginProvidersSettled = false;
private readonly catalogCache: ProviderCatalogCache | null;
private readonly refreshSchedule: ProviderRefreshSchedule | null;
constructor(options: ProviderSnapshotManagerOptions) {
this.logger = options.logger;
this.catalogCache = options.catalogCachePath
? new ProviderCatalogCache(options.catalogCachePath, this.logger)
: null;
this.pluginProviders = new PluginAgentClientRegistry(
options.logger.child({ module: "plugin-providers" }),
);
@@ -336,7 +344,7 @@ export class ProviderSnapshotManager {
logger: options.logger,
})
: null;
this.refreshSchedule?.setProviders(this.getEnabledProviderIds());
this.refreshSchedule?.setProviders(this.getBackgroundRefreshProviderIds());
}
getSnapshot(cwd?: string): ProviderSnapshot {
@@ -366,8 +374,17 @@ export class ProviderSnapshotManager {
const target = createGlobalSnapshotTarget();
const homeCwd = target.snapshotCwd;
this.getOrCreateTarget(homeCwd);
for (const catalogs of this.catalogs.values()) {
// Refresh the global target first so passive workspace warmUps in flight cannot steal a
// premature stale marker on a shared provider key and spawn a duplicate probe.
await this.refreshProviders(target, providers, reason);
const refreshedGlobalKeys = new Map<AgentProvider, string | undefined>();
const globalTarget = this.targets.get(homeCwd);
for (const provider of providers) {
refreshedGlobalKeys.set(provider, globalTarget?.bindings.get(provider)?.key);
}
for (const [catalogKey, catalogs] of this.catalogs) {
for (const provider of providers) {
if (refreshedGlobalKeys.get(provider) === catalogKey) continue;
const catalog = catalogs.get(provider);
if (!catalog || (reason === "background" && catalog.load)) continue;
catalogs.set(provider, {
@@ -376,9 +393,8 @@ export class ProviderSnapshotManager {
});
}
}
// Refresh each known target: provider keys coalesce reads, while target-scoped
// providers must discover again in their own execution context.
await this.refreshProviders(target, providers, reason);
// Refresh each known workspace target: provider keys hit the freshly populated global
// catalogue above, while target-scoped providers discover again in their own context.
await Promise.all(
[...this.targets.keys()]
.filter((cwd) => cwd !== homeCwd)
@@ -809,6 +825,14 @@ export class ProviderSnapshotManager {
for (const provider of changed) {
this.generation.providerStates.get(provider)?.discoveryLimit.clearQueue();
this.usageActivityCache.delete(provider);
const before = this.generation.definitions[provider];
const after = generation.definitions[provider];
// Clear persisted disk cache when a provider is removed. Config changes that affect
// discovery (command/args/env/providerOptions) already alter the persisted cache key,
// while static model overlays (`models`/`additionalModels`) are applied live on hydration.
if (before && !after) {
this.catalogCache?.deleteProvider(provider);
}
}
this.generation = generation;
this.providerClients = clients;
@@ -821,7 +845,7 @@ export class ProviderSnapshotManager {
for (const provider of changed) target.bindings.delete(provider);
}
this.publishTargets(this.targets.keys());
this.refreshSchedule?.setProviders(this.getEnabledProviderIds());
this.refreshSchedule?.setProviders(this.getBackgroundRefreshProviderIds());
this.refreshSchedule?.recordRefresh([...changed]);
const providers = [...changed].filter((provider) => generation.definitions[provider]);
if (providers.length === 0) return;
@@ -863,7 +887,10 @@ export class ProviderSnapshotManager {
// (background processes, sockets, etc.) get a chance to release even when
// a given provider hasn't been touched yet during this daemon's lifetime.
this.getAgentManagerProviderState();
await shutdownAgentClients(this.ownedClients, this.logger);
await Promise.all([
shutdownAgentClients(this.ownedClients, this.logger),
this.catalogCache?.flush(),
]);
}
destroy(): void {
@@ -902,12 +929,15 @@ export class ProviderSnapshotManager {
if (!definition) continue;
registry[provider] = {
...definition,
catalogRefresh: client.catalogRefresh ?? definition.catalogRefresh,
createClient: () => client,
resolveCreateConfig:
client.resolveCreateConfig?.bind(client) ?? definition.resolveCreateConfig,
isCreateConfigUnattended:
client.isCreateConfigUnattended?.bind(client) ?? definition.isCreateConfigUnattended,
fetchCatalog: (options, _client, context) => client.fetchCatalog(options, context),
fetchRawCatalog: undefined,
applyCatalogConfig: undefined,
};
}
@@ -1156,7 +1186,8 @@ export class ProviderSnapshotManager {
this.publishTargets([snapshotCwd]);
if (refresh !== "manual" && catalog.load) return catalog.load;
if (!refresh && catalog.result && !catalog.stale) return;
const background = strongerRefresh(refresh, catalog.stale) === "background";
const effectiveRefresh = strongerRefresh(refresh, catalog.stale);
const background = effectiveRefresh === "background";
catalog.stale = undefined;
const current = catalog;
@@ -1168,6 +1199,8 @@ export class ProviderSnapshotManager {
if (!isCurrent()) return;
return this.trackProbe(
this.refreshProvider({
cacheKey: key,
refresh: effectiveRefresh,
catalogOptions,
provider,
definition,
@@ -1239,6 +1272,8 @@ export class ProviderSnapshotManager {
}
private async refreshProvider(options: {
cacheKey: string;
refresh?: RefreshReason;
catalogOptions: FetchCatalogOptions;
provider: AgentProvider;
definition: ProviderDefinition;
@@ -1247,6 +1282,8 @@ export class ProviderSnapshotManager {
publish: (entry: ProviderSnapshotEntry, result: { incomplete: boolean }) => boolean;
}): Promise<void> {
const {
cacheKey,
refresh,
catalogOptions,
provider,
definition,
@@ -1254,51 +1291,162 @@ export class ProviderSnapshotManager {
client,
publish: setEntry,
} = options;
const refreshMode = definition.catalogRefresh ?? "background";
const persistedCacheKey = buildPersistedCatalogKey(
cacheKey,
definition.configuration?.providerOptions,
);
const applyCatalogConfig = definition.applyCatalogConfig ?? ((catalog) => catalog);
try {
const catalog = await runProviderRefreshWithDeadline({
const outcome = await runProviderRefreshWithDeadline({
label: definition.label,
timeoutMs: this.refreshTimeoutMs,
signal: this.stopped.signal,
operation: async (context) => {
const available = await context.runActivity("availability", () =>
const availability = await context.runActivity("availability", () =>
raceProviderRefreshAbort(
context.signal,
client.isAvailable(context.signal, catalogOptions),
client.checkAvailability
? client.checkAvailability(context.signal, catalogOptions)
: client.isAvailable(context.signal, catalogOptions).then(
(available): AgentClientAvailability => ({
status: available ? "available" : "unavailable",
}),
),
),
);
if (!available) {
return null;
if (availability.status === "unavailable") {
return { kind: "unavailable" as const };
}
if (availability.status === "error") {
return { kind: "error" as const, message: availability.message };
}
return await definition.fetchCatalog(catalogOptions, client, context);
if (!refresh && refreshMode === "on_demand" && this.catalogCache) {
const persisted = await this.catalogCache.get(provider, persistedCacheKey);
if (persisted) {
const currentFingerprint = await context.runActivity("binary-fingerprint", () =>
raceProviderRefreshAbort(
context.signal,
client.getCatalogBinaryFingerprint?.(catalogOptions) ??
Promise.resolve(undefined),
),
);
const fingerprintMatches =
!persisted.binaryFingerprint ||
!currentFingerprint ||
persisted.binaryFingerprint === currentFingerprint;
if (fingerprintMatches) {
return { kind: "hydrated" as const, persisted };
}
}
}
const rawResult = definition.fetchRawCatalog
? await definition.fetchRawCatalog(catalogOptions, client, context)
: {
catalog: await definition.fetchCatalog(catalogOptions, client, context),
discovered: true,
};
const binaryFingerprint =
this.catalogCache &&
rawResult.discovered &&
rawResult.catalog.incomplete !== true &&
refreshMode === "on_demand"
? await context
.runActivity("binary-fingerprint", () =>
raceProviderRefreshAbort(
context.signal,
client.getCatalogBinaryFingerprint?.(catalogOptions) ??
Promise.resolve(undefined),
),
)
.catch(() => undefined)
: undefined;
return {
kind: "fetched" as const,
rawCatalog: rawResult.catalog,
discovered: rawResult.discovered,
binaryFingerprint,
};
},
});
if (!catalog) {
if (outcome.kind === "unavailable") {
setEntry({ ...base, status: "unavailable", enabled: true }, { incomplete: false });
return;
}
if (outcome.kind === "error") {
setEntry(
{ ...base, status: "error", enabled: true, error: outcome.message },
{ incomplete: false },
);
return;
}
if (outcome.kind === "hydrated") {
const { persisted } = outcome;
const hydratedCatalog = applyCatalogConfig(persisted.catalog);
setEntry(
{
...base,
defaultModeId:
hydratedCatalog.defaultModeId === undefined
? base.defaultModeId
: hydratedCatalog.defaultModeId,
status: "ready",
enabled: true,
models: normalizeAgentModelCatalog(hydratedCatalog.models),
modes: hydratedCatalog.modes,
fetchedAt: persisted.fetchedAt,
},
{ incomplete: false },
);
return;
}
const models = normalizeAgentModelCatalog(catalog.models);
if (models.length !== catalog.models.length) {
const { rawCatalog, discovered, binaryFingerprint } = outcome;
const configuredCatalog = applyCatalogConfig(rawCatalog);
const models = normalizeAgentModelCatalog(configuredCatalog.models);
if (models.length !== configuredCatalog.models.length) {
this.logger.warn(
{ provider, discardedRows: catalog.models.length - models.length },
{ provider, discardedRows: configuredCatalog.models.length - models.length },
"Provider catalog contains repeated model IDs; retaining the first definition",
);
}
const fetchedAt = new Date().toISOString();
setEntry(
{
...base,
defaultModeId:
catalog.defaultModeId === undefined ? base.defaultModeId : catalog.defaultModeId,
configuredCatalog.defaultModeId === undefined
? base.defaultModeId
: configuredCatalog.defaultModeId,
status: "ready",
enabled: true,
models,
modes: catalog.modes,
fetchedAt: new Date().toISOString(),
modes: configuredCatalog.modes,
fetchedAt,
},
{ incomplete: catalog.incomplete === true },
{ incomplete: configuredCatalog.incomplete === true },
);
if (
this.catalogCache &&
discovered &&
rawCatalog.incomplete !== true &&
refreshMode === "on_demand"
) {
this.catalogCache.set(provider, persistedCacheKey, {
fetchedAt,
...(binaryFingerprint ? { binaryFingerprint } : {}),
catalog: {
models: normalizeAgentModelCatalog(rawCatalog.models),
modes: rawCatalog.modes,
...(rawCatalog.defaultModeId !== undefined
? { defaultModeId: rawCatalog.defaultModeId }
: {}),
},
});
}
} catch (error) {
const emitted = setEntry(
{ ...base, status: "error", enabled: true, error: toErrorMessage(error) },
@@ -1366,10 +1514,11 @@ export class ProviderSnapshotManager {
return [...this.generation.order];
}
private getEnabledProviderIds(): AgentProvider[] {
return this.generation.order.filter(
(provider) => this.generation.definitions[provider]!.enabled,
);
private getBackgroundRefreshProviderIds(): AgentProvider[] {
return this.generation.order.filter((provider) => {
const definition = this.generation.definitions[provider]!;
return definition.enabled && (definition.catalogRefresh ?? "background") === "background";
});
}
private resolveRefreshProviders(providers?: AgentProvider[]): AgentProvider[] | undefined {
@@ -1422,6 +1571,33 @@ function createWorkspaceSnapshotTarget(cwd: string): ProviderSnapshotTarget {
};
}
function buildPersistedCatalogKey(
cacheKey: string,
providerOptions: ProviderOptions | undefined,
): string {
if (!providerOptions || Object.keys(providerOptions).length === 0) {
return cacheKey;
}
return JSON.stringify([cacheKey, canonicalizeForCacheKey(providerOptions)]);
}
function canonicalizeForCacheKey(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((item) => canonicalizeForCacheKey(item));
}
if (value && typeof value === "object") {
const sorted: Record<string, unknown> = {};
for (const key of Object.keys(value as Record<string, unknown>).sort()) {
const entry = (value as Record<string, unknown>)[key];
if (entry !== undefined) {
sorted[key] = canonicalizeForCacheKey(entry);
}
}
return sorted;
}
return value;
}
function createFetchCatalogOptions(
scope: ProviderCatalogScope,
force: boolean,
@@ -3,7 +3,7 @@ import { ACPProviderOptionsSchema } from "./acp-options.js";
import { applyProviderOptionsPatch } from "../option-controls.js";
import { assertChangesAreLive } from "../provider-options.js";
import { type ChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import { once } from "node:events";
import fs from "node:fs/promises";
import { homedir } from "node:os";
@@ -11,6 +11,8 @@ import path from "node:path";
import { Readable, Writable } from "node:stream";
import { setImmediate } from "node:timers/promises";
import type { ProviderCatalogRefreshMode } from "@getpaseo/plugin/server/provider";
import { resolveDaemonVersion } from "../../daemon-version.js";
import { terminateWithTreeKill } from "../../../utils/tree-kill.js";
import type { ProcessTerminator } from "../../../utils/tree-kill.js";
import type {
@@ -1047,8 +1049,22 @@ function isACPCreateConfigUnattended(input: AgentCreateConfigUnattendedInput): b
);
}
let cachedAcpClientInfo: { name: string; title: string; version: string } | null = null;
function resolveAcpClientInfo(): { name: string; title: string; version: string } {
if (!cachedAcpClientInfo) {
cachedAcpClientInfo = {
name: "paseo",
title: "Paseo",
version: resolveDaemonVersion(import.meta.url),
};
}
return cachedAcpClientInfo;
}
export class ACPAgentClient implements AgentClient {
readonly provider: string;
readonly catalogRefresh: ProviderCatalogRefreshMode = "on_demand";
private readonly usageProvider?: string;
readonly capabilities: AgentCapabilityFlags;
readonly resolveCreateConfig = resolveACPCreateConfig;
@@ -1542,6 +1558,64 @@ export class ACPAgentClient implements AgentClient {
});
}
async getCatalogCacheKey(_options: FetchCatalogOptions): Promise<string> {
const env = createProviderEnv({ runtimeSettings: this.runtimeSettings });
const sortedEnv = Object.entries(env).sort(([a], [b]) => a.localeCompare(b));
let command: string;
let args: string[];
try {
const prefix = await resolveProviderLaunch({
commandConfig: this.runtimeSettings?.command,
defaultBinary: this.defaultCommand[0],
});
const resolvedArgs =
prefix.source === "override"
? prefix.args
: [...prefix.args, ...this.defaultCommand.slice(1)];
const availability = await checkProviderLaunchAvailable(
{
...prefix,
env,
},
undefined,
{ probe: false },
);
command = availability.resolvedPath
? path.resolve(availability.resolvedPath)
: `unresolved:${prefix.command}`;
args = resolvedArgs;
} catch {
command = `unresolved:${this.defaultCommand[0]}`;
args = this.defaultCommand.slice(1);
}
return createHash("sha256")
.update(JSON.stringify(["acp:global/1", command, args, sortedEnv]))
.digest("hex");
}
async getCatalogBinaryFingerprint(_options: FetchCatalogOptions): Promise<string | undefined> {
try {
const env = createProviderEnv({ runtimeSettings: this.runtimeSettings });
const prefix = await resolveProviderLaunch({
commandConfig: this.runtimeSettings?.command,
defaultBinary: this.defaultCommand[0],
});
const availability = await checkProviderLaunchAvailable(
{
...prefix,
env,
},
undefined,
{ probe: false },
);
if (!availability.resolvedPath) return undefined;
const info = await fs.stat(path.resolve(availability.resolvedPath));
return `${info.mtimeMs}:${info.size}`;
} catch {
return undefined;
}
}
async isAvailable(): Promise<boolean> {
try {
await this.resolveLaunchCommand();
@@ -1702,7 +1776,7 @@ export class ACPAgentClient implements AgentClient {
this.clientCapabilityMeta,
clientCapabilities ?? this.clientCapabilities,
),
clientInfo: { name: "Paseo", version: "dev" },
clientInfo: resolveAcpClientInfo(),
}),
transport.processError,
...(initializeTimeoutPromise ? [initializeTimeoutPromise] : []),
@@ -3279,7 +3353,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.clientCapabilityMeta,
this.clientCapabilities,
),
clientInfo: { name: "Paseo", version: "dev" },
clientInfo: resolveAcpClientInfo(),
}),
processError,
]),
@@ -0,0 +1,473 @@
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { runAcpProvider } from "@getpaseo/plugin/server/acp";
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest";
import { afterEach, describe, expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { resolveDaemonVersion } from "../daemon-version.js";
import { ProviderSnapshotManager } from "./provider-snapshot-manager.js";
import { GenericACPAgentClient } from "./providers/generic-acp-agent.js";
const tempDirs: string[] = [];
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
async function createTempDir(prefix: string): Promise<string> {
const dir = await mkdtemp(path.join(tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function createFakeAcpExecutable(options: {
dir: string;
name: string;
logFile: string;
models: Array<{ value: string; name: string }>;
version?: string;
}): Promise<string> {
const filePath = path.join(options.dir, options.name);
const script = `#!/usr/bin/env node
const { appendFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
const args = process.argv.slice(2);
appendFileSync(
${JSON.stringify(options.logFile)},
JSON.stringify({ kind: "spawn", args, cwd: process.cwd() }) + "\\n",
);
if (args.includes("--version")) {
console.log(${JSON.stringify(options.version ?? "1.5.18")});
process.exit(0);
}
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
const configOptions = [
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: ${JSON.stringify(options.models[0]?.value ?? "default-model")},
options: ${JSON.stringify(options.models)},
},
{
id: "mode",
name: "Mode",
category: "mode",
type: "select",
currentValue: "default",
options: [{ value: "default", name: "Default" }],
},
];
createInterface({ input: process.stdin }).on("line", (line) => {
if (!line.trim()) return;
const msg = JSON.parse(line);
appendFileSync(
${JSON.stringify(options.logFile)},
JSON.stringify({ kind: "rpc", method: msg.method, params: msg.params }) + "\\n",
);
if (msg.method === "initialize") {
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });
} else if (msg.method === "session/new") {
send({ id: msg.id, result: { sessionId: "sess-1", configOptions } });
} else if (msg.method === "session/close") {
send({ id: msg.id, result: {} });
}
});
`;
if (process.platform === "win32") {
const scriptPath = path.join(options.dir, `${options.name}.cjs`);
await writeFile(scriptPath, script, "utf8");
const cmdPath = path.join(options.dir, `${options.name}.cmd`);
await writeFile(
cmdPath,
[
"@echo off",
`:: models=${options.models.map((m) => m.value).join(",")}`,
`"${process.execPath}" "${scriptPath}" %*`,
"",
].join("\r\n"),
"utf8",
);
return cmdPath;
}
await writeFile(filePath, script, "utf8");
await chmod(filePath, 0o755);
return filePath;
}
async function readEvents(logFile: string): Promise<Array<Record<string, unknown>>> {
try {
const content = await readFile(logFile, "utf8");
return content
.trim()
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line) as Record<string, unknown>);
} catch {
return [];
}
}
function acpSpawns(events: Array<Record<string, unknown>>) {
return events.filter(
(event) => event.kind === "spawn" && Array.isArray(event.args) && event.args.includes("acp"),
);
}
function disabledBuiltinsOverrides() {
return Object.fromEntries(BUILTIN_PROVIDER_IDS.map((id) => [id, { enabled: false }]));
}
describe("respectful ACP probing", () => {
test("plugin ACP on_demand coalesces across 3 workspaces (1 spawn), hydrates from disk on restart (0 spawns), and re-discovers when binary changes", async () => {
const dir = await createTempDir("paseo-acp-ondemand-");
const logFile = path.join(dir, "trace.ndjson");
const cachePath = path.join(dir, "cache", "provider-catalogs.json");
const binary = await createFakeAcpExecutable({
dir,
name: "fake-acp",
logFile,
models: [{ value: "model-v1", name: "Model V1" }],
});
const registration = runAcpProvider({
id: "fake-acp",
label: "Fake ACP",
command: [binary, "acp"],
});
expect(registration.catalogRefresh).toBe("on_demand");
const manager1 = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: disabledBuiltinsOverrides(),
catalogCachePath: cachePath,
});
try {
manager1.replacePluginProviders([registration]);
await Promise.all([
manager1.getProvider({ provider: "fake-acp", wait: true }),
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-1"), wait: true }),
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-2"), wait: true }),
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-3"), wait: true }),
]);
const entry1 = await manager1.getProvider({ provider: "fake-acp", wait: false });
expect(entry1).toMatchObject({
status: "ready",
models: [expect.objectContaining({ id: "model-v1", label: "Model V1" })],
});
const eventsAfterColdStart = await readEvents(logFile);
expect(acpSpawns(eventsAfterColdStart)).toHaveLength(1);
const initializeCall = eventsAfterColdStart.find(
(event) => event.kind === "rpc" && event.method === "initialize",
);
expect(initializeCall?.params).toMatchObject({
clientInfo: {
name: "paseo",
title: "Paseo",
version: resolveDaemonVersion(import.meta.url),
},
});
} finally {
await manager1.shutdown();
}
// Restart with unchanged binary -> 0 spawns, hydrates from disk cache.
const manager2 = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: disabledBuiltinsOverrides(),
catalogCachePath: cachePath,
});
try {
manager2.replacePluginProviders([registration]);
const entry2 = await manager2.getProvider({ provider: "fake-acp", wait: true });
expect(entry2).toMatchObject({
status: "ready",
models: [expect.objectContaining({ id: "model-v1", label: "Model V1" })],
});
expect(acpSpawns(await readEvents(logFile))).toHaveLength(1);
} finally {
await manager2.shutdown();
}
// Upgrade binary on disk (different size + mtime) -> re-discovers once on next start.
await createFakeAcpExecutable({
dir,
name: "fake-acp",
logFile,
models: [
{ value: "model-v1", name: "Model V1" },
{ value: "model-v2", name: "Model V2 Upgraded" },
],
});
const manager3 = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: disabledBuiltinsOverrides(),
catalogCachePath: cachePath,
});
try {
manager3.replacePluginProviders([registration]);
const entry3 = await manager3.getProvider({ provider: "fake-acp", wait: true });
expect(entry3.models?.map((model) => model.id)).toEqual(["model-v1", "model-v2"]);
expect(acpSpawns(await readEvents(logFile))).toHaveLength(2);
// Explicit manual Refresh runs 1 global spawn and updates the cache.
await manager3.refreshSettingsSnapshot({ providers: ["fake-acp"] });
expect(acpSpawns(await readEvents(logFile))).toHaveLength(3);
} finally {
await manager3.shutdown();
}
});
test("installed binary failing status() surfaces actionable error instead of Not installed, with 0 ACP spawns", async () => {
const dir = await createTempDir("paseo-acp-status-err-");
const logFile = path.join(dir, "trace.ndjson");
const cachePath = path.join(dir, "cache", "provider-catalogs.json");
const binary = await createFakeAcpExecutable({
dir,
name: "old-cli",
logFile,
models: [{ value: "m1", name: "M1" }],
});
const registration: ProviderRegistration = {
...runAcpProvider({
id: "old-cli",
label: "Old CLI",
command: [binary, "acp"],
}),
async status() {
return {
available: false,
diagnostic:
"Antigravity CLI 1.5.0 is older than 1.5.1. Update Antigravity CLI to 1.5.1 or later.\nSSH session: no",
};
},
};
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: disabledBuiltinsOverrides(),
catalogCachePath: cachePath,
});
try {
manager.replacePluginProviders([registration]);
const entry = await manager.getProvider({ provider: "old-cli", wait: true });
expect(entry).toMatchObject({
status: "error",
error:
"Antigravity CLI 1.5.0 is older than 1.5.1. Update Antigravity CLI to 1.5.1 or later.",
});
expect((await readEvents(logFile)).filter((event) => event.kind === "spawn")).toHaveLength(0);
} finally {
await manager.shutdown();
}
});
test("core server GenericACPAgentClient defaults to on_demand, global cache key, and real clientInfo", async () => {
const dir = await createTempDir("paseo-core-acp-");
const logFile = path.join(dir, "trace.ndjson");
const cachePath = path.join(dir, "cache", "provider-catalogs.json");
const binary = await createFakeAcpExecutable({
dir,
name: "core-acp",
logFile,
models: [{ value: "core-model", name: "Core Model" }],
});
const client = new GenericACPAgentClient({
logger: createTestLogger(),
command: [binary, "acp"],
providerId: "core-acp",
label: "Core ACP",
});
expect(client.catalogRefresh).toBe("on_demand");
const keyGlobal = await client.getCatalogCacheKey({ scope: "global", force: false });
const keyWs1 = await client.getCatalogCacheKey({
scope: "workspace",
cwd: path.join(dir, "ws-1"),
force: false,
});
const keyWs2 = await client.getCatalogCacheKey({
scope: "workspace",
cwd: path.join(dir, "ws-2"),
force: false,
});
expect(keyGlobal).toBeTruthy();
expect(keyWs1).toBe(keyGlobal);
expect(keyWs2).toBe(keyGlobal);
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: {
...disabledBuiltinsOverrides(),
"core-acp": {
extends: "acp",
label: "Core ACP",
command: [binary, "acp"],
},
},
catalogCachePath: cachePath,
});
try {
await Promise.all([
manager.getProvider({ provider: "core-acp", wait: true }),
manager.getProvider({ provider: "core-acp", cwd: path.join(dir, "ws-1"), wait: true }),
manager.getProvider({ provider: "core-acp", cwd: path.join(dir, "ws-2"), wait: true }),
]);
const entry = await manager.getProvider({ provider: "core-acp", wait: false });
expect(entry).toMatchObject({
status: "ready",
models: [expect.objectContaining({ id: "core-model" })],
});
const events = await readEvents(logFile);
expect(acpSpawns(events)).toHaveLength(1);
const init = events.find((event) => event.kind === "rpc" && event.method === "initialize");
expect(init?.params).toMatchObject({
clientInfo: {
name: "paseo",
title: "Paseo",
version: resolveDaemonVersion(import.meta.url),
},
});
} finally {
await manager.shutdown();
}
});
test("workspaceOnlyCatalog (hoplite-style) skips global session/new and discovers per workspace on demand", async () => {
const dir = await createTempDir("paseo-acp-hoplite-");
const logFile = path.join(dir, "trace.ndjson");
const cachePath = path.join(dir, "cache", "provider-catalogs.json");
const binary = await createFakeAcpExecutable({
dir,
name: "hoplite-acp",
logFile,
models: [{ value: "ws-model", name: "Workspace Model" }],
});
const registration = runAcpProvider({
id: "hoplite-test",
label: "Hoplite Test",
command: [binary, "acp"],
acpOptions: { workspaceOnlyCatalog: true },
});
expect(registration.catalogRefresh).toBe("on_demand");
expect(registration.getCatalogCacheKey).toBeUndefined();
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
providerOverrides: disabledBuiltinsOverrides(),
catalogCachePath: cachePath,
});
try {
manager.replacePluginProviders([registration]);
const globalEntry = await manager.getProvider({ provider: "hoplite-test", wait: true });
expect(globalEntry).toMatchObject({ status: "ready", models: [], modes: [] });
const eventsAfterGlobal = await readEvents(logFile);
expect(
eventsAfterGlobal.filter((event) => event.kind === "rpc" && event.method === "session/new"),
).toHaveLength(0);
// Workspace target discovers models for that workspace.
const ws1 = path.join(dir, "ws-1");
await mkdir(ws1, { recursive: true });
const wsEntry = await manager.getProvider({
provider: "hoplite-test",
cwd: ws1,
wait: true,
});
expect(wsEntry).toMatchObject({
status: "ready",
models: [expect.objectContaining({ id: "ws-model" })],
});
const eventsAfterWs = await readEvents(logFile);
expect(
eventsAfterWs.filter((event) => event.kind === "rpc" && event.method === "session/new"),
).toHaveLength(1);
} finally {
await manager.shutdown();
}
});
test("applies updated additionalModels and replacement models after restart without re-spawning ACP", async () => {
const dir = await createTempDir("paseo-acp-overlay-");
const logFile = path.join(dir, "trace.ndjson");
const cachePath = path.join(dir, "cache", "provider-catalogs.json");
const binary = await createFakeAcpExecutable({
dir,
name: "fake-overlay",
logFile,
models: [{ value: "model-v1", name: "Model V1" }],
});
const createRegistration = (): ProviderRegistration => ({
...runAcpProvider({
id: "fake-overlay",
label: "Fake Overlay",
command: [binary, "acp"],
}),
async status() {
return { available: true };
},
});
// Run 1: discover raw catalog with old-extra additional model.
const manager1 = new ProviderSnapshotManager({
logger: createTestLogger(),
catalogCachePath: cachePath,
providerOverrides: {
...disabledBuiltinsOverrides(),
"fake-overlay": {
additionalModels: [{ id: "old-extra", label: "Old Extra" }],
},
},
});
try {
manager1.replacePluginProviders([createRegistration()]);
const entry = await manager1.getProvider({ provider: "fake-overlay", wait: true });
expect(entry.models?.map((m) => m.id)).toEqual(["model-v1", "old-extra"]);
expect(acpSpawns(await readEvents(logFile))).toHaveLength(1);
} finally {
await manager1.shutdown();
}
// Run 2 (stopped config edit): additionalModels changed to new-extra -> 0 spawns, new overlay applied.
const manager2 = new ProviderSnapshotManager({
logger: createTestLogger(),
catalogCachePath: cachePath,
providerOverrides: {
...disabledBuiltinsOverrides(),
"fake-overlay": {
additionalModels: [{ id: "new-extra", label: "New Extra" }],
},
},
});
try {
manager2.replacePluginProviders([createRegistration()]);
const entry = await manager2.getProvider({ provider: "fake-overlay", wait: true });
expect(entry.models?.map((m) => m.id)).toEqual(["model-v1", "new-extra"]);
expect(acpSpawns(await readEvents(logFile))).toHaveLength(1);
await expect(
manager2.validateAgentConfiguration({
provider: "fake-overlay",
model: "new-extra",
}),
).resolves.toEqual([]);
} finally {
await manager2.shutdown();
}
});
});
@@ -250,17 +250,18 @@ function wrapCommonJsBundle(code: string): string {
return `(function(require) {\nconst module = { exports: {} };\nconst exports = module.exports;\n${code}\nreturn module.exports;\n})`;
}
function makeHermesInteropEager(code: string): string {
// Hermes evaluates esbuild's lazy CommonJS interop getters from a string with
function fixHermesInteropLoopBinding(code: string): string {
// Hermes evaluates esbuild's CommonJS interop getters from a string with
// the final loop binding, so every named import can resolve to the last export.
// Plugin bundles execute once and do not need live bindings from host modules.
return code.replaceAll("get: () => from[key]", "value: from[key]");
// Bind each key in its own closure while keeping host module getters lazy so
// enumerating a host namespace (such as react-native) never triggers unrelated getters.
return code.replaceAll("get: () => from[key]", "get: ((k) => () => from[k])(key)");
}
async function minifyClientBundle(code: string): Promise<string> {
const { transform } = loadEsbuild();
// Minify after the eager replace. Whitespace minify rewrites the getter this
// replace matches, and identifier minify can delete the helper entirely.
// Minify after the loop-binding rewrite. Whitespace minify rewrites the getter
// this replace matches, and identifier minify can delete the helper entirely.
const result = await transform(code, {
minifyWhitespace: true,
minifySyntax: true,
@@ -384,9 +385,9 @@ async function compileTarget(entryPath: string, target: PluginBuildTarget): Prom
checkSharedDependencies(result.metafile.inputs, pluginDirectory);
const output = result.outputFiles[0]?.text;
if (!output) throw new Error(`Plugin ${target} compilation produced no output`);
const eager = makeHermesInteropEager(output);
let prepared = eager;
if (target === "client") prepared = await minifyClientBundle(eager);
const hermesSafe = fixHermesInteropLoopBinding(output);
let prepared = hermesSafe;
if (target === "client") prepared = await minifyClientBundle(hermesSafe);
return wrapCommonJsBundle(prepared);
}
@@ -643,26 +643,37 @@ export default function contribute() { return title(" plugin "); }`;
expect(Buffer.byteLength(clientBundle)).toBeLessThan(Buffer.byteLength(serverBundle) * 0.9);
});
it("keeps distinct host exports eager when minifying in the worker", async () => {
it("keeps distinct host exports lazy with per-key closures when minifying in the worker", async () => {
const entries = await createSplitPlugin();
await writeFile(
entries.client,
`import * as host from "zod";
`import * as host from "react-native";
export default function contribute() { return [host.first, host.second]; }`,
);
const { clientBundle } = await compilePlugin({ client: entries.client, server: null });
const host = { first: "first export", second: "second export" };
expect(clientBundle).toContain("(k=>()=>from[k])(key)");
expect(clientBundle).not.toContain("value:from[key]");
let throwingReads = 0;
const host = {
first: "first export",
second: "second export",
get PushNotificationIOS() {
throwingReads += 1;
throw new Error("`new NativeEventEmitter()` requires a non-null argument.");
},
};
const factory = new Function(`return ${clientBundle}`)() as (
require: (specifier: string) => typeof host,
) => { default: () => unknown };
function requireHost(specifier: string): typeof host {
expect(specifier).toBe("zod");
expect(specifier).toBe("react-native");
return host;
}
const exports = factory(requireHost);
host.first = "changed first export";
host.second = "changed second export";
expect(throwingReads).toBe(0);
expect(exports.default()).toEqual(["first export", "second export"]);
expect(throwingReads).toBe(0);
});
it("rejects node imports from the client entry", async () => {
@@ -795,6 +795,7 @@ export class PluginService {
command: provider.command,
launchWrap: provider.launchWrap,
requiresConfiguration: provider.requiresConfiguration,
catalogRefresh: provider.catalogRefresh,
status: provider.hasStatus
? (request) => {
if (!this.runtime.getProviderStatus)
@@ -2,8 +2,9 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginHookAgent, PluginNotificationSendResult } from "@getpaseo/plugin/server";
import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage";
import type {
ProviderConnectRequest,
ProviderCatalogOptions,
ProviderCatalogRefreshMode,
ProviderConnectRequest,
ProviderEvent,
ProviderInput,
ProviderInstallationLaunch,
@@ -11,6 +12,8 @@ import type {
ProviderUpdateReport,
} from "@getpaseo/plugin/server/provider";
import {
ProviderCatalogRefreshModeSchema,
ProviderClientInfoSchema,
ProviderUpdateReportSchema,
ProviderEventSchema,
ProviderInputSchema,
@@ -20,6 +23,7 @@ import { z } from "zod";
export interface PluginProviderMetadata {
requiresConfiguration?: boolean;
catalogRefresh?: ProviderCatalogRefreshMode;
hasCatalogCacheKey?: boolean;
hasStatus?: boolean;
installation?: PluginProviderInstallationMetadata;
@@ -184,6 +188,7 @@ const providerMetadataSchema = z
iconPath: z.string().optional(),
docsUrl: z.string().optional(),
requiresConfiguration: z.boolean().optional(),
catalogRefresh: ProviderCatalogRefreshModeSchema.optional(),
hasCatalogCacheKey: z.boolean().optional(),
hasStatus: z.boolean().optional(),
installation: z
@@ -216,6 +221,7 @@ const ProviderInstallationLaunchSchema = ProviderLaunchSchema.extend({
const providerConnectRequestSchema = z
.object({
launch: ProviderLaunchSchema.optional(),
clientInfo: ProviderClientInfoSchema.optional(),
versions: z.array(z.number().int().positive()),
capabilities: z.array(z.string()),
})
@@ -33,6 +33,7 @@ import {
import { fileURLToPath } from "node:url";
import type { ZodType } from "zod";
import {
ProviderCatalogRefreshModeSchema,
ProviderEventSchema,
type ProviderConnection,
type ProviderRegistration,
@@ -210,6 +211,12 @@ export function createPluginWorker(options: {
if (typeof provider.connect !== "function") {
throw new Error(`Plugin provider ${id} must implement connect()`);
}
if (
provider.catalogRefresh !== undefined &&
!ProviderCatalogRefreshModeSchema.safeParse(provider.catalogRefresh).success
) {
throw new Error(`Invalid catalogRefresh mode for plugin provider ${id}`);
}
if (
provider.getCatalogCacheKey !== undefined &&
typeof provider.getCatalogCacheKey !== "function"
@@ -314,6 +321,7 @@ export function createPluginWorker(options: {
iconPath: provider.icon,
docsUrl: provider.docsUrl,
requiresConfiguration: provider.requiresConfiguration,
catalogRefresh: provider.catalogRefresh,
hasCatalogCacheKey: provider.getCatalogCacheKey !== undefined,
hasStatus: provider.status !== undefined,
installation: provider.installation
@@ -2388,12 +2388,27 @@ it.each(["replacement", "socket-overflow"] as const)(
expect(existsSync(drained), "terminal finished writing the overflow burst").toBe(true);
}
await waitForCondition(() => viewers.replayed(desktop), 10000);
const replayEnd = viewers.frames.findIndex(
(row) => row.frame.opcode === TerminalStreamOpcode.ReplayEnd,
);
const replay = viewers.frames
.slice(0, replayEnd)
.filter((row) => row.frame.opcode === TerminalStreamOpcode.ReplayData)
.map((row) => Buffer.from(row.frame.payload).toString("utf8"))
.join("");
expect(replay).toContain("BEFORE-LOSS");
if (loss === "socket-overflow") expect(replay).toContain("AFTER-LOSS");
if (loss === "socket-overflow") {
// The PTY finishing its write does not mean the worker has parsed it.
// When the reconnect snapshot is cut first (ConPTY on Windows lags), the
// rest must reach the viewer as live output after the replay.
const afterReplay = () =>
viewers.frames
.slice(replayEnd + 1)
.filter((row) => row.frame.opcode === TerminalStreamOpcode.Output)
.map((row) => Buffer.from(row.frame.payload).toString("utf8"))
.join("");
await waitForCondition(() => (replay + afterReplay()).includes("AFTER-LOSS"), 10000);
}
expect((await workerRecords(paseoHome)).map((worker) => worker.pid)).toEqual([record!.pid]);
session.send({ type: "input", data: "RECOVERED\r" });
await waitForCondition(() => viewers.text(desktop).includes("ECHO:RECOVERED"), 3000);
@@ -2403,7 +2418,7 @@ it.each(["replacement", "socket-overflow"] as const)(
await viewers.delivery.close();
}
},
30000,
40000,
);
it.each([true, false])(
@@ -18,39 +18,86 @@ async function launchAgent(source: string) {
await writeFile(executable, source);
return {
directory,
executable,
launch: {
command: process.execPath,
args: [executable, "acp", "--disable-telemetry"],
args: [executable, "acp"],
env: { CAPTURE: path.join(directory, "requests.ndjson") },
},
};
}
it("reports a CLI without the acp subcommand as unavailable", async () => {
const { launch } = await launchAgent(`
process.stderr.write("Unknown command: acp");
process.exitCode = 1;
`);
it("uses clean agy acp command without --disable-telemetry and on_demand catalog refresh", () => {
const provider = createAntigravityProvider();
expect(provider.command?.slice(0, 2)).toEqual(["agy", "acp"]);
expect(await provider.status!({ launch })).toMatchObject({
available: false,
diagnostic: expect.stringContaining("1.5.0"),
});
expect(provider.command).toEqual(["agy", "acp"]);
expect(provider.catalogRefresh).toBe("on_demand");
});
const minimalAcpAgent = `
const { createInterface } = require("node:readline");
createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method } = JSON.parse(line);
if (method === "initialize")
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: { protocolVersion: 1, agentCapabilities: {} } }) + "\\n");
it("rejects agy versions older than 1.5.1 without spawning agy acp", async () => {
const { launch } = await launchAgent(`
const { appendFileSync } = require("node:fs");
appendFileSync(process.env.CAPTURE, JSON.stringify(process.argv.slice(2)) + "\\n");
if (process.argv.includes("acp")) process.exit(1);
if (process.argv.includes("--version")) console.log("1.5.0");
`);
const provider = createAntigravityProvider();
expect(await provider.status!({ launch })).toEqual({
available: false,
diagnostic: [
"Antigravity CLI 1.5.0 is older than 1.5.1. Update Antigravity CLI to 1.5.1 or later (earlier versions restrict model access for ACP clients).",
"SSH session: no",
"Sign-in: can differ from agy over SSH",
].join("\n"),
});
const invocations = (await readFile(launch.env.CAPTURE, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line) as string[]);
expect(invocations).toHaveLength(1);
expect(invocations[0]).toContain("--version");
expect(invocations[0]).not.toContain("acp");
});
it("memoizes agy --version by binary stat across repeated status() checks", async () => {
const { executable, launch } = await launchAgent(`
const { appendFileSync } = require("node:fs");
appendFileSync(process.env.CAPTURE, JSON.stringify(process.argv.slice(2)) + "\\n");
if (process.argv.includes("--version")) console.log("1.5.18");
`);
const provider = createAntigravityProvider();
expect(await provider.status!({ launch })).toMatchObject({ available: true });
expect(await provider.status!({ launch })).toMatchObject({ available: true });
const beforeModify = (await readFile(launch.env.CAPTURE, "utf8")).trim().split("\n");
expect(beforeModify).toHaveLength(1);
// Modifying the binary invalidates the stat-keyed memoization.
await writeFile(
executable,
`
const { appendFileSync } = require("node:fs");
appendFileSync(process.env.CAPTURE, JSON.stringify(process.argv.slice(2)) + "\\n");
if (process.argv.includes("--version")) console.log("1.5.0");
`,
);
expect(await provider.status!({ launch })).toMatchObject({
available: false,
diagnostic: expect.stringContaining("1.5.0 is older than 1.5.1"),
});
const afterModify = (await readFile(launch.env.CAPTURE, "utf8")).trim().split("\n");
expect(afterModify).toHaveLength(2);
});
const versionedCliAgent = `
if (process.argv.includes("--version")) {
console.log("1.5.18");
process.exit(0);
}
process.exit(1);
`;
describe("diagnostic", () => {
it("says agy runs outside an SSH session when the daemon has no SSH variables", async () => {
const { launch } = await launchAgent(minimalAcpAgent);
const { launch } = await launchAgent(versionedCliAgent);
expect(await createAntigravityProvider().status!({ launch })).toEqual({
available: true,
diagnostic: "SSH session: no\nSign-in: can differ from agy over SSH",
@@ -60,7 +107,7 @@ describe("diagnostic", () => {
it.each(["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"])(
"says agy runs in an SSH session when the daemon has %s",
async (variable) => {
const { launch } = await launchAgent(minimalAcpAgent);
const { launch } = await launchAgent(versionedCliAgent);
const env = { ...launch.env, [variable]: "set" };
expect(await createAntigravityProvider().status!({ launch: { ...launch, env } })).toEqual({
available: true,
@@ -69,13 +116,13 @@ describe("diagnostic", () => {
},
);
it("says whether agy runs in an SSH session when ACP does not start", async () => {
it("says whether agy runs in an SSH session when --version fails", async () => {
const { launch } = await launchAgent(`process.exit(1);`);
const env = { ...launch.env, SSH_CONNECTION: "set" };
expect(await createAntigravityProvider().status!({ launch: { ...launch, env } })).toEqual({
available: false,
diagnostic: [
"Antigravity ACP did not start. Install Antigravity 1.5.0 or later. If you override the command, include the acp subcommand.",
"Antigravity CLI did not report its version. Install Antigravity 1.5.1 or later.",
"SSH session: yes (SSH_CONNECTION)",
"Sign-in: can differ from agy outside SSH",
].join("\n"),
@@ -156,6 +203,10 @@ it.each([true, false])(
"loads a saved stream-JSON session with ACP system prompt support %s",
async (supportsSystemPrompt) => {
const { directory, launch } = await launchAgent(`
if (process.argv.includes("--version")) {
console.log("1.5.18");
process.exit(0);
}
const { appendFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
const configOptions = [
@@ -201,6 +252,7 @@ it.each([true, false])(
expect(await provider.status!({ launch })).toMatchObject({ available: true });
const connection = await provider.connect({
launch,
clientInfo: { name: "paseo", title: "Paseo", version: "0.17.5" },
versions: [1],
capabilities: ["session.configure", "session.persistence"],
});
@@ -285,11 +337,17 @@ it.each([true, false])(
.trim()
.split("\n")
.map((line) => JSON.parse(line));
const initialize = requests.find((request) => request.method === "initialize");
expect(initialize.params.clientInfo).toEqual({
name: "paseo",
title: "Paseo",
version: "0.17.5",
});
const load = requests.find((request) => request.method === "session/load");
expect(load.params.sessionId).toBe("saved-conversation");
expect(load.params._meta.antigravity).toEqual(
expect(load.params._meta).toEqual(
supportsSystemPrompt
? { systemPrompt: { append: "A test system instruction" } }
? { antigravity: { systemPrompt: { append: "A test system instruction" } } }
: undefined,
);
} finally {
@@ -575,6 +633,7 @@ it("offers each model its own thinking options and opens Orchestrator with its d
.toMatchObject({ type: "catalog" });
const catalog = events.find((event) => event.type === "catalog");
if (catalog?.type !== "catalog") throw new Error("Expected a catalog");
expect(catalog.catalog.defaultMode).toBe("full-access");
const thinkingByModel = Object.fromEntries(
catalog.catalog.models.map((model) => [
model.id,
@@ -887,7 +946,7 @@ it("keeps a turn open for backgrounded run_command calls but not IsDaemon comman
}
});
it("runs a wrapped session as [...wrap, agy, acp, --disable-telemetry] with the session env", async () => {
it("runs a wrapped session as [...wrap, agy, acp] with the session env", async () => {
const { directory, launch: fixture } = await launchAgent(`
const { createInterface } = require("node:readline");
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
@@ -951,7 +1010,7 @@ child.on("exit", (code) => process.exit(code ?? 1));
.toMatchObject({ type: "session.ready" });
const launched = JSON.parse(await readFile(record, "utf8"));
expect(launched).toEqual({
argv: [record, process.execPath, agentScript, "acp", "--disable-telemetry"],
argv: [record, process.execPath, agentScript, "acp"],
hook: "final",
});
} finally {
+101 -19
View File
@@ -1,9 +1,10 @@
import { stat } from "node:fs/promises";
import { execCommand } from "@getpaseo/plugin/server";
import { runAcpProvider, type AcpTransformer } from "@getpaseo/plugin/server/acp";
import {
PROVIDER_PROTOCOL_VERSION,
type ProviderInstallationLaunch,
type ProviderRegistration,
import type {
ProviderInstallationLaunch,
ProviderLaunch,
ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { z } from "zod";
import { mapToolCall } from "./tool-calls.js";
@@ -68,22 +69,89 @@ const antigravity: AcpTransformer = {
},
};
const MIN_AGY_VERSION = [1, 5, 1] as const;
const MIN_AGY_VERSION_LABEL = "1.5.1";
const VERSION_CACHE_LIMIT = 32;
const agyVersionCache = new Map<string, string | undefined>();
const agyVersionInFlight = new Map<string, Promise<string | undefined>>();
function parseSemverTriplet(version: string): readonly [number, number, number] | null {
const match = /\b(\d+)\.(\d+)\.(\d+)\b/.exec(version);
if (!match) return null;
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
function isVersionAtLeast(
actual: readonly [number, number, number],
minimum: readonly [number, number, number],
): boolean {
for (let index = 0; index < 3; index += 1) {
if (actual[index]! !== minimum[index]!) return actual[index]! > minimum[index]!;
}
return true;
}
async function statSignature(filePath: string): Promise<string | null> {
try {
const info = await stat(filePath);
return `${info.mtimeMs}:${info.size}`;
} catch {
return null;
}
}
async function agyVersionCacheKey(
launch: Pick<ProviderLaunch, "command" | "args">,
prefix: readonly string[],
): Promise<string | null> {
const binarySignature = await statSignature(launch.command);
if (!binarySignature) return null;
// Wrappers or test harnesses may invoke `[node, script.cjs, "acp"]`; include the script stat
// when the first prefix arg points to an existing file so edits invalidate the cache.
const scriptSignature = prefix[0] ? await statSignature(prefix[0]) : null;
return JSON.stringify([launch.command, binarySignature, prefix, scriptSignature]);
}
/** The release `agy --version` reports, or its first line when it names no release. */
async function readAgyVersion(
launch: ProviderInstallationLaunch,
signal: AbortSignal,
launch: Pick<ProviderInstallationLaunch, "command" | "args" | "env">,
signal?: AbortSignal,
): Promise<string | undefined> {
// The launch ends with the `acp` subcommand and its flags; the version comes from the CLI itself.
const acp = launch.args.indexOf("acp");
const prefix = acp === -1 ? launch.args : launch.args.slice(0, acp);
const { stdout } = await execCommand(launch.command, [...prefix, "--version"], {
const cacheKey = await agyVersionCacheKey(launch, prefix);
if (cacheKey !== null) {
if (agyVersionCache.has(cacheKey)) {
return agyVersionCache.get(cacheKey);
}
const existing = agyVersionInFlight.get(cacheKey);
if (existing) return existing;
}
const run = execCommand(launch.command, [...prefix, "--version"], {
env: launch.env,
timeout: 5000,
maxBuffer: 8192,
signal,
}).then(({ stdout }) => {
const firstLine = stdout.trim().split("\n")[0]?.trim();
const version = /\b\d+\.\d+\.\d+\S*/.exec(stdout)?.[0] ?? (firstLine || undefined);
if (cacheKey !== null) {
if (agyVersionCache.size >= VERSION_CACHE_LIMIT) agyVersionCache.clear();
agyVersionCache.set(cacheKey, version);
}
return version;
});
const firstLine = stdout.trim().split("\n")[0]?.trim();
return /\b\d+\.\d+\.\d+\S*/.exec(stdout)?.[0] ?? (firstLine || undefined);
if (cacheKey !== null) {
agyVersionInFlight.set(cacheKey, run);
try {
return await run;
} finally {
if (agyVersionInFlight.get(cacheKey) === run) agyVersionInFlight.delete(cacheKey);
}
}
return run;
}
// agy 1.5.14 reads its sign-in from a token file when any of these is set, and from the OS keyring
@@ -107,7 +175,7 @@ export function createAntigravityProvider(): ProviderRegistration {
label: "Antigravity",
description: "Antigravity CLI on your host",
icon: "icon.svg",
command: ["agy", "acp", "--disable-telemetry"],
command: ["agy", "acp"],
acpOptions: {
// agy 1.5.14 lists thinking options for the selected model only, and none for Orchestrator.
perModelThinkingOptions: true,
@@ -155,23 +223,37 @@ export function createAntigravityProvider(): ProviderRegistration {
},
},
async status({ launch }) {
if (!launch) return { available: false, diagnostic: "Install Antigravity 1.5.0 or later." };
if (!launch) {
return {
available: false,
diagnostic: `Install Antigravity ${MIN_AGY_VERSION_LABEL} or later.`,
};
}
// A sign-in problem can stop ACP from starting, so the report says which sign-in either way.
const signIn = describeSignIn(launch.env);
let version: string | undefined;
try {
const connection = await provider.connect({
launch,
versions: [PROVIDER_PROTOCOL_VERSION],
capabilities: [],
});
await connection.close();
return { available: true, diagnostic: signIn };
version = await readAgyVersion(launch);
} catch {
return {
available: false,
diagnostic: `Antigravity ACP did not start. Install Antigravity 1.5.0 or later. If you override the command, include the acp subcommand.\n${signIn}`,
diagnostic: `Antigravity CLI did not report its version. Install Antigravity ${MIN_AGY_VERSION_LABEL} or later.\n${signIn}`,
};
}
if (!version) {
return {
available: false,
diagnostic: `Antigravity CLI did not report its version. Install Antigravity ${MIN_AGY_VERSION_LABEL} or later.\n${signIn}`,
};
}
const parsed = parseSemverTriplet(version);
if (parsed && !isVersionAtLeast(parsed, MIN_AGY_VERSION)) {
return {
available: false,
diagnostic: `Antigravity CLI ${version} is older than ${MIN_AGY_VERSION_LABEL}. Update Antigravity CLI to ${MIN_AGY_VERSION_LABEL} or later (earlier versions restrict model access for ACP clients).\n${signIn}`,
};
}
return { available: true, diagnostic: signIn };
},
};
}
@@ -14,11 +14,11 @@ Paseo runs Antigravity through the official Agent Client Protocol (`agy acp`) on
Antigravity is built into Paseo and enabled by default. You do not need a plugin or extra configuration.
1. Install the [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli) (`agy`) version 1.5.0 or later on your daemon host.
1. Install the [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli) (`agy`) version 1.5.1 or later on your daemon host.
2. Run `agy` in a terminal and sign in.
3. In Paseo, choose **Antigravity** when you start an agent.
If `agy` is outside your daemon PATH, use a [command override](/docs/custom-providers#custom-binary) and keep `acp` and `--disable-telemetry` in the arguments.
If `agy` is outside your daemon PATH, use a [command override](/docs/custom-providers#custom-binary) and keep `acp` in the arguments.
## Permissions
@@ -31,7 +31,9 @@ Paseo connects to `agy acp` and shows the permission modes that the CLI provides
| Accept edits | Antigravity approves workspace edits automatically and still asks about commands that require approval. |
| Plan | Antigravity plans before it acts. |
Scheduled runs can use **Full access** without a person to approve each tool call. Finish or stop the current turn before you switch to or from **Full access**.
Finish or stop the current turn before you switch to or from **Full access**.
Use personal Google sign-in (`oauth-personal`) for interactive sessions. For unattended or scheduled runs, configure API-key authentication (`GEMINI_API_KEY` or `agent-platform`) instead of consumer OAuth.
## Sessions and tools
@@ -47,7 +49,7 @@ In Paseo, open **Settings → Providers → Antigravity** and select **Diagnosti
### New models are missing
Paseo reads the model list from `agy` when the daemon starts and when you select **Refresh**. If your account gets new models after that, open **Settings → Providers → Antigravity** and select **Refresh**.
Paseo discovers Antigravity models and thinking levels once on first startup (or after you update the `agy` CLI) and caches the catalog on disk across daemon restarts without background polling. When your account gains new models, open **Settings → Providers → Antigravity** and select **Refresh**.
### Paseo shows different models than `agy models`
@@ -12,11 +12,11 @@ Paseo 通过你已安装的 `agy` CLI 提供的官方 Agent Client Protocol(`a
Antigravity 内置于 Paseo 且默认启用,无需安装插件或额外配置。
1. 在 daemon 主机上安装 1.5.0 或更高版本的 [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli)(`agy`)。
1. 在 daemon 主机上安装 1.5.1 或更高版本的 [Antigravity CLI](https://antigravity.google/docs/getting-started?tab=cli)(`agy`)。
2. 在终端中运行 `agy` 并登录。
3. 在 Paseo 中启动 Agent 时选择 **Antigravity**。
如果 `agy` 不在 daemon 的 PATH 中,请使用[命令覆盖](/docs/custom-providers#custom-binary),并在参数中保留 `acp` 和 `--disable-telemetry`。
如果 `agy` 不在 daemon 的 PATH 中,请使用[命令覆盖](/docs/custom-providers#custom-binary),并在参数中保留 `acp`。
## 权限 {#permissions}
@@ -29,7 +29,9 @@ Paseo 连接到 `agy acp`,并显示 CLI 提供的权限模式。**Full access*
| Accept edits | Antigravity 会自动批准工作区内的编辑,仍会询问需要审批的命令。 |
| Plan | Antigravity 先规划,再执行。 |
定时任务可以使用 **Full access**,无需人为逐次审批工具调用。切换到 **Full access** 或从该模式切换到其他模式前,请先完成或停止当前轮次。
切换到 **Full access** 或从该模式切换到其他模式前,请先完成或停止当前轮次。
个人 Google 登录(`oauth-personal`)适用于交互式会话。对于无人值守或定时任务,请配置 API 密钥认证(`GEMINI_API_KEY` 或 `agent-platform`),不要使用个人 OAuth。
## 会话和工具 {#sessions-and-tools}
@@ -45,7 +47,7 @@ Paseo 连接到 `agy acp`,并显示 CLI 提供的权限模式。**Full access*
### 缺少新模型 {#new-models-are-missing}
Paseo 在 daemon 启动时和你选择 **刷新** 时从 `agy` 读取模型列表。如果你的账号在此之后获得了新模型,请打开 **设置 → Providers → Antigravity** 并选择 **刷新**。
Paseo 会在首次启动(或升级 `agy` CLI 后)探测一次 Antigravity 的模型和思考级别,并将目录缓存到磁盘以便在 daemon 重启后复用,不会在后台定时轮询。当你的账号获得新模型时,请打开 **设置 → Providers → Antigravity** 并选择 **刷新**。
### Paseo 显示的模型与 `agy models` 不同 {#paseo-shows-different-models-than-agy-models}