You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "Sun-GLiang (via GitHub)" <gi...@apache.org> on 2026/08/25 02:30:33 UTC

[PR] feat(cli): add ACP session creation and listing [maka]

Sun-GLiang opened a new pull request, #3744:
URL: https://github.com/apache/maka/pull/3744

   ## Summary
   
   - Add the Runtime Host seams needed by ACP Session lifecycle work: a bounded single-page Session catalog reader and a one-shot subscription open that never retries on a replacement Host.
   - Add an ACP connection-scoped Session registry that creates durable Maka Sessions, continuously consumes one subscription per Session, tracks the latest snapshot, records subscription failures, and cleans up all adapter-owned resources on EOF.
   - Implement ACP `session/new` and cursor-paginated `session/list` through the official SDK, including canonical `cwd` filtering, legacy-record omission, stable Runtime Host error mapping, and explicit rejection of unsupported MCP server and additional-directory inputs.
   - Preserve PR1's probeable startup contract: Runtime Host connection is delayed until the first implemented Session method, concurrent Session calls share the same abortable connection, and initialize or unsupported methods do not start Host discovery.
   - Keep `session/close` unadvertised and returning `-32601`; durable Runtime Host Sessions are never deleted or archived by adapter cleanup. Its active-turn cancellation and adapter-state removal remain follow-up work.
   
   Refs #3132
   Depends on #3658
   
   ## Stacking
   
   This Draft is based on the current head of #3658. Because that branch lives in a fork and cannot be selected as an upstream base branch, GitHub currently shows the combined PR1 + PR2 diff against `main`.
   
   - [ ] Rebase the branch after #3658 lands so this PR contains only the PR2 delta.
   
   ## Verification
   
   - `npm --workspace maka-agent test` — 462 passed, 0 failed
   - `npm --workspace @maka/runtime-host test` — 1124 passed, 0 failed
   - `npm run format:check`
   - `npm run lint`
   - `npm run typecheck`
   - `npm run check:asf-headers`
   - `npm run check:release` — 109 passed, 0 failed
   - `npm run release:cli:pack` with the repository-pinned npm 11.19.0
   - `npm run release:cli:smoke` — installed and exercised the immutable tarball offline
   
   Repository-wide `npm test` still reproduces an unchanged macOS Runtime executable-root assertion. Under the parallel root runner, one long Runtime Host startup-recovery test also exceeded its timing budget; the complete Runtime Host suite passes when run standalone as shown above.
   
   ## AI use
   
   Select exactly one:
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: Codex assisted with implementation, tests, rebase/conflict resolution, verification, and review. Every PR2 commit includes a `Generated-by: Codex` trailer.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [x] Lint, format, typecheck and the affected suites pass locally
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3891442676


