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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ the [activation facade example](typescript/README.md#opt-in-activation-facade).
`activateToolExtension(context, { serverInfo, toolConfig })` returns a small
runtime handle; initialization remains deferred, not client-ready. Await
`runtime.deactivate()` for facade cleanup and existing client-stop behavior.
Optional [launch hooks](typescript/README.md#optional-launch-hooks) support
per-server inherited-environment patches and pre-start notification registration
with client-owned cleanup, without overriding `runServer` or changing settings.
It preserves caller-owned subscriptions, but does not drain every legacy
in-flight restart or isolate the module-global logger/status. Existing manual
composition remains supported.
Expand Down
53 changes: 53 additions & 0 deletions typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,59 @@ multi-tool-instance isolation. Existing low-level activation APIs remain
available unchanged for custom composition; no consumer migration or custom
lifecycle hooks are required.

## Optional launch hooks

Pass `hooks` to `activateToolExtension` or `createToolContext` for runtime-only
customization. `getLaunchEnvironment({ settings, serverId, serverName })`
synchronously returns an environment patch for each actual client-creation
attempt, not each debounced restart request. It must not mutate settings or
`process.env`. An omitted key preserves its inherited value, `''` sets an empty
value, and an explicit `undefined` removes the inherited key. Inherited names
match case-insensitively on Windows and case-sensitively elsewhere.

The patch is applied to a fresh copy of `process.env` **before** env-file merging,
debugger/built-in assignments, extra paths and finally static `extraEnvVars`.
Thus an env file can reintroduce a removed inherited key; static overrides keep
their existing precedence. A throwing hook fails that launch through the normal
creation-error path. Hooks are not part of `ToolConfig` or the Python settings
payload. Existing callers without hooks retain their environment behavior.

`configureClient({ client, settings, serverId, serverName, registerDisposable })`
registers tool-specific handlers on the new client **before** `client.start()`.
For example, add this property alongside `serverInfo` and `toolConfig` in the
activation options:

```typescript
hooks: {
configureClient: ({ client, registerDisposable }) => {
registerDisposable(client.onNotification('example/score', (score: number) => {
// Update extension-owned UI here.
}));
},
},
```

Register each returned disposable immediately, so earlier registrations can be
released if later setup throws. The callback must finish synchronously and
return no value; its `undefined` return type deliberately rejects async callbacks.
Do not start, stop or replace the client from this hook. The runtime owns client
lifetime; tool-specific UI stays owned by the extension.

Each actual client generation has an idempotent setup scope, separate from
post-start state listeners. It is closed on setup/start/trace failure, retirement
after an old stop settles or replacement takes ownership, missing-interpreter
retirement, and shutdown. Registrations added to an already closed scope are
disposed immediately. Cleanup errors are contained. Shutdown closes scopes even
while creation/start is pending; it still does not promise to interrupt or drain
every in-flight lifecycle operation. A late successful start is stopped.

Lower-level `restartServer` callers can pass the same hooks and an optional
shutdown `signal`. Its returned `disposables` include the setup scope. The optional
`clientSetup` result property identifies that same scope for custom composition
that needs to retire it separately from state listeners; it is not an additional
resource to dispose twice. `createServer` alone accepts only the environment hook
and remains an unstarted-client factory.

## Typed tool definitions

Adoption is optional. Annotate a definition with `ToolDefinition<TSettings>` to
Expand Down
20 changes: 18 additions & 2 deletions typescript/src/activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { createConfigFileWatchers } from './configWatcher';
import { traceError, traceLog, traceVerbose } from './logging';
import { NullFormatter } from './nullFormatter';
import { PythonEnvironmentsProvider } from './python';
import { restartServer, RestartServerOptions } from './server';
import { restartServer, RestartServerOptions, ToolLifecycleHooks } from './server';
import { checkIfConfigurationChanged, getExtensionSettings, getWorkspaceSettings } from './settings';
import { registerLanguageStatusItem, updateStatus } from './status';
import { IBaseSettings, IServerInfo, ToolConfig } from './types';
Expand Down Expand Up @@ -139,6 +139,7 @@ export interface CreateToolContextOptions {
outputChannel: vscode.LogOutputChannel;
toolConfig: ToolConfig;
pythonProvider: PythonEnvironmentsProvider;
hooks?: ToolLifecycleHooks;
}

/**
Expand All @@ -163,6 +164,13 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens
let pythonInitialized = false;
let extensionSubscriptions: vscode.Disposable[] | undefined;
let serverDisposables: vscode.Disposable[] = [];
let clientSetup: vscode.Disposable | undefined;
const hookShutdown = options.hooks ? new AbortController() : undefined;

function disposeClientSetup(): void {
clientSetup?.dispose();
clientSetup = undefined;
}

const nullFormatter = toolConfig.isFormatter ? new NullFormatter() : undefined;
nullFormatter?.register();
Expand Down Expand Up @@ -238,6 +246,7 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens
}
ctx.lsClient = undefined;
}
disposeClientSetup();
for (const d of serverDisposables) {
try {
d.dispose();
Expand Down Expand Up @@ -288,7 +297,10 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens
toolConfig,
pythonProvider,
extensionSettings,
hooks: options.hooks,
signal: hookShutdown?.signal,
onOldClientStopped: () => {
disposeClientSetup();
if (!disposed) {
nullFormatter?.register();
}
Expand Down Expand Up @@ -316,8 +328,10 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens
return;
}

disposeClientSetup();
ctx.lsClient = result.client;
serverDisposables = result.disposables;
clientSetup = result.clientSetup;
serverDisposables = result.disposables.filter((disposable) => disposable !== clientSetup);

if (nullFormatter && result.client) {
if (result.client.state === State.Running) {
Expand Down Expand Up @@ -404,6 +418,8 @@ export function createToolContext(options: CreateToolContextOptions): ToolExtens

dispose(): void {
disposed = true;
hookShutdown?.abort();
disposeClientSetup();
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = undefined;
Expand Down
3 changes: 3 additions & 0 deletions typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ export { createConfigFileWatchers } from './configWatcher';
export {
createServer,
CreateServerOptions,
ClientSetupContext,
getServerCwd,
restartServer,
RestartServerOptions,
RestartServerResult,
ServerLaunchContext,
ToolLifecycleHooks,
} from './server';

// Null formatter helper
Expand Down
Loading
Loading