##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,542 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  RuntimeHostSubscriptionError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+  type SessionContinuitySnapshot,
+  type SubscriptionFrame,
+  type SubscriptionOpenInput,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_VERSION = 1 as const;
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+interface AcpSessionSubscription extends AsyncIterable<SubscriptionFrame> {
+  readonly snapshot: SessionContinuitySnapshot;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<AcpSessionSubscription>;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+export interface AcpSessionRegistryFailure {
+  readonly source: 'runtime_host';
+  readonly operation: 'subscription.consume';
+  readonly code: string;
+  readonly reason?: string;
+}
+
+export interface AcpSessionRegistryInspection {
+  readonly snapshot: SessionContinuitySnapshot;
+  readonly failure?: AcpSessionRegistryFailure;
+}
+
+interface AcpSessionRecord {
+  readonly sessionId: string;
+  readonly subscription: AcpSessionSubscription;
+  snapshot: SessionContinuitySnapshot;
+  failure?: AcpSessionRegistryFailure;
+  consumerTask: Promise<void>;
+  closing: boolean;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #records = new Map<string, AcpSessionRecord>();
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen();
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen();
+    return this.#track(this.#list(params));
+  }
+
+  inspect(sessionId: string): AcpSessionRegistryInspection | undefined {
+    const record = this.#records.get(sessionId);
+    if (!record) return undefined;
+    return {
+      snapshot: structuredClone(record.snapshot),
+      ...(record.failure ? { failure: { ...record.failure } } : {}),
+    };
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection();
+    const sessionId = this.#newSessionId();
+    try {
+      await connection.request('session.create', {
+        sessionId,
+        workspace: { kind: 'host_path', path: params.cwd },
+        modelTarget: { kind: 'default' },
+      });
+    } catch (error) {
+      throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+    }
+
+    let subscription: AcpSessionSubscription;
+    try {
+      subscription = await connection.openSessionSubscriptionOnce({

Review Comment:
   Verified: the 17th create could reach `session.create` before the Host rejected `subscription.open`, leaving a durable Session behind. Fixed in 419c386a5 without changing the approved PR2 lifecycle boundary. The registry now reserves the shared Runtime Host per-connection subscription capacity from active + pending attachments before `session.create`, including concurrent requests; the 17th request is rejected before persistence, and capacity is released when a subscription terminates. The Host and adapter use one shared limit constant. Coverage includes concurrent admission, released-slot reuse, and 17 creates through the official ACP SDK against a real Runtime Host.
   
   I am pushing back on making attachment lazy/releasable or adding a connection pool in this PR: those would conflict with PR2s one shared Host context, immediate continuous subscription consumption, and deliberately unimplemented `session/close`. PR2 therefore keeps a maximum of 16 simultaneously attached Sessions; broader live-session support should be revalidated with the planned close lifecycle rather than changing that architecture here.



##########
packages/cli/src/acp/stdio-server.ts:
##########
@@ -34,6 +40,24 @@ export async function runMakaAcpStdioServer(
   input: MakaAcpStdioServerInput,
   dependencies: MakaAcpStdioServerDependencies = {},
 ): Promise<number> {
+  const sessionRegistry = new AcpSessionRegistry({
+    connect: async (signal) => {
+      const context = await (dependencies.connectRuntimeHostCli ?? connectRuntimeHostCli)({

Review Comment:
   Verified: ACP `session/new` and `session/list` do not require the model connection catalog, so the previous bootstrap coupled healthy Session operations to an unrelated catalog read. Fixed in 419c386a5 by extracting `connectRuntimeHostCliConnection` for connection/profile ownership and cleanup; the existing `connectRuntimeHostCli` remains the catalog-reading wrapper for current CLI/TUI callers, while ACP uses the connection-only seam. A regression makes the model catalog reader throw and confirms the connection-only bootstrap still succeeds; existing catalog abort/cleanup behavior remains covered.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3911245411


##########
packages/runtime-host/protocol-compatible-changes/session-subscription-capacity.json:
##########
@@ -0,0 +1,5 @@
+{
+  "epoch": 87,

Review Comment:
   Yes — good catch. This was a semantic conflict rather than a textual merge conflict: `main` advanced from epoch 87 to 93 after the previous alignment, so Git could merge cleanly while this compatible-change declaration became stale.
   
   Fixed in 7b1165b28 after merging the latest `main`; the declaration now names epoch 93. That merge also exposed two CLI test fixtures missing `main`\s new `subscribeConnectionCatalogChanges` seam, fixed in 081e120c7.
   
   The protocol epoch guard, typecheck, lint, format check, and the focused ACP/Runtime Host suite (99 tests) pass locally. CI is running on the updated branch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3911413448


##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,571 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  RuntimeHostSubscriptionError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CONNECTION_SUBSCRIPTION_MAX_ITEMS,
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+  type SessionContinuitySnapshot,
+  type SubscriptionFrame,
+  type SubscriptionOpenInput,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_VERSION = 1 as const;
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+interface AcpSessionSubscription extends AsyncIterable<SubscriptionFrame> {
+  readonly snapshot: SessionContinuitySnapshot;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<AcpSessionSubscription>;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+export interface AcpSessionRegistryFailure {
+  readonly source: 'runtime_host';
+  readonly operation: 'subscription.consume';
+  readonly code: string;
+  readonly reason?: string;
+}
+
+export interface AcpSessionRegistryInspection {
+  readonly snapshot: SessionContinuitySnapshot;
+  readonly failure?: AcpSessionRegistryFailure;
+}
+
+interface AcpSessionRecord {
+  readonly sessionId: string;
+  readonly subscription: AcpSessionSubscription;
+  snapshot: SessionContinuitySnapshot;
+  failure?: AcpSessionRegistryFailure;
+  consumerTask: Promise<void>;
+  closing: boolean;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #records = new Map<string, AcpSessionRecord>();
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #activeSubscriptions = 0;
+  #pendingSubscriptionOpens = 0;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen();
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen();
+    return this.#track(this.#list(params));
+  }
+
+  inspect(sessionId: string): AcpSessionRegistryInspection | undefined {
+    const record = this.#records.get(sessionId);
+    if (!record) return undefined;
+    return {
+      snapshot: structuredClone(record.snapshot),
+      ...(record.failure ? { failure: { ...record.failure } } : {}),
+    };
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection();
+    this.#reserveSubscriptionCapacity();
+    try {
+      const sessionId = this.#newSessionId();
+      try {
+        await connection.request('session.create', {
+          sessionId,
+          workspace: { kind: 'host_path', path: params.cwd },
+          modelTarget: { kind: 'default' },
+        });
+      } catch (error) {
+        throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+      }
+
+      let subscription: AcpSessionSubscription;
+      try {
+        subscription = await connection.openSessionSubscriptionOnce({

Review Comment:
   This is the attach. Nothing in PR2 reads what it produces (`snapshot` and `failure` only feed `inspect()`, which only tests call), and the Host keeps the durable Session with zero subscribers. If it moves to PR3's first prompt, everything from L205 down to `#consume` goes with it.



##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,571 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  RuntimeHostSubscriptionError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CONNECTION_SUBSCRIPTION_MAX_ITEMS,
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+  type SessionContinuitySnapshot,
+  type SubscriptionFrame,
+  type SubscriptionOpenInput,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_VERSION = 1 as const;
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+interface AcpSessionSubscription extends AsyncIterable<SubscriptionFrame> {
+  readonly snapshot: SessionContinuitySnapshot;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<AcpSessionSubscription>;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+export interface AcpSessionRegistryFailure {
+  readonly source: 'runtime_host';
+  readonly operation: 'subscription.consume';
+  readonly code: string;
+  readonly reason?: string;
+}
+
+export interface AcpSessionRegistryInspection {
+  readonly snapshot: SessionContinuitySnapshot;
+  readonly failure?: AcpSessionRegistryFailure;
+}
+
+interface AcpSessionRecord {
+  readonly sessionId: string;
+  readonly subscription: AcpSessionSubscription;
+  snapshot: SessionContinuitySnapshot;
+  failure?: AcpSessionRegistryFailure;
+  consumerTask: Promise<void>;
+  closing: boolean;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #records = new Map<string, AcpSessionRecord>();
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #activeSubscriptions = 0;
+  #pendingSubscriptionOpens = 0;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen();
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen();
+    return this.#track(this.#list(params));
+  }
+
+  inspect(sessionId: string): AcpSessionRegistryInspection | undefined {
+    const record = this.#records.get(sessionId);
+    if (!record) return undefined;
+    return {
+      snapshot: structuredClone(record.snapshot),
+      ...(record.failure ? { failure: { ...record.failure } } : {}),
+    };
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection();
+    this.#reserveSubscriptionCapacity();
+    try {
+      const sessionId = this.#newSessionId();
+      try {
+        await connection.request('session.create', {
+          sessionId,
+          workspace: { kind: 'host_path', path: params.cwd },
+          modelTarget: { kind: 'default' },
+        });
+      } catch (error) {
+        throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+      }
+
+      let subscription: AcpSessionSubscription;
+      try {
+        subscription = await connection.openSessionSubscriptionOnce({
+          sessionId,
+          transcript: { kind: 'none' },
+        });
+      } catch (error) {
+        throw RequestError.internalError(
+          {
+            ...runtimeHostErrorData(error, 'subscription.open'),
+            sessionId,
+            durableSessionCreated: true,
+          },
+          'Runtime Host subscription could not be opened for the durable session',
+        );
+      }
+
+      if (this.#closing) {
+        try {
+          await subscription.close();
+        } catch {
+          await this.#closeOwnedConnection();
+        }
+        throw RequestError.internalError(
+          {
+            source: 'runtime_host',
+            operation: 'subscription.open',
+            code: 'registry_closed',
+            sessionId,
+            durableSessionCreated: true,
+          },
+          'ACP connection closed while the durable session was being attached',
+        );
+      }
+
+      const record: AcpSessionRecord = {
+        sessionId,
+        subscription,
+        snapshot: structuredClone(subscription.snapshot),
+        consumerTask: Promise.resolve(),
+        closing: false,
+      };
+      this.#records.set(sessionId, record);
+      this.#activeSubscriptions += 1;
+      record.consumerTask = this.#consume(record);
+      return { sessionId };
+    } finally {

Review Comment:
   If the reservation stays: this `finally` is the half of the P1 fix nothing pins. Delete it and the suite is still green, because the failure cases each do one create and then dispose. Sixteen successful creates after the failing one would lock it.



##########
packages/runtime-host/src/client/connection.ts:
##########
@@ -622,6 +606,13 @@ class RuntimeHostConnectionImpl implements RuntimeHostConnection {
     );
   }
 
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<RuntimeHostSessionSubscription> {
+    return this.openSessionSubscription(input, timeoutMs);

Review Comment:
   On a concrete connection "once" has no meaning; this body is `openSessionSubscription` verbatim, and the only real semantics live in the reconnecting layer's `#requireCurrent`. It landed on the base interface because `runtime-host-cli-context.ts:90` types the field as `RuntimeHostConnection` while it always holds the reconnecting one. Narrow that field and this method can stay on the reconnecting connection only; the "composes through a decorated connection" test goes with it.



##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,571 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  RuntimeHostSubscriptionError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CONNECTION_SUBSCRIPTION_MAX_ITEMS,
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+  type SessionContinuitySnapshot,
+  type SubscriptionFrame,
+  type SubscriptionOpenInput,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_VERSION = 1 as const;
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+interface AcpSessionSubscription extends AsyncIterable<SubscriptionFrame> {
+  readonly snapshot: SessionContinuitySnapshot;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<AcpSessionSubscription>;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+export interface AcpSessionRegistryFailure {
+  readonly source: 'runtime_host';
+  readonly operation: 'subscription.consume';
+  readonly code: string;
+  readonly reason?: string;
+}
+
+export interface AcpSessionRegistryInspection {
+  readonly snapshot: SessionContinuitySnapshot;
+  readonly failure?: AcpSessionRegistryFailure;
+}
+
+interface AcpSessionRecord {
+  readonly sessionId: string;
+  readonly subscription: AcpSessionSubscription;
+  snapshot: SessionContinuitySnapshot;
+  failure?: AcpSessionRegistryFailure;
+  consumerTask: Promise<void>;
+  closing: boolean;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #records = new Map<string, AcpSessionRecord>();
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #activeSubscriptions = 0;
+  #pendingSubscriptionOpens = 0;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen();
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen();
+    return this.#track(this.#list(params));
+  }
+
+  inspect(sessionId: string): AcpSessionRegistryInspection | undefined {
+    const record = this.#records.get(sessionId);
+    if (!record) return undefined;
+    return {
+      snapshot: structuredClone(record.snapshot),
+      ...(record.failure ? { failure: { ...record.failure } } : {}),
+    };
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection();
+    this.#reserveSubscriptionCapacity();
+    try {
+      const sessionId = this.#newSessionId();
+      try {
+        await connection.request('session.create', {
+          sessionId,
+          workspace: { kind: 'host_path', path: params.cwd },
+          modelTarget: { kind: 'default' },
+        });
+      } catch (error) {
+        throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+      }
+
+      let subscription: AcpSessionSubscription;
+      try {
+        subscription = await connection.openSessionSubscriptionOnce({
+          sessionId,
+          transcript: { kind: 'none' },
+        });
+      } catch (error) {
+        throw RequestError.internalError(
+          {
+            ...runtimeHostErrorData(error, 'subscription.open'),
+            sessionId,
+            durableSessionCreated: true,
+          },
+          'Runtime Host subscription could not be opened for the durable session',
+        );
+      }
+
+      if (this.#closing) {
+        try {
+          await subscription.close();
+        } catch {
+          await this.#closeOwnedConnection();
+        }
+        throw RequestError.internalError(
+          {
+            source: 'runtime_host',
+            operation: 'subscription.open',
+            code: 'registry_closed',
+            sessionId,
+            durableSessionCreated: true,
+          },
+          'ACP connection closed while the durable session was being attached',
+        );
+      }
+
+      const record: AcpSessionRecord = {
+        sessionId,
+        subscription,
+        snapshot: structuredClone(subscription.snapshot),
+        consumerTask: Promise.resolve(),
+        closing: false,
+      };
+      this.#records.set(sessionId, record);
+      this.#activeSubscriptions += 1;
+      record.consumerTask = this.#consume(record);
+      return { sessionId };
+    } finally {
+      this.#pendingSubscriptionOpens -= 1;
+    }
+  }
+
+  #reserveSubscriptionCapacity(): void {

Review Comment:
   If the reservation stays: this mirrors the Host's per-connection admission with a compile-time constant, and it is only right while the registry owns its connection alone. Worth one sentence here saying so, since the day ACP shares a Host connection with another CLI path the client count drifts and we are back to the original P1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3912719868


##########
packages/cli/src/__tests__/acp-session-registry.test.ts:
##########
@@ -0,0 +1,618 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, test } from 'node:test';
+import { RequestError, type NewSessionRequest } from '@agentclientprotocol/sdk';
+import { RuntimeHostOperationError } from '@maka/runtime-host/client';
+import { SESSION_CATALOG_CWD_MAX_BYTES } from '@maka/runtime-host/protocol';
+import { AcpSessionRegistry, type AcpSessionRegistryConnection } from '../acp/session-registry.js';
+
+const SESSION_REVISION = `sha256:${'a'.repeat(64)}` as const;
+const NEW_SESSION_REVISION = `sha256:${'b'.repeat(64)}` as const;
+
+describe('ACP Session registry', () => {
+  test('does not connect when disposed before a Session method is used', async () => {
+    let connectCalls = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        connectCalls += 1;
+        return fakeConnection();
+      },
+    });
+
+    await registry.dispose();
+    await registry.dispose();
+
+    assert.equal(connectCalls, 0);
+  });
+
+  test('reports the requested Session operation after disposal', async () => {
+    const registry = new AcpSessionRegistry({
+      connect: async () => fakeConnection(),
+    });
+    await registry.dispose();
+
+    for (const [operation, request] of [
+      ['session.create', () => registry.create({ cwd: '/workspace', mcpServers: [] })],
+      ['session.catalog.query', () => registry.list({})],
+    ] as const) {
+      await assert.rejects(request(), (error: unknown) => {
+        assert.ok(error instanceof RequestError);
+        assert.equal(error.code, -32603);
+        assert.deepEqual(error.data, {
+          source: 'runtime_host',
+          operation,
+          code: 'registry_closed',
+        });
+        return true;
+      });
+    }
+  });
+
+  test('does not start a queued connection after disposal begins', async () => {
+    let connectCalls = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        connectCalls += 1;
+        return fakeConnection();
+      },
+    });
+
+    const list = registry.list({});
+    const dispose = registry.dispose();
+
+    await assert.rejects(
+      list,
+      (error: unknown) =>
+        error instanceof RequestError &&
+        error.code === -32603 &&
+        (error.data as { code?: string }).code === 'registry_closed',
+    );
+    await dispose;
+    assert.equal(connectCalls, 0);
+  });
+
+  test('aborts an in-flight connection before disposal waits for it', async () => {
+    let connectSignal: AbortSignal | undefined;
+    const registry = new AcpSessionRegistry({
+      connect: async (signal) => {
+        connectSignal = signal;
+        return new Promise<ReturnType<typeof fakeConnection>>((_, reject) => {
+          signal.addEventListener('abort', () => reject(signal.reason), { once: true });
+        });
+      },
+    });
+
+    const list = registry.list({});
+    await waitFor(() => connectSignal !== undefined);
+    const dispose = registry.dispose();
+
+    await assert.rejects(
+      list,
+      (error: unknown) =>
+        error instanceof RequestError &&
+        error.code === -32603 &&
+        (error.data as { code?: string }).code === 'registry_closed',
+    );
+    await dispose;
+    assert.equal(connectSignal?.aborted, true);
+  });
+
+  test('shares one in-flight connection across concurrent Session methods', async () => {
+    const connecting = deferred<ReturnType<typeof fakeConnection>>();
+    let connectCalls = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        connectCalls += 1;
+        return connecting.promise;
+      },
+      newSessionId: () => 'session-concurrent',
+    });
+    const create = registry.create({ cwd: '/workspace', mcpServers: [] });
+    const list = registry.list({});
+    await waitFor(() => connectCalls === 1);
+
+    connecting.resolve(
+      fakeConnection({
+        request: async (operation) =>
+          operation === 'session.catalog.query'
+            ? {
+                kind: 'page',
+                revision: SESSION_REVISION,
+                sessions: [],
+                nextCursor: null,
+              }
+            : {},
+      }),
+    );
+
+    assert.deepEqual(await create, { sessionId: 'session-concurrent' });
+    assert.deepEqual(await list, { sessions: [] });
+    assert.equal(connectCalls, 1);
+    await registry.dispose();
+  });
+
+  test('reports a stable connection error and retries on a later Session request', async () => {
+    let connectCalls = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        connectCalls += 1;
+        if (connectCalls === 1) throw new Error('Host unavailable');
+        return fakeConnection({
+          request: async () => ({
+            kind: 'page',
+            revision: SESSION_REVISION,
+            sessions: [],
+            nextCursor: null,
+          }),
+        });
+      },
+    });
+
+    await assert.rejects(registry.list({}), (error: unknown) => {
+      assert.ok(error instanceof RequestError);
+      assert.equal(error.code, -32603);
+      assert.deepEqual(error.data, {
+        source: 'runtime_host',
+        operation: 'connect',
+        code: 'connection_failed',
+      });
+      return true;
+    });
+    assert.deepEqual(await registry.list({}), { sessions: [] });
+    assert.equal(connectCalls, 2);
+    await registry.dispose();
+  });
+
+  test('closes a connection that resolves after disposal starts', async () => {
+    const connecting = deferred<ReturnType<typeof fakeConnection>>();
+    let connectCalls = 0;
+    let closeCalls = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        connectCalls += 1;
+        return connecting.promise;
+      },
+    });
+    const list = registry.list({});
+    await waitFor(() => connectCalls === 1);
+    const dispose = registry.dispose();
+
+    connecting.resolve(
+      fakeConnection({
+        close: async () => {
+          closeCalls += 1;
+        },
+      }),
+    );
+
+    await assert.rejects(list, (error: unknown) => {
+      assert.ok(error instanceof RequestError);
+      assert.equal(error.code, -32603);
+      assert.equal((error.data as { code?: string }).code, 'registry_closed');
+      return true;
+    });
+    await dispose;
+    assert.equal(closeCalls, 1);
+  });
+
+  test('creates more than the Host subscription limit without opening a subscription', async () => {
+    const sessionCount = 17;
+    const createdSessionIds: string[] = [];
+    let subscriptionOpens = 0;
+    let nextId = 0;
+    const registry = new AcpSessionRegistry({
+      connect: async () => {
+        const connection = fakeConnection({
+          request: async (operation, input) => {
+            assert.equal(operation, 'session.create');
+            createdSessionIds.push((input as { sessionId: string }).sessionId);
+            return {};
+          },
+        });
+        return {
+          ...connection,
+          openSessionSubscriptionOnce: async () => {
+            subscriptionOpens += 1;
+            throw new Error('PR 2 must not open a subscription');
+          },
+        } as AcpSessionRegistryConnection;
+      },
+      newSessionId: () => `session-unattached-${++nextId}`,
+    });
+
+    const creates = await Promise.all(
+      Array.from({ length: sessionCount }, () =>
+        registry.create({ cwd: '/workspace', mcpServers: [] }),
+      ),
+    );
+
+    assert.equal(creates.length, sessionCount);
+    assert.equal(createdSessionIds.length, sessionCount);
+    assert.equal(subscriptionOpens, 0);

Review Comment:
   Nothing in the registry can increment this counter, so the assertion cannot fail. The child-process test and the stdio-server test already prove no-attach; this one and the last `openSessionSubscriptionOnce` string can go.



##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,399 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+type AcpSessionRegistryOperation = 'session.create' | 'session.catalog.query';
+type AcpSessionRegistryLifecycleOperation = 'connect' | AcpSessionRegistryOperation;
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen('session.create');
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen('session.catalog.query');
+    return this.#track(this.#list(params));
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection('session.create');
+    const sessionId = this.#newSessionId();
+    try {
+      await connection.request('session.create', {
+        sessionId,
+        workspace: { kind: 'host_path', path: params.cwd },
+        modelTarget: { kind: 'default' },
+      });
+    } catch (error) {
+      throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+    }
+    return { sessionId };
+  }
+
+  async #list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    const cursor = params.cursor == null ? undefined : decodeAcpSessionCursor(params.cursor);
+    const requestedCwd = params.cwd == null ? undefined : await normalizeCwd(params.cwd);
+    if (cursor && requestedCwd !== undefined && cursor.cwd !== requestedCwd) {
+      throw RequestError.invalidParams(
+        { reason: 'cursor_cwd_mismatch' },
+        'cursor was created for a different cwd filter',
+      );
+    }
+    const cwd = requestedCwd ?? cursor?.cwd ?? null;
+    const connection = await this.#getConnection('session.catalog.query');
+    let page;
+    try {
+      page = await readRuntimeHostSessionCatalogPage(
+        connection,
+        cursor ? { revision: cursor.revision, cursor: cursor.cursor } : undefined,
+      );
+    } catch (error) {
+      if (error instanceof RuntimeHostSessionCatalogRevisionChangedError) {
+        throw RequestError.invalidParams(
+          { reason: 'stale_cursor' },
+          'session catalog changed; restart listing from the first page',
+        );
+      }
+      throw requestErrorFromRuntimeHost(error, 'session.catalog.query');
+    }
+
+    const sessions = page.sessions.flatMap((session) => {
+      if ('kind' in session || (cwd !== null && session.workspace.hostCwd !== cwd)) return [];
+      const updatedAt = isoTimestamp(session.activityAt);
+      return [
+        {
+          sessionId: session.id,
+          cwd: session.workspace.hostCwd,
+          title: session.name,
+          ...(updatedAt ? { updatedAt } : {}),
+        },
+      ];
+    });
+    return {
+      sessions,
+      ...(page.nextCursor
+        ? { nextCursor: encodeAcpSessionCursor({ ...page.nextCursor, cwd }) }
+        : {}),
+    };
+  }
+
+  async #dispose(): Promise<void> {
+    const connectionClose = this.#closeOwnedConnection();
+    await Promise.allSettled([connectionClose]);
+    await Promise.allSettled([...this.#inFlightOperations]);
+  }
+
+  #closeOwnedConnection(): Promise<void> {
+    const connection = this.#connection;
+    const connectTask = this.#connectTask;
+    if (!connection && !connectTask) return Promise.resolve();
+    this.#connectionCloseTask ??= connection
+      ? Promise.resolve().then(() => connection.close())
+      : connectTask!.then(
+          (connected) => connected.close(),
+          () => undefined,
+        );
+    return this.#connectionCloseTask;
+  }
+
+  async #getConnection(
+    operation: AcpSessionRegistryOperation,
+  ): Promise<AcpSessionRegistryConnection> {
+    this.#assertOpen(operation);
+    if (this.#connection) return this.#connection;
+    let connectController = this.#connectAbortController;
+    if (!this.#connectTask) {
+      connectController = new AbortController();
+      this.#connectAbortController = connectController;
+      this.#connectTask = Promise.resolve().then(() => {
+        if (this.#closing) throw registryClosedError('connect');
+        connectController!.signal.throwIfAborted();
+        return this.#connect(connectController!.signal);
+      });
+    }
+    const connectTask = this.#connectTask;
+    let connection: AcpSessionRegistryConnection;
+    try {
+      connection = await connectTask;
+    } catch {
+      if (this.#connectTask === connectTask) this.#connectTask = undefined;
+      if (this.#connectAbortController === connectController) {
+        this.#connectAbortController = undefined;
+      }
+      if (this.#closing) throw registryClosedError('connect');
+      throw RequestError.internalError(
+        {
+          source: 'runtime_host',
+          operation: 'connect',
+          code: 'connection_failed',
+        },
+        'Runtime Host connection failed',
+      );
+    }
+    if (this.#connectAbortController === connectController) {
+      this.#connectAbortController = undefined;
+    }
+    if (this.#closing) {
+      await this.#closeOwnedConnection().catch(() => undefined);
+      throw registryClosedError('connect');
+    }
+    this.#connection ??= connection;
+    return this.#connection;
+  }
+
+  async #track<T>(operation: Promise<T>): Promise<T> {
+    this.#inFlightOperations.add(operation);
+    try {
+      return await operation;
+    } finally {
+      this.#inFlightOperations.delete(operation);
+    }
+  }
+
+  #assertOpen(operation: AcpSessionRegistryOperation): void {
+    if (!this.#closing) return;
+    throw registryClosedError(operation);
+  }
+}
+
+function registryClosedError(operation: AcpSessionRegistryLifecycleOperation): RequestError {
+  return RequestError.internalError(
+    { source: 'runtime_host', operation, code: 'registry_closed' },
+    'ACP session registry is closed',
+  );
+}
+
+function validateNewSessionParams(params: NewSessionRequest): void {
+  assertBoundedAbsoluteCwd(params.cwd);
+  if (params.mcpServers.length > 0) {

Review Comment:
   Fine for PR2. For PR3: the ACP schema makes `mcpServers` required, so any editor with a context server configured lands here. One real `session/new` from Zed would settle what to do with it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han merged PR #3744:
URL: https://github.com/apache/maka/pull/3744


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on PR #3744:
URL: https://github.com/apache/maka/pull/3744#issuecomment-5506201931

   Thanks for the review. I’ve revised PR2 to keep it limited to durable session creation and listing. `session/new` no longer attaches a subscription; client-side subscription capacity tracking and the premature one-shot API have also been removed.
   
   PR3 will expose the Runtime Host-backed Session configuration through ACP. It will add lightweight current-connection ownership tracking when that state gets its first real consumer, return the supported `configOptions` from `session/new`, and implement `session/set_config_option` through Runtime Host CAS updates—still without opening a subscription.
   
   Subscription attachment is deferred to the first `session/prompt` in PR4. The updated PR2 tests verify that 17 sessions can be created on one ACP connection without attachment. I also addressed the first-page catalog revision retry, strict opaque cursor validation, and CLI help feedback. The implementation checklist and PR description have been updated accordingly.
   
   ---
   
   感谢 review。我已调整 PR2,使其范围仅限于 durable session 的创建和列出。`session/new` 不再 attach subscription,同时移除了客户端侧的 subscription capacity 计数以及过早引入的 one-shot API。
   
   PR3 将通过 ACP 暴露由 Runtime Host 管理的 Session 配置能力。届时 ownership 状态会出现首个实际消费者,因此 PR3 会引入轻量的 current-connection ownership tracking;同时让 `session/new` 返回受支持的 `configOptions`,并通过 Runtime Host 的 CAS 更新实现 `session/set_config_option`。这些配置操作仍然不会打开 subscription。
   
   Subscription attach 延至 PR4 的首次 `session/prompt`。更新后的 PR2 测试验证了同一个 ACP connection 可以在不 attach 的情况下创建 17 个 session。此外,首页 catalog revision-change 重试、严格的 opaque cursor 校验以及 CLI help 反馈也已处理,implementation checklist 和 PR 描述已同步更新。
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3890143569


##########
packages/cli/src/acp/session-registry.ts:
##########
@@ -0,0 +1,542 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize } from 'node:path';
+import {
+  RequestError,
+  type ListSessionsRequest,
+  type ListSessionsResponse,
+  type NewSessionRequest,
+  type NewSessionResponse,
+} from '@agentclientprotocol/sdk';
+import {
+  readRuntimeHostSessionCatalogPage,
+  RuntimeHostCatalogReadError,
+  RuntimeHostOperationError,
+  RuntimeHostRequestInterruptedError,
+  RuntimeHostSessionCatalogRevisionChangedError,
+  RuntimeHostSubscriptionError,
+  type RuntimeHostConnection,
+  type RuntimeHostSessionCatalogPageCursor,
+} from '@maka/runtime-host/client';
+import {
+  SESSION_CATALOG_CURSOR_MAX_BYTES,
+  SESSION_CATALOG_CWD_MAX_BYTES,
+  type SessionContinuitySnapshot,
+  type SubscriptionFrame,
+  type SubscriptionOpenInput,
+} from '@maka/runtime-host/protocol';
+
+const ACP_SESSION_CURSOR_VERSION = 1 as const;
+const ACP_SESSION_CURSOR_MAX_BYTES = 8 * 1024;
+
+interface AcpSessionSubscription extends AsyncIterable<SubscriptionFrame> {
+  readonly snapshot: SessionContinuitySnapshot;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryConnection {
+  readonly request: RuntimeHostConnection['request'];
+  openSessionSubscriptionOnce(
+    input: SubscriptionOpenInput,
+    timeoutMs?: number,
+  ): Promise<AcpSessionSubscription>;
+  close(): Promise<void>;
+}
+
+export interface AcpSessionRegistryOptions {
+  readonly connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly newSessionId?: () => string;
+}
+
+export interface AcpSessionRegistryFailure {
+  readonly source: 'runtime_host';
+  readonly operation: 'subscription.consume';
+  readonly code: string;
+  readonly reason?: string;
+}
+
+export interface AcpSessionRegistryInspection {
+  readonly snapshot: SessionContinuitySnapshot;
+  readonly failure?: AcpSessionRegistryFailure;
+}
+
+interface AcpSessionRecord {
+  readonly sessionId: string;
+  readonly subscription: AcpSessionSubscription;
+  snapshot: SessionContinuitySnapshot;
+  failure?: AcpSessionRegistryFailure;
+  consumerTask: Promise<void>;
+  closing: boolean;
+}
+
+/** Owns all Runtime Host resources associated with one ACP connection. */
+export class AcpSessionRegistry {
+  readonly #connect: (signal: AbortSignal) => Promise<AcpSessionRegistryConnection>;
+  readonly #newSessionId: () => string;
+  readonly #records = new Map<string, AcpSessionRecord>();
+  readonly #inFlightOperations = new Set<Promise<unknown>>();
+  #connection: AcpSessionRegistryConnection | undefined;
+  #connectTask: Promise<AcpSessionRegistryConnection> | undefined;
+  #connectAbortController: AbortController | undefined;
+  #closing = false;
+  #connectionCloseTask: Promise<void> | undefined;
+  #disposeTask: Promise<void> | undefined;
+
+  constructor(options: AcpSessionRegistryOptions) {
+    this.#connect = options.connect;
+    this.#newSessionId = options.newSessionId ?? randomUUID;
+  }
+
+  async create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    this.#assertOpen();
+    validateNewSessionParams(params);
+    return this.#track(this.#create(params));
+  }
+
+  async list(params: ListSessionsRequest): Promise<ListSessionsResponse> {
+    this.#assertOpen();
+    return this.#track(this.#list(params));
+  }
+
+  inspect(sessionId: string): AcpSessionRegistryInspection | undefined {
+    const record = this.#records.get(sessionId);
+    if (!record) return undefined;
+    return {
+      snapshot: structuredClone(record.snapshot),
+      ...(record.failure ? { failure: { ...record.failure } } : {}),
+    };
+  }
+
+  dispose(): Promise<void> {
+    this.#closing = true;
+    this.#connectAbortController?.abort();
+    this.#disposeTask ??= this.#dispose();
+    return this.#disposeTask;
+  }
+
+  async #create(params: NewSessionRequest): Promise<NewSessionResponse> {
+    const connection = await this.#getConnection();
+    const sessionId = this.#newSessionId();
+    try {
+      await connection.request('session.create', {
+        sessionId,
+        workspace: { kind: 'host_path', path: params.cwd },
+        modelTarget: { kind: 'default' },
+      });
+    } catch (error) {
+      throw requestErrorFromRuntimeHost(error, 'session.create', { sessionId });
+    }
+
+    let subscription: AcpSessionSubscription;
+    try {
+      subscription = await connection.openSessionSubscriptionOnce({

Review Comment:
   [P1] (category ① — normal supported path)
   
   Thanks for keeping Runtime Host as the Session authority. One lifecycle limit still looks reachable on the normal `session/new` path: this creates the durable Session first, then opens and retains one subscription for every created Session until the entire ACP stdio connection exits. Runtime Host caps a connection at 16 subscriptions, and this PR has no per-Session close/release operation, so the 17th create returns an error after the Session was already committed; each retry creates another catalog entry and fails again. Could the adapter either make attachment lazy/releasable, or reserve capacity with the real subscription owner before committing the Session, and cover 17+ creates on one real ACP connection? Please feel free to push back if the ACP client lifecycle guarantees the process is replaced before this limit.



##########
packages/cli/src/acp/stdio-server.ts:
##########
@@ -34,6 +40,24 @@ export async function runMakaAcpStdioServer(
   input: MakaAcpStdioServerInput,
   dependencies: MakaAcpStdioServerDependencies = {},
 ): Promise<number> {
+  const sessionRegistry = new AcpSessionRegistry({
+    connect: async (signal) => {
+      const context = await (dependencies.connectRuntimeHostCli ?? connectRuntimeHostCli)({

Review Comment:
   [P2] (category ② — reasonable failure/recovery path)
   
   Thanks for reusing the existing Host bootstrap. The ACP registry only consumes the connection and `close()`, but `connectRuntimeHostCli()` also reads the entire connection/model catalog before returning. That makes otherwise healthy `session/list` and `session/new` fail as `connection_failed` whenever the unrelated connection catalog is temporarily unreadable or revision-churning, before a Session request is sent. Would a connection-only/lazy-catalog bootstrap be a better fit here, with a regression where the connection catalog fails while `session.catalog.query` remains healthy? Please push back if ACP intentionally requires a healthy model catalog even for listing existing Sessions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3910780299


##########
packages/runtime-host/protocol-compatible-changes/session-subscription-capacity.json:
##########
@@ -0,0 +1,5 @@
+{
+  "epoch": 87,

Review Comment:
   Is this conflict with main already?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on PR #3744:
URL: https://github.com/apache/maka/pull/3744#issuecomment-5506457899

   Thanks for the review. I’ve revised PR2 to keep it limited to durable session creation and listing. `session/new` no longer attaches a subscription; client-side subscription capacity tracking and the premature one-shot API have also been removed.
   
   PR3 will expose the Runtime Host-backed Session configuration through ACP. It will add lightweight current-connection ownership tracking when that state gets its first real consumer, return the supported `configOptions` from `session/new`, and implement `session/set_config_option` through Runtime Host CAS updates—still without opening a subscription.
   
   Subscription attachment is deferred to the first `session/prompt` in PR4. The updated PR2 tests verify that 17 sessions can be created on one ACP connection without attachment. I also addressed the first-page catalog revision retry, strict opaque cursor validation, and CLI help feedback. The implementation checklist and PR description have been updated accordingly.
   
   ---
   
   感谢 review。我已调整 PR2,使其范围仅限于 durable session 的创建和列出。`session/new` 不再 attach subscription,同时移除了客户端侧的 subscription capacity 计数以及过早引入的 one-shot API。
   
   PR3 将通过 ACP 暴露由 Runtime Host 管理的 Session 配置能力。届时 ownership 状态会出现首个实际消费者,因此 PR3 会引入轻量的 current-connection ownership tracking;同时让 `session/new` 返回受支持的 `configOptions`,并通过 Runtime Host 的 CAS 更新实现 `session/set_config_option`。这些配置操作仍然不会打开 subscription。
   
   Subscription attach 延至 PR4 的首次 `session/prompt`。更新后的 PR2 测试验证了同一个 ACP connection 可以在不 attach 的情况下创建 17 个 session。此外,首页 catalog revision-change 重试、严格的 opaque cursor 校验以及 CLI help 反馈也已处理,implementation checklist 和 PR 描述已同步更新。
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(cli): add ACP session creation and listing [maka]

Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on code in PR #3744:
URL: https://github.com/apache/maka/pull/3744#discussion_r3911245411


##########
packages/runtime-host/protocol-compatible-changes/session-subscription-capacity.json:
##########
@@ -0,0 +1,5 @@
+{
+  "epoch": 87,

Review Comment:
   Yes — good catch. This was a semantic conflict rather than a textual merge conflict: `main` advanced from epoch 87 to 93 after the previous alignment, so Git could merge cleanly while this compatible-change declaration became stale.
   
   Fixed in 7b1165b28 after merging the latest `main`; the declaration now names epoch 93. That merge also exposed two CLI test fixtures missing the new `subscribeConnectionCatalogChanges` seam from `main`, fixed in 081e120c7.
   
   The protocol epoch guard, typecheck, lint, format check, and the focused ACP/Runtime Host suite (99 tests) pass locally. CI is running on the updated branch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org