@h-ai/ai 1.0.0-beta.17 → 1.0.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as AIFunctions, c7 as McpServerOptions } from './ai-acp-types-DQ8jO9Ie.js';
2
- export { A as A2AAgentCardConfig, a as A2AApiKeySecurity, b as A2AAuthenticator, c as A2ACallOptions, d as A2ACallResult, e as A2ACallerIdentity, f as A2AConfig, g as A2AConfigSchema, h as A2AContextInfo, i as A2AHandleResult, j as A2AMessageRecord, k as A2AOperations, l as A2ASecurityConfig, m as A2ASkillConfigSchema, n as A2ATaskFilter, o as ACPAgentAdapter, p as ACPAgentAdapterInput, q as ACPAgentLaunch, r as ACPAgentSchema, s as ACPClientOptions, t as ACPConfig, u as ACPConfigInput, v as ACPConfigSchema, w as ACPCreateSessionOptions, x as ACPGitReport, y as ACPOperations, z as ACPPublishSchema, B as ACPRepositorySchema, C as ACPSessionInfo, D as ACPTransport, E as ACPWorkspaceSchema, F as AIConfig, G as AIConfigInput, H as AIConfigSchema, J as AIInitOptions, K as AIRelStore, L as AIRelStoreCompareAndSwap, M as AIRelStoreOptions, N as AIResourceEntry, O as AIResourceRegistry, P as AIStoreProvider, Q as AIVectorBackend, R as AIVectorStore, S as AIVersionedRecord, T as AUDIO_WS_PATH, U as ApiType, V as ApiTypeSchema, W as AskOptions, X as AssistantMessage, Y as AudioConfig, Z as AudioConfigSchema, _ as AudioFormatSchema, $ as AudioModelEntry, a0 as AudioModelEntrySchema, a1 as AudioOperation, a2 as AudioOperationSchema, a3 as AudioOperationsSchema, a4 as AudioProviderName, a5 as AudioProviderSchema, a6 as AudioWsClientMessage, a7 as AudioWsClientMessageSchema, a8 as AudioWsDoneMessage, a9 as AudioWsDoneMessageSchema, aa as AudioWsEndMessage, ab as AudioWsErrorMessage, ac as AudioWsSegmentDoneMessage, ad as AudioWsSegmentStartedMessage, ae as AudioWsServerMessage, af as AudioWsSpeechMessage, ag as AudioWsStartMessage, ah as AudioWsStartMessageSchema, ai as AudioWsTextMessage, aj as AudioWsTextMessageSchema, ak as AudioWsTranscriptMessage, al as ChatCompletionChoice, am as ChatCompletionChunk, an as ChatCompletionDelta, ao as ChatCompletionRequest, ap as ChatCompletionResponse, aq as ChatHistoryOptions, ar as ChatMessage, as as ChatRecord, at as Citation, au as CommitTurnInput, av as CompressConfig, aw as CompressConfigSchema, ax as CompressOperations, ay as CompressOptions, az as CompressResult, aA as CompressionStrategy, aB as CompressionStrategySchema, aC as ConsolidateOptions, aD as ConsolidateResult, aE as ContextChatOptions, aF as ContextChatResult, aG as ContextManager, aH as ContextManagerOptions, aI as ContextOperations, aJ as ContextResetOptions, aK as ContextStreamEvent, aL as ConversationTurn, aM as ConversationTurnStatus, aN as DefineToolOptions, aO as DeveloperMessage, aP as EmbeddingConfig, aQ as EmbeddingConfigSchema, aR as EmbeddingItem, aS as EmbeddingOperations, aT as EmbeddingRequest, aU as EmbeddingResponse, aV as EntityDocumentRelation, aW as EntityDocumentResult, aX as EntityListOptions, aY as EntityQueryOptions, aZ as EntityType, a_ as EntityTypeSchema, a$ as FileConfig, b0 as FileConfigSchema, b1 as FileOperations, b2 as FileParseMethod, b3 as FileParseOptions, b4 as FileParseRequest, b5 as FileParseResult, b6 as GenerateImageRequest, b7 as GenerateImageResult, b8 as GenerateObjectRequest, b9 as GeneratedImage, ba as HaiAIError, bb as ImageConfig, bc as ImageConfigSchema, bd as ImageContent, be as ImageModelEntry, bf as ImageModelEntrySchema, bg as ImageOperations, bh as ImageProviderName, bi as ImageProviderSchema, bj as ImageSize, bk as InteractionScope, bl as KnowledgeAskOptions, bm as KnowledgeAskResult, bn as KnowledgeConfig, bo as KnowledgeConfigSchema, bp as KnowledgeDocumentInfo, bq as KnowledgeDocumentListOptions, br as KnowledgeDocumentMetadata, bs as KnowledgeDocumentRemoveOptions, bt as KnowledgeDocumentRevision, bu as KnowledgeEntity, bv as KnowledgeIngestBatchProgress, bw as KnowledgeIngestBatchResult, bx as KnowledgeIngestFileInput, by as KnowledgeIngestInput, bz as KnowledgeIngestResult, bA as KnowledgeOperations, bB as KnowledgeRepairOptions, bC as KnowledgeRepairProgress, bD as KnowledgeRepairResult, bE as KnowledgeRetrieveItem, bF as KnowledgeRetrieveOptions, bG as KnowledgeRetrieveResult, bH as KnowledgeSetupOptions, bI as KnowledgeStore, bJ as LLMConfig, bK as LLMConfigSchema, bL as LLMOperations, bM as MCPConfig, bN as MCPConfigSchema, bO as MCPContext, bP as MCPExternalServer, bQ as MCPExternalServerSchema, bR as MCPOperations, bS as MCPPrompt, bT as MCPPromptArgument, bU as MCPPromptContent, bV as MCPPromptMessage, bW as MCPResource, bX as MCPResourceContent, bY as MCPServerCapabilities, bZ as MCPServerCapabilitiesSchema, b_ as MCPServerConfig, b$ as MCPServerConfigSchema, c0 as MCPToolDefinition, c1 as MCPToolHandler, c2 as ManagedAudioOperations, c3 as ManagedImageOperations, c4 as ManagedLLMOperations, c5 as ManagedMCPOperations, c6 as ManagedRetrievalOperations, c8 as MemoryAccessScope, c9 as MemoryAdminOperations, ca as MemoryClearAllOptions, cb as MemoryClearOptions, cc as MemoryConfig, cd as MemoryConfigSchema, ce as MemoryCoreOperations, cf as MemoryEntry, cg as MemoryEntryInput, ch as MemoryExtractOptions, ci as MemoryInjectionOptions, cj as MemoryListOptions, ck as MemoryListPageOptions, cl as MemoryOperations, cm as MemoryRecallOptions, cn as MemoryType, co as MemoryTypeSchema, cp as MemoryUpdateInput, cq as MessageContent, cr as MessageRole, cs as ModelCapabilitiesSchema, ct as ModelEntry, cu as ModelEntrySchema, cv as ModelScenario, cw as ModelScenarioSchema, cx as ObjectRef, cy as OptionalSecretSchema, cz as OutputFormat, cA as PersonaOperations, cB as PersonaProfile, cC as PersonaProfileInput, cD as PersonaProfileUpdate, cE as PersonaScopeOptions, cF as RagContextItem, cG as RagOperations, cH as RagOptions, cI as RagResult, cJ as RagStreamEvent, cK as ReasoningOperations, cL as ReasoningOptions, cM as ReasoningResult, cN as ReasoningStep, cO as ReasoningStepType, cP as ReasoningStrategy, cQ as ReasoningStreamEvent, cR as ReferenceImage, cS as RerankDocument, cT as RerankItem, cU as RerankOperations, cV as RerankRequest, cW as RerankResponse, cX as ResolveRequiredModelEntryOptions, cY as ResolvedAudioModel, cZ as ResolvedImageModel, c_ as ResolvedModelConfig, c$ as RetrievalConfig, d0 as RetrievalConfigSchema, d1 as RetrievalOperations, d2 as RetrievalRequest, d3 as RetrievalResult, d4 as RetrievalResultItem, d5 as RetrievalSource, d6 as RetrievalSourceConfig, d7 as RetrievalSourceSchema, d8 as SSEDecoder, d9 as SSEEvent, da as ScopedMemoryBinding, db as ScopedMemoryOperations, dc as SessionInfo, dd as StoreFilter, de as StorePage, df as StoreScope, dg as StreamOperations, dh as StreamProcessor, di as StreamResult, dj as SummaryConfig, dk as SummaryConfigSchema, dl as SummaryOperations, dm as SummaryOptions, dn as SummaryResult, dp as SystemMessage, dq as TempModelConfig, dr as TextContent, ds as TokenConfig, dt as TokenConfigSchema, du as TokenOperations, dv as TokenUsage, dw as Tool, dx as ToolAuthorizationRequest, dy as ToolAuthorizer, dz as ToolCall, dA as ToolDefinition, dB as ToolErrorType, dC as ToolExecutionContext, dD as ToolExecutionOptions, dE as ToolMessage, dF as ToolRegistryOperations, dG as ToolRegistryOptions, dH as ToolsOperations, dI as UserMessage, dJ as WhereClause, dK as WhereOperator, dL as WhereValue, dM as ensureAudioCredential, dN as resolveAudioModel, dO as resolveImageModel, dP as resolveModelApi, dQ as resolveModelEntry, dR as serializePlayableAudio } from './ai-acp-types-DQ8jO9Ie.js';
1
+ import { I as AIFunctions, c7 as McpServerOptions } from './ai-acp-types-Df_JG_-t.js';
2
+ export { A as A2AAgentCardConfig, a as A2AApiKeySecurity, b as A2AAuthenticator, c as A2ACallOptions, d as A2ACallResult, e as A2ACallerIdentity, f as A2AConfig, g as A2AConfigSchema, h as A2AContextInfo, i as A2AHandleResult, j as A2AMessageRecord, k as A2AOperations, l as A2ASecurityConfig, m as A2ASkillConfigSchema, n as A2ATaskFilter, o as ACPAgentAdapter, p as ACPAgentAdapterInput, q as ACPAgentLaunch, r as ACPAgentSchema, s as ACPClientOptions, t as ACPConfig, u as ACPConfigInput, v as ACPConfigSchema, w as ACPCreateSessionOptions, x as ACPGitReport, y as ACPOperations, z as ACPPublishSchema, B as ACPRepositorySchema, C as ACPSessionInfo, dS as ACPSessionWorkspace, D as ACPTransport, E as ACPWorkspaceSchema, F as AIConfig, G as AIConfigInput, H as AIConfigSchema, J as AIInitOptions, K as AIRelStore, L as AIRelStoreCompareAndSwap, M as AIRelStoreOptions, N as AIResourceEntry, O as AIResourceRegistry, P as AIStoreProvider, Q as AIVectorBackend, R as AIVectorStore, S as AIVersionedRecord, T as AUDIO_WS_PATH, U as ApiType, V as ApiTypeSchema, W as AskOptions, X as AssistantMessage, Y as AudioConfig, Z as AudioConfigSchema, _ as AudioFormatSchema, $ as AudioModelEntry, a0 as AudioModelEntrySchema, a1 as AudioOperation, a2 as AudioOperationSchema, a3 as AudioOperationsSchema, a4 as AudioProviderName, a5 as AudioProviderSchema, a6 as AudioWsClientMessage, a7 as AudioWsClientMessageSchema, a8 as AudioWsDoneMessage, a9 as AudioWsDoneMessageSchema, aa as AudioWsEndMessage, ab as AudioWsErrorMessage, ac as AudioWsSegmentDoneMessage, ad as AudioWsSegmentStartedMessage, ae as AudioWsServerMessage, af as AudioWsSpeechMessage, ag as AudioWsStartMessage, ah as AudioWsStartMessageSchema, ai as AudioWsTextMessage, aj as AudioWsTextMessageSchema, ak as AudioWsTranscriptMessage, al as ChatCompletionChoice, am as ChatCompletionChunk, an as ChatCompletionDelta, ao as ChatCompletionRequest, ap as ChatCompletionResponse, aq as ChatHistoryOptions, ar as ChatMessage, as as ChatRecord, at as Citation, au as CommitTurnInput, av as CompressConfig, aw as CompressConfigSchema, ax as CompressOperations, ay as CompressOptions, az as CompressResult, aA as CompressionStrategy, aB as CompressionStrategySchema, aC as ConsolidateOptions, aD as ConsolidateResult, aE as ContextChatOptions, aF as ContextChatResult, aG as ContextManager, aH as ContextManagerOptions, aI as ContextOperations, aJ as ContextResetOptions, aK as ContextStreamEvent, aL as ConversationTurn, aM as ConversationTurnStatus, aN as DefineToolOptions, aO as DeveloperMessage, aP as EmbeddingConfig, aQ as EmbeddingConfigSchema, aR as EmbeddingItem, aS as EmbeddingOperations, aT as EmbeddingRequest, aU as EmbeddingResponse, aV as EntityDocumentRelation, aW as EntityDocumentResult, aX as EntityListOptions, aY as EntityQueryOptions, aZ as EntityType, a_ as EntityTypeSchema, a$ as FileConfig, b0 as FileConfigSchema, b1 as FileOperations, b2 as FileParseMethod, b3 as FileParseOptions, b4 as FileParseRequest, b5 as FileParseResult, b6 as GenerateImageRequest, b7 as GenerateImageResult, b8 as GenerateObjectRequest, b9 as GeneratedImage, ba as HaiAIError, bb as ImageConfig, bc as ImageConfigSchema, bd as ImageContent, be as ImageModelEntry, bf as ImageModelEntrySchema, bg as ImageOperations, bh as ImageProviderName, bi as ImageProviderSchema, bj as ImageSize, bk as InteractionScope, bl as KnowledgeAskOptions, bm as KnowledgeAskResult, bn as KnowledgeConfig, bo as KnowledgeConfigSchema, bp as KnowledgeDocumentInfo, bq as KnowledgeDocumentListOptions, br as KnowledgeDocumentMetadata, bs as KnowledgeDocumentRemoveOptions, bt as KnowledgeDocumentRevision, bu as KnowledgeEntity, bv as KnowledgeIngestBatchProgress, bw as KnowledgeIngestBatchResult, bx as KnowledgeIngestFileInput, by as KnowledgeIngestInput, bz as KnowledgeIngestResult, bA as KnowledgeOperations, bB as KnowledgeRepairOptions, bC as KnowledgeRepairProgress, bD as KnowledgeRepairResult, bE as KnowledgeRetrieveItem, bF as KnowledgeRetrieveOptions, bG as KnowledgeRetrieveResult, bH as KnowledgeSetupOptions, bI as KnowledgeStore, bJ as LLMConfig, bK as LLMConfigSchema, bL as LLMOperations, bM as MCPConfig, bN as MCPConfigSchema, bO as MCPContext, bP as MCPExternalServer, bQ as MCPExternalServerSchema, bR as MCPOperations, bS as MCPPrompt, bT as MCPPromptArgument, bU as MCPPromptContent, bV as MCPPromptMessage, bW as MCPResource, bX as MCPResourceContent, bY as MCPServerCapabilities, bZ as MCPServerCapabilitiesSchema, b_ as MCPServerConfig, b$ as MCPServerConfigSchema, c0 as MCPToolDefinition, c1 as MCPToolHandler, c2 as ManagedAudioOperations, c3 as ManagedImageOperations, c4 as ManagedLLMOperations, c5 as ManagedMCPOperations, c6 as ManagedRetrievalOperations, c8 as MemoryAccessScope, c9 as MemoryAdminOperations, ca as MemoryClearAllOptions, cb as MemoryClearOptions, cc as MemoryConfig, cd as MemoryConfigSchema, ce as MemoryCoreOperations, cf as MemoryEntry, cg as MemoryEntryInput, ch as MemoryExtractOptions, ci as MemoryInjectionOptions, cj as MemoryListOptions, ck as MemoryListPageOptions, cl as MemoryOperations, cm as MemoryRecallOptions, cn as MemoryType, co as MemoryTypeSchema, cp as MemoryUpdateInput, cq as MessageContent, cr as MessageRole, cs as ModelCapabilitiesSchema, ct as ModelEntry, cu as ModelEntrySchema, cv as ModelScenario, cw as ModelScenarioSchema, cx as ObjectRef, cy as OptionalSecretSchema, cz as OutputFormat, cA as PersonaOperations, cB as PersonaProfile, cC as PersonaProfileInput, cD as PersonaProfileUpdate, cE as PersonaScopeOptions, cF as RagContextItem, cG as RagOperations, cH as RagOptions, cI as RagResult, cJ as RagStreamEvent, cK as ReasoningOperations, cL as ReasoningOptions, cM as ReasoningResult, cN as ReasoningStep, cO as ReasoningStepType, cP as ReasoningStrategy, cQ as ReasoningStreamEvent, cR as ReferenceImage, cS as RerankDocument, cT as RerankItem, cU as RerankOperations, cV as RerankRequest, cW as RerankResponse, cX as ResolveRequiredModelEntryOptions, cY as ResolvedAudioModel, cZ as ResolvedImageModel, c_ as ResolvedModelConfig, c$ as RetrievalConfig, d0 as RetrievalConfigSchema, d1 as RetrievalOperations, d2 as RetrievalRequest, d3 as RetrievalResult, d4 as RetrievalResultItem, d5 as RetrievalSource, d6 as RetrievalSourceConfig, d7 as RetrievalSourceSchema, d8 as SSEDecoder, d9 as SSEEvent, da as ScopedMemoryBinding, db as ScopedMemoryOperations, dc as SessionInfo, dd as StoreFilter, de as StorePage, df as StoreScope, dg as StreamOperations, dh as StreamProcessor, di as StreamResult, dj as SummaryConfig, dk as SummaryConfigSchema, dl as SummaryOperations, dm as SummaryOptions, dn as SummaryResult, dp as SystemMessage, dq as TempModelConfig, dr as TextContent, ds as TokenConfig, dt as TokenConfigSchema, du as TokenOperations, dv as TokenUsage, dw as Tool, dx as ToolAuthorizationRequest, dy as ToolAuthorizer, dz as ToolCall, dA as ToolDefinition, dB as ToolErrorType, dC as ToolExecutionContext, dD as ToolExecutionOptions, dE as ToolMessage, dF as ToolRegistryOperations, dG as ToolRegistryOptions, dH as ToolsOperations, dI as UserMessage, dJ as WhereClause, dK as WhereOperator, dL as WhereValue, dM as ensureAudioCredential, dN as resolveAudioModel, dO as resolveImageModel, dP as resolveModelApi, dQ as resolveModelEntry, dR as serializePlayableAudio } from './ai-acp-types-Df_JG_-t.js';
3
3
  export { A as AudioCapabilitiesRequest, a as AudioContent, b as AudioFormat, c as AudioInputStream, d as AudioModelCapabilities, e as AudioOperations, f as AudioReference, P as PlayableAudio, S as SynthesisEvent, g as SynthesisOptions, h as SynthesisRequest, i as SynthesisResult, j as SynthesisStreamRequest, k as SynthesisTextSegment, T as TranscriptionEvent, l as TranscriptionOptions, m as TranscriptionRequest, n as TranscriptionResult, o as TranscriptionSegment, p as TranscriptionStreamRequest, q as TranscriptionTimestampGranularity, r as TranscriptionWord } from './ai-audio-types-4R5yUAVl.js';
4
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
5
  export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { aiM, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, resolveModelApi, sessionIdentitySchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema, branchNameSchema } from './chunk-HEYVFQC6.js';
2
- export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-HEYVFQC6.js';
1
+ import { aiM, AIConfigSchema, MemoryConfigSchema, ModelEntrySchema, AudioModelEntrySchema, ImageModelEntrySchema, MCPExternalServerSchema, RetrievalSourceSchema, KnowledgeConfigSchema, TokenConfigSchema, SummaryConfigSchema, CompressConfigSchema, ACPConfigSchema, ACPAgentSchema, ACPWorkspaceSchema, AudioConfigSchema, resolveModelEntry, resolveAudioModel, ensureAudioCredential, resolveModelApi, sessionIdentitySchema, ImageConfigSchema, resolveImageModel, ACPPublishSchema, branchNameSchema } from './chunk-SEEJ4D65.js';
2
+ export { A2AConfigSchema, A2ASkillConfigSchema, ACPAgentSchema, ACPConfigSchema, ACPPublishSchema, ACPRepositorySchema, ACPWorkspaceSchema, AIConfigSchema, AUDIO_WS_PATH, ApiTypeSchema, AudioConfigSchema, AudioFormatSchema, AudioModelEntrySchema, AudioOperationSchema, AudioOperationsSchema, AudioProviderSchema, AudioWsClientMessageSchema, AudioWsDoneMessageSchema, AudioWsStartMessageSchema, AudioWsTextMessageSchema, CompressConfigSchema, CompressionStrategySchema, EmbeddingConfigSchema, EntityTypeSchema, FileConfigSchema, ImageConfigSchema, ImageModelEntrySchema, ImageProviderSchema, KnowledgeConfigSchema, LLMConfigSchema, MCPConfigSchema, MCPExternalServerSchema, MCPServerCapabilitiesSchema, MCPServerConfigSchema, MemoryConfigSchema, MemoryTypeSchema, ModelCapabilitiesSchema, ModelEntrySchema, ModelScenarioSchema, OptionalSecretSchema, RetrievalConfigSchema, RetrievalSourceSchema, SummaryConfigSchema, TokenConfigSchema, ensureAudioCredential, resolveAudioModel, resolveImageModel, resolveModelApi, resolveModelEntry, serializePlayableAudio } from './chunk-SEEJ4D65.js';
3
3
  import { HaiAIError } from './chunk-M77C3VAP.js';
4
4
  export { HaiAIError } from './chunk-M77C3VAP.js';
5
5
  import process2 from 'process';
@@ -12,7 +12,7 @@ import { createHash, randomUUID } from 'crypto';
12
12
  import { setTimeout as setTimeout$1 } from 'timers/promises';
13
13
  import { z, ZodError } from 'zod';
14
14
  import { mkdir, realpath } from 'fs/promises';
15
- import { isAbsolute, resolve, relative, dirname, basename } from 'path';
15
+ import { isAbsolute, win32, posix, resolve, relative, dirname, basename } from 'path';
16
16
  import { spawn } from 'child_process';
17
17
  import { Writable, Readable } from 'stream';
18
18
  import { methods, ndJsonStream, client, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
@@ -1866,14 +1866,63 @@ async function connectACP(transport, options = {}, inputLimits) {
1866
1866
  throw error;
1867
1867
  }
1868
1868
  }
1869
-
1870
- // src/acp/ai-acp-git.ts
1871
1869
  function createGitOperations(workspace, runtime) {
1872
1870
  const git = (cwd, args, env) => runtime.run("git", ["-C", cwd, ...args], void 0, {
1873
1871
  GIT_TERMINAL_PROMPT: "0",
1874
1872
  ...env
1875
1873
  });
1876
1874
  const source = (id) => runtime.path(`main/${id}`);
1875
+ const path = !runtime.resource && process2.platform === "win32" ? win32 : posix;
1876
+ const scoped = Object.keys(workspace.gitEnvironmentRefs).length > 0;
1877
+ const remoteUrl = (url, cwd) => path.isAbsolute(url) || /^[^/\\]+:/.test(url) ? url : path.resolve(cwd, url);
1878
+ async function withRemoteGit(action, main) {
1879
+ const references = workspace.gitEnvironmentRefs;
1880
+ if (runtime.resource) {
1881
+ const engineKeys = new Set(Object.keys(engineEnvironment()).map((key) => key.toUpperCase()));
1882
+ if (Object.keys(references).some((key) => engineKeys.has(key.toUpperCase())))
1883
+ throw new ACPFailure("invalid");
1884
+ }
1885
+ const credentials = resolveEnvironment(references);
1886
+ return runtime.withTemporaryDirectory(async (directory) => {
1887
+ const options = ["-c", `core.hooksPath=${path.join(directory, "disabled-hooks")}`];
1888
+ const home = { HOME: directory, USERPROFILE: directory, XDG_CONFIG_HOME: directory };
1889
+ const privateGit = (args, env) => runtime.run("git", ["-C", directory, ...options, ...args], directory, { ...home, ...env, GIT_TERMINAL_PROMPT: "0" }, false);
1890
+ if (main) {
1891
+ const format = await git(main, ["rev-parse", "--show-object-format"]);
1892
+ const objects = await git(main, ["rev-parse", "--path-format=absolute", "--git-path", "objects"]);
1893
+ if (format !== "sha1" && format !== "sha256" || !path.isAbsolute(objects) || /[\r\n]/.test(objects))
1894
+ throw new ACPFailure("conflict");
1895
+ await privateGit(["init", "--bare", "--template=", `--object-format=${format}`]);
1896
+ await runtime.run(runtime.resource ? "node" : process2.execPath, [
1897
+ "-e",
1898
+ 'require("node:fs").writeFileSync(process.argv[1], process.argv[2] + "\\n", { flag: "wx" })',
1899
+ path.join(directory, "objects", "info", "alternates"),
1900
+ objects
1901
+ ], directory, void 0, false);
1902
+ }
1903
+ return action(directory, (args) => privateGit(args, credentials));
1904
+ });
1905
+ }
1906
+ async function clone(repo) {
1907
+ const cloneArgs = ["clone", "--origin", repo.remote, "--branch", repo.mainBranch];
1908
+ if (!scoped)
1909
+ return git(runtime.root, [...cloneArgs, "--", repo.url, source(repo.id)]);
1910
+ return withRemoteGit(async (directory, remoteGit) => {
1911
+ const staged = path.join(directory, "remote.git");
1912
+ await remoteGit(["clone", "--bare", "--no-local", "--template=", "--branch", repo.mainBranch, "--", remoteUrl(repo.url, runtime.root), staged]);
1913
+ await git(runtime.root, [...cloneArgs, "--", staged, source(repo.id)]);
1914
+ return git(source(repo.id), ["remote", "set-url", repo.remote, repo.url]);
1915
+ });
1916
+ }
1917
+ async function fetchMain(repo, main) {
1918
+ const ref = `refs/heads/${repo.mainBranch}`;
1919
+ if (!scoped)
1920
+ return git(main, ["fetch", "--", repo.remote, ref]);
1921
+ return withRemoteGit(async (directory, remoteGit) => {
1922
+ await remoteGit(["fetch", "--no-recurse-submodules", "--", remoteUrl(repo.url, main), `${ref}:${ref}`]);
1923
+ return git(main, ["fetch", "--no-recurse-submodules", "--", directory, ref]);
1924
+ }, main);
1925
+ }
1877
1926
  async function ready() {
1878
1927
  if (!workspace.repositories.length)
1879
1928
  return;
@@ -1883,27 +1932,27 @@ function createGitOperations(workspace, runtime) {
1883
1932
  throw new ACPFailure("gitMissing");
1884
1933
  }
1885
1934
  }
1886
- async function clean(path) {
1887
- if (await git(path, ["status", "--porcelain"]))
1935
+ async function clean(path2) {
1936
+ if (await git(path2, ["status", "--porcelain", "--untracked-files=normal"]))
1888
1937
  throw new ACPFailure("conflict");
1889
1938
  }
1890
- async function supportedContent(path) {
1891
- const index = await git(path, ["ls-files", "--stage", "-z"]);
1939
+ async function supportedContent(path2) {
1940
+ const index = await git(path2, ["ls-files", "--stage", "-z"]);
1892
1941
  if (index.split("\0").some((entry) => entry.startsWith("160000 ")))
1893
1942
  throw new ACPFailure("unsupported");
1894
- const attributes = await git(path, ["ls-files", "-z", "--", ".gitattributes", ":(glob)**/.gitattributes"]);
1943
+ const attributes = await git(path2, ["ls-files", "-z", "--", ".gitattributes", ":(glob)**/.gitattributes"]);
1895
1944
  for (const file of attributes.split("\0").filter(Boolean)) {
1896
- const content = await git(path, ["show", `HEAD:${file}`]);
1945
+ const content = await git(path2, ["show", `HEAD:${file}`]);
1897
1946
  if (content.split("\n").some((line) => !line.trimStart().startsWith("#") && /\bfilter=lfs\b/.test(line)))
1898
1947
  throw new ACPFailure("unsupported");
1899
1948
  }
1900
1949
  }
1901
- async function checked(repo, path = source(repo.id), branch = repo.mainBranch) {
1902
- if (await git(path, ["branch", "--show-current"]) !== branch)
1950
+ async function checked(repo, path2 = source(repo.id), branch = repo.mainBranch) {
1951
+ await runtime.file("directory", path2);
1952
+ if (await git(path2, ["branch", "--show-current"]) !== branch)
1903
1953
  throw new ACPFailure("conflict");
1904
- if (await git(path, ["remote", "get-url", repo.remote]) !== repo.url)
1954
+ if (await git(path2, ["remote", "get-url", repo.remote]) !== repo.url)
1905
1955
  throw new ACPFailure("conflict");
1906
- await runtime.file("exists", path);
1907
1956
  }
1908
1957
  async function reports(operation) {
1909
1958
  await ready();
@@ -1946,37 +1995,26 @@ function createGitOperations(workspace, runtime) {
1946
1995
  "--branch",
1947
1996
  repo.mainBranch
1948
1997
  ]);
1949
- if (await runtime.file("exists", `main/${repo.id}`) === "false") {
1950
- await git(runtime.root, [
1951
- "clone",
1952
- "--origin",
1953
- repo.remote,
1954
- "--branch",
1955
- repo.mainBranch,
1956
- "--",
1957
- repo.url,
1958
- source(repo.id)
1959
- ]);
1960
- }
1998
+ if (await runtime.file("exists", `main/${repo.id}`) === "false")
1999
+ await clone(repo);
1961
2000
  await checked(repo);
1962
2001
  await supportedContent(source(repo.id));
1963
2002
  }
1964
2003
  return runtime.path("main");
1965
2004
  },
1966
2005
  /**
1967
- * 从每个工程本地主分支创建独立工作树并复制普通文件。
1968
- * @param sessionId - 已校验的框架会话 ID。
2006
+ * 在调用方独占的会话目录创建各工程工作树并复制普通文件。
2007
+ * @param sessionId - 已校验且已独占会话目录的框架会话 ID。
1969
2008
  * @param branch - 所有工程使用的同名新分支。
1970
- * @returns 独立会话目录;中途失败不回滚已有工作树。
2009
+ * @returns 完成后返回;中途失败保留已建立的工作树。
1971
2010
  * @example
1972
2011
  * ```ts
1973
2012
  * // 内部上下文:runtime/git/connection 为相应工厂已创建的句柄。
1974
- * const directory = await git.createWorktree('task-1', 'acp/task-1')
2013
+ * await git.createWorktree('task-1', 'acp/task-1')
1975
2014
  * ```
1976
2015
  */
1977
2016
  async createWorktree(sessionId, branch) {
1978
2017
  await ready();
1979
- await runtime.file("mkdir", `sessions/${sessionId}`);
1980
2018
  for (const repo of workspace.repositories) {
1981
2019
  await checked(repo);
1982
2020
  await supportedContent(source(repo.id));
@@ -1991,7 +2029,46 @@ function createGitOperations(workspace, runtime) {
1991
2029
  ]);
1992
2030
  }
1993
2031
  await runtime.file("copy", "main/files", `sessions/${sessionId}/files`);
1994
- return runtime.path(`sessions/${sessionId}`);
2032
+ },
2033
+ /**
2034
+ * 预检所有登记的会话工作树,确认回收状态已持久化后逐个执行 Git 移除。
2035
+ * @param sessionId - 持久记录所拥有的会话目录 ID。
2036
+ * @param branch - 创建时登记的会话分支。
2037
+ * @param begin - 写入开始回收的持久状态;写入失败时不删除工作树。
2038
+ * @returns 回收完成;失败保留其他工作树供重试。
2039
+ * @example
2040
+ * ```ts
2041
+ * // 模块内部上下文:git 为工厂已创建的句柄,回调由持有会话锁的调用方提供。
2042
+ * await git.reclaimWorktree('task-1', 'acp/task-1', async () => {})
2043
+ * ```
2044
+ */
2045
+ async reclaimWorktree(sessionId, branch, begin) {
2046
+ await ready();
2047
+ const paths = [];
2048
+ for (const repo of workspace.repositories) {
2049
+ await checked(repo);
2050
+ const main = source(repo.id);
2051
+ const worktree = runtime.path(`sessions/${sessionId}/${repo.id}`);
2052
+ const exists = await runtime.file("exists", worktree) === "true";
2053
+ const registrations = await git(main, ["worktree", "list", "--porcelain", "-z"]);
2054
+ const registration = registrations.split("\0\0").map((entry) => entry.split("\0")).find(([entry]) => {
2055
+ if (!entry?.startsWith("worktree "))
2056
+ return false;
2057
+ const registeredPath = entry.slice("worktree ".length);
2058
+ return !runtime.resource && process2.platform === "win32" ? win32.relative(registeredPath, worktree) === "" : registeredPath === worktree;
2059
+ });
2060
+ if (!registration && !exists)
2061
+ continue;
2062
+ if (!registration?.includes(`branch refs/heads/${branch}`) || registration.some((entry) => entry === "locked" || entry.startsWith("locked "))) {
2063
+ throw new ACPFailure("conflict");
2064
+ }
2065
+ if (exists)
2066
+ await clean(worktree);
2067
+ paths.push({ main, worktree });
2068
+ }
2069
+ await begin();
2070
+ for (const { main, worktree } of paths)
2071
+ await git(main, ["worktree", "remove", "--", worktree]);
1995
2072
  },
1996
2073
  /**
1997
2074
  * 更新各工程主分支,只允许快进合并。
@@ -2003,19 +2080,14 @@ function createGitOperations(workspace, runtime) {
2003
2080
  * ```
2004
2081
  */
2005
2082
  updateMain: () => reports(async (repo, report) => {
2006
- const path = source(repo.id);
2083
+ const path2 = source(repo.id);
2007
2084
  await checked(repo);
2008
- await clean(path);
2085
+ await clean(path2);
2009
2086
  report.phase = "fetch";
2010
- await git(path, [
2011
- "fetch",
2012
- "--",
2013
- repo.remote,
2014
- `refs/heads/${repo.mainBranch}`
2015
- ]);
2087
+ await fetchMain(repo, path2);
2016
2088
  report.phase = "merge";
2017
- await git(path, ["merge", "--ff-only", "FETCH_HEAD"]);
2018
- report.commit = await git(path, ["rev-parse", "HEAD"]);
2089
+ await git(path2, ["merge", "--ff-only", "FETCH_HEAD"]);
2090
+ report.commit = await git(path2, ["rev-parse", "HEAD"]);
2019
2091
  }),
2020
2092
  /**
2021
2093
  * 逐仓提交会话修改并发布,禁止强推。
@@ -2053,12 +2125,7 @@ function createGitOperations(workspace, runtime) {
2053
2125
  let targetBranch = branch;
2054
2126
  if (request.mode === "merge-main") {
2055
2127
  report.phase = "fetch";
2056
- await git(main, [
2057
- "fetch",
2058
- "--",
2059
- repo.remote,
2060
- `refs/heads/${repo.mainBranch}`
2061
- ]);
2128
+ await fetchMain(repo, main);
2062
2129
  report.phase = "merge";
2063
2130
  const remoteHead = await git(main, ["rev-parse", "FETCH_HEAD"]);
2064
2131
  const localHead = await git(main, ["rev-parse", "HEAD"]);
@@ -2072,13 +2139,16 @@ function createGitOperations(workspace, runtime) {
2072
2139
  targetBranch = repo.mainBranch;
2073
2140
  }
2074
2141
  report.phase = "push";
2075
- await git(target, [
2076
- "push",
2077
- "--",
2078
- repo.remote,
2079
- `HEAD:refs/heads/${targetBranch}`
2080
- ]);
2081
- report.commit = await git(target, ["rev-parse", "HEAD"]);
2142
+ if (scoped) {
2143
+ const commit = await git(target, ["rev-parse", "HEAD"]);
2144
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit))
2145
+ throw new ACPFailure("conflict");
2146
+ await withRemoteGit(async (_, remoteGit) => remoteGit(["push", "--no-recurse-submodules", "--", remoteUrl(repo.url, target), `${commit}:refs/heads/${targetBranch}`]), main);
2147
+ report.commit = commit;
2148
+ } else {
2149
+ await git(target, ["push", "--", repo.remote, `HEAD:refs/heads/${targetBranch}`]);
2150
+ report.commit = await git(target, ["rev-parse", "HEAD"]);
2151
+ }
2082
2152
  })
2083
2153
  };
2084
2154
  }
@@ -2097,6 +2167,8 @@ const fs = require('node:fs/promises'); const path = require('node:path');
2097
2167
  catch (e) { if (e.code !== 'ENOENT') throw e; }
2098
2168
  }
2099
2169
  if (op === 'mkdir') await fs.mkdir(target, { recursive: true });
2170
+ else if (op === 'mkdir-exclusive') await fs.mkdir(target);
2171
+ else if (op === 'directory') { if (!(await fs.stat(target)).isDirectory()) throw Error('directory'); }
2100
2172
  else if (op === 'exists') process.stdout.write(String(await fs.stat(target).then(() => true, e => { if(e.code === 'ENOENT') return false; throw e; })));
2101
2173
  else if (op === 'write') { await fs.mkdir(path.dirname(target), { recursive: true }); await fs.writeFile(target, Buffer.from(content, 'base64'), { flag: 'wx', mode: 0o600 }); }
2102
2174
  else if (op === 'read') process.stdout.write((await fs.readFile(target)).toString('base64'));
@@ -2182,9 +2254,9 @@ async function openRuntime(workspace) {
2182
2254
  throw new ACPFailure("closed");
2183
2255
  };
2184
2256
  const path = (relative2) => workspace.storage.type === "volume" ? `${root}/${relative2}` : resolve(root, relative2);
2185
- function transport(command, args, cwd, env = {}) {
2257
+ function transport(command, args, cwd, env = {}, inheritWorkspaceEnvironment = true) {
2186
2258
  ensure();
2187
- const values = { ...environment, ...env };
2259
+ const values = inheritWorkspaceEnvironment ? { ...environment, ...env } : env;
2188
2260
  return engine && container ? {
2189
2261
  type: "stdio",
2190
2262
  command: engine,
@@ -2204,8 +2276,8 @@ async function openRuntime(workspace) {
2204
2276
  env: { ...values, ...engineEnvironment() }
2205
2277
  } : { type: "stdio", command, args, cwd, env: values };
2206
2278
  }
2207
- async function run(command, args, cwd = root, env) {
2208
- const launch = transport(command, args, cwd, env);
2279
+ async function run(command, args, cwd = root, env, inheritWorkspaceEnvironment = true) {
2280
+ const launch = transport(command, args, cwd, env, inheritWorkspaceEnvironment);
2209
2281
  if (launch.type !== "stdio")
2210
2282
  throw new ACPFailure("runtime");
2211
2283
  return execute(launch.command, launch.args ?? [], launch.cwd, launch.env);
@@ -2216,6 +2288,34 @@ async function openRuntime(workspace) {
2216
2288
  transport,
2217
2289
  run,
2218
2290
  resource: container ? { engine, container } : void 0,
2291
+ /**
2292
+ * 在运行端创建并回收私有临时目录,目录位于工作区挂载之外。
2293
+ * @param action - 在临时目录存在时执行的操作。
2294
+ * @returns 操作结果;成功或失败都清理当前调用拥有的目录。
2295
+ * @example
2296
+ * ```ts
2297
+ * // 模块内部上下文:runtime 为已打开的执行环境。
2298
+ * await runtime.withTemporaryDirectory(directory => runtime.run('git', ['-C', directory, 'init', '--bare']))
2299
+ * ```
2300
+ */
2301
+ async withTemporaryDirectory(action) {
2302
+ const node = engine ? "node" : process2.execPath;
2303
+ const directory = await run(node, ["-e", `
2304
+ const fs = require('node:fs');
2305
+ const path = require('node:path');
2306
+ const base = fs.realpathSync(process.argv[1] || require('node:os').tmpdir());
2307
+ for (const mount of process.argv.slice(2)) {
2308
+ const relative = path.relative(fs.realpathSync(mount), base);
2309
+ if (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)) throw Error('scope');
2310
+ }
2311
+ process.stdout.write(fs.mkdtempSync(path.join(base, 'hai-acp-git-')));
2312
+ `, ...engine ? ["/tmp", root, "/state"] : ["", root]], root, void 0, false);
2313
+ try {
2314
+ return await action(directory);
2315
+ } finally {
2316
+ await run(node, ["-e", 'require("node:fs").rmSync(process.argv[1], { recursive: true, force: true })', directory], root, void 0, false);
2317
+ }
2318
+ },
2219
2319
  /**
2220
2320
  * 计算受管理的会话状态目录。
2221
2321
  * @param sessionId - 已校验的会话 ID。
@@ -2229,7 +2329,7 @@ async function openRuntime(workspace) {
2229
2329
  state: (sessionId) => workspace.storage.type === "volume" ? `/state/${sessionId}` : path(`.state/${sessionId}`),
2230
2330
  /**
2231
2331
  * 执行受工作区约束的文件操作,拒绝链接和路径逃逸。
2232
- * @param op - mkdir/exists/write/read/copy 操作。
2332
+ * @param op - mkdir/mkdir-exclusive/directory/exists/write/read/copy 操作。
2233
2333
  * @param name - 工作区内相对路径或已校验的内部绝对路径。
2234
2334
  * @param content - write 时为 Base64,copy 时为目标路径,其余为空。
2235
2335
  * @returns 文本结果:exists 为 true/false,read 为 Base64,其余为空。
@@ -2403,6 +2503,48 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2403
2503
  return workspace;
2404
2504
  }
2405
2505
  const workspaceKey = (workspace) => workspace.storage.type === "directory" ? `directory:${process2.platform === "win32" ? workspace.storage.path.toLowerCase() : workspace.storage.path}` : `volume:${workspace.storage.engine}:${workspace.storage.name}`;
2506
+ const sessionDirectory = (info) => info.newWorktree ? `sessions/${info.id}` : "main";
2507
+ function describeWorkspace(workspace, runtime, info) {
2508
+ const directory = sessionDirectory(info);
2509
+ const { storage } = workspace;
2510
+ let location;
2511
+ if (storage.type === "directory") {
2512
+ location = { type: "directory", path: runtime.root };
2513
+ } else {
2514
+ const { engine, name } = storage;
2515
+ if (engine === "auto")
2516
+ throw new ACPFailure("runtime");
2517
+ location = { type: "volume", engine, name, mountPath: runtime.root };
2518
+ }
2519
+ return {
2520
+ storage: location,
2521
+ path: runtime.path(directory),
2522
+ repositories: workspace.repositories.map((repo) => ({
2523
+ id: repo.id,
2524
+ path: runtime.path(`${directory}/${repo.id}`)
2525
+ }))
2526
+ };
2527
+ }
2528
+ function checkStorage(workspace, info) {
2529
+ const pinned = info.workspace?.storage;
2530
+ if (!pinned)
2531
+ return;
2532
+ const current = workspace.storage;
2533
+ const matches = pinned.type === "directory" ? current.type === "directory" && pinned.path === current.path : current.type === "volume" && pinned.name === current.name && pinned.engine === current.engine;
2534
+ if (!matches)
2535
+ throw new ACPFailure("conflict");
2536
+ }
2537
+ function checkLayout(workspace, runtime, info) {
2538
+ const current = describeWorkspace(workspace, runtime, info);
2539
+ const paths = new Map(current.repositories.map((repo) => [repo.id, repo.path]));
2540
+ const cwd = info.repositoryId ? paths.get(info.repositoryId) : current.path;
2541
+ if (info.cwd !== cwd)
2542
+ throw new ACPFailure("conflict");
2543
+ const pinned = info.workspace;
2544
+ if (pinned && (pinned.path !== current.path || pinned.repositories.length !== paths.size || pinned.repositories.some((repo) => paths.get(repo.id) !== repo.path))) {
2545
+ throw new ACPFailure("conflict");
2546
+ }
2547
+ }
2406
2548
  async function normalizeWorkspace(workspace) {
2407
2549
  if (workspace.storage.type === "directory") {
2408
2550
  await mkdir(workspace.storage.path, { recursive: true });
@@ -2557,20 +2699,24 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2557
2699
  live.delete(id);
2558
2700
  }
2559
2701
  async function start(info, options, resume) {
2560
- const agent = info.agent;
2561
2702
  const releaseSession = await acquire(`session:${info.id}`);
2562
2703
  let releaseDirectory;
2563
2704
  let runtime;
2564
2705
  let connection;
2565
- let recordExists = true;
2706
+ let recordMutable = !resume;
2566
2707
  try {
2708
+ if (resume) {
2709
+ info = await get(sessions, info.id);
2710
+ if (info.status === "opening" || info.status === "active")
2711
+ throw new ACPFailure("busy");
2712
+ if (info.worktreeStatus)
2713
+ throw new ACPFailure("closed");
2714
+ recordMutable = true;
2715
+ }
2716
+ const agent = info.agent;
2567
2717
  const workspace = info.workspaceId ? await getWorkspace(info.workspaceId) : void 0;
2568
2718
  if (!agent.enabled)
2569
2719
  throw new ACPFailure("unsupported");
2570
- if (resume && !await sessions.get(info.id)) {
2571
- recordExists = false;
2572
- throw new ACPFailure("missing");
2573
- }
2574
2720
  if (workspace) {
2575
2721
  if (agent.mode === "custom-service")
2576
2722
  throw new ACPFailure("unsupported");
@@ -2582,6 +2728,8 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2582
2728
  }
2583
2729
  if (!info.newWorktree)
2584
2730
  releaseDirectory = await acquire(`${workspaceKey(workspace)}:main`);
2731
+ checkStorage(workspace, info);
2732
+ const directory = sessionDirectory(info);
2585
2733
  if (!resume) {
2586
2734
  const releasePrepare = info.newWorktree ? await acquire(`${workspaceKey(workspace)}:main`) : void 0;
2587
2735
  try {
@@ -2590,13 +2738,24 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2590
2738
  await sessions.save(info.id, info);
2591
2739
  const git = createGitOperations(workspace, runtime);
2592
2740
  await git.prepare();
2593
- info.cwd = info.newWorktree ? await git.createWorktree(info.id, info.branch) : runtime.path("main");
2741
+ const layout = describeWorkspace(workspace, runtime, info);
2742
+ if (info.newWorktree) {
2743
+ await runtime.file("mkdir", "sessions");
2744
+ await runtime.file("mkdir-exclusive", directory);
2745
+ }
2746
+ info.workspace = layout;
2747
+ info.cwd = layout.repositories.find((repo) => repo.id === info.repositoryId)?.path ?? layout.path;
2748
+ await sessions.save(info.id, info);
2749
+ if (info.newWorktree)
2750
+ await git.createWorktree(info.id, info.branch);
2594
2751
  } finally {
2595
2752
  await releasePrepare?.();
2596
2753
  }
2597
2754
  } else {
2598
2755
  runtime = await openRuntime(workspace);
2599
2756
  }
2757
+ checkLayout(workspace, runtime, info);
2758
+ await runtime.file("directory", info.cwd);
2600
2759
  } else if (agent.mode !== "custom-service" || !info.cwd || info.newWorktree) {
2601
2760
  throw new ACPFailure("invalid");
2602
2761
  }
@@ -2636,7 +2795,7 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2636
2795
  await runtime?.close();
2637
2796
  info.status = "failed";
2638
2797
  info.resource = void 0;
2639
- if (recordExists)
2798
+ if (recordMutable)
2640
2799
  await sessions.save(info.id, info);
2641
2800
  await releaseDirectory?.();
2642
2801
  await releaseSession();
@@ -2656,15 +2815,23 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
2656
2815
  const info = await get(sessions, id);
2657
2816
  if (!info.workspaceId || request && !info.newWorktree)
2658
2817
  throw new ACPFailure("unsupported");
2659
- const workspace = await getWorkspace(info.workspaceId);
2660
2818
  await stop(id);
2661
2819
  const release = await acquire(`session:${id}`);
2662
2820
  try {
2663
- return await workspaceOperation(workspace, (runtime) => request ? createGitOperations(workspace, runtime).publish(
2664
- id,
2665
- info.branch,
2666
- request
2667
- ) : createGitOperations(workspace, runtime).updateMain());
2821
+ const current2 = await get(sessions, id);
2822
+ if (!current2.workspaceId || request && !current2.newWorktree)
2823
+ throw new ACPFailure("unsupported");
2824
+ if (request && current2.worktreeStatus)
2825
+ throw new ACPFailure("closed");
2826
+ const workspace = await getWorkspace(current2.workspaceId);
2827
+ checkStorage(workspace, current2);
2828
+ return await workspaceOperation(workspace, (runtime) => {
2829
+ const git = createGitOperations(workspace, runtime);
2830
+ if (!request)
2831
+ return git.updateMain();
2832
+ checkLayout(workspace, runtime, current2);
2833
+ return git.publish(id, current2.branch, request);
2834
+ });
2668
2835
  } finally {
2669
2836
  await release();
2670
2837
  }
@@ -3195,14 +3362,14 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
3195
3362
  sessions: {
3196
3363
  /**
3197
3364
  * 绑定模型、工作区和 MCP,准备目录后建立原生会话;newWorktree 可选择独立工程分支。
3198
- * @param options - 智能体、工作区、模型、MCP 及可信回调;newWorktree 默认 false。
3365
+ * @param options - 智能体、工作区、可选会话仓库、模型、MCP 及可信回调;newWorktree 默认 false。
3199
3366
  * @returns 可用于 prompt/stream/publish 的会话句柄;启动失败保留失败记录。
3200
3367
  * @example
3201
3368
  * ```ts
3202
3369
  * import { ai } from '@h-ai/ai'
3203
3370
  * // 前提:ai 已成功初始化。
3204
3371
  * // 普通 API 先检查 result.success,再读取 data 或 error。
3205
- * const result = await ai.acp.sessions.create({ agentId: 'coder', workspaceId: 'project', newWorktree: true })
3372
+ * const result = await ai.acp.sessions.create({ agentId: 'coder', workspaceId: 'project', repositoryId: 'api', newWorktree: true })
3206
3373
  * ```
3207
3374
  */
3208
3375
  create: (options) => protect(async () => {
@@ -3215,10 +3382,19 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
3215
3382
  const modelId = options.modelId ?? agent.defaultModelId ?? agent.modelIds[0];
3216
3383
  if (modelId && !agent.modelIds.includes(modelId))
3217
3384
  throw new ACPFailure("model");
3385
+ const workspace = options.workspaceId ? await getWorkspace(options.workspaceId) : void 0;
3386
+ if (options.repositoryId !== void 0) {
3387
+ sessionIdentitySchema.parse(options.repositoryId);
3388
+ if (!workspace || agent.mode === "custom-service" || options.cwd !== void 0)
3389
+ throw new ACPFailure("invalid");
3390
+ if (!workspace.repositories.some((repo) => repo.id === options.repositoryId))
3391
+ throw new ACPFailure("missing", { id: options.repositoryId });
3392
+ }
3218
3393
  const info2 = {
3219
3394
  id,
3220
3395
  agentId: agent.id,
3221
3396
  workspaceId: options.workspaceId,
3397
+ repositoryId: options.repositoryId,
3222
3398
  cwd: options.cwd ?? "",
3223
3399
  newWorktree: options.newWorktree ?? false,
3224
3400
  branch: options.newWorktree ? branchNameSchema.parse(options.branch ?? `acp/${id}`) : void 0,
@@ -3229,8 +3405,6 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
3229
3405
  mcpServers: options.mcpServers ?? [],
3230
3406
  mcpServerIds: options.mcpServerIds
3231
3407
  };
3232
- if (options.workspaceId)
3233
- await getWorkspace(options.workspaceId);
3234
3408
  await unique(sessions, id, info2);
3235
3409
  return info2;
3236
3410
  });
@@ -3305,6 +3479,44 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
3305
3479
  * ```
3306
3480
  */
3307
3481
  close: (id) => protect(() => stop(id)),
3482
+ /**
3483
+ * 回收停止后由框架登记的干净工作树;调用方须先停止独立预览。
3484
+ * @param id - 框架会话 ID;仅支持记录了归属的独立 Git 会话。
3485
+ * @returns 回收完成的 HaiResult;可重试,保留分支、普通文件及原生历史。
3486
+ * @example
3487
+ * ```ts
3488
+ * import { ai } from '@h-ai/ai'
3489
+ * // 前提:已关闭 Agent,已停止预览并提交或另存修改。
3490
+ * const result = await ai.acp.sessions.reclaimWorktree('task-1')
3491
+ * if (!result.success) throw new Error(result.error.message)
3492
+ * ```
3493
+ */
3494
+ reclaimWorktree: (id) => protect(async () => {
3495
+ sessionIdentitySchema.parse(id);
3496
+ const release = await acquire(`session:${id}`);
3497
+ try {
3498
+ const info = await get(sessions, id);
3499
+ if (info.status === "opening" || info.status === "active" || info.resource)
3500
+ throw new ACPFailure("busy");
3501
+ if (info.worktreeStatus === "reclaimed")
3502
+ return;
3503
+ if (!info.workspaceId || !info.workspace?.repositories.length || !info.newWorktree || !info.branch)
3504
+ throw new ACPFailure("unsupported");
3505
+ const workspace = await getWorkspace(info.workspaceId);
3506
+ checkStorage(workspace, info);
3507
+ await workspaceOperation(workspace, async (runtime) => {
3508
+ checkLayout(workspace, runtime, info);
3509
+ await createGitOperations(workspace, runtime).reclaimWorktree(id, info.branch, async () => {
3510
+ info.worktreeStatus = "reclaiming";
3511
+ await sessions.save(id, info);
3512
+ });
3513
+ info.worktreeStatus = "reclaimed";
3514
+ await sessions.save(id, info);
3515
+ });
3516
+ } finally {
3517
+ await release();
3518
+ }
3519
+ }),
3308
3520
  /**
3309
3521
  * 仅删除已关闭或失败的会话记录;不删除工作树及原生文件,不替代 Git worktree 清理。
3310
3522
  * @param id - 框架会话 ID。
@@ -3318,12 +3530,12 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
3318
3530
  * ```
3319
3531
  */
3320
3532
  remove: (id) => protect(async () => {
3321
- const info = await get(sessions, id);
3322
- if (live.has(id) || info.status === "active" || info.status === "opening") {
3323
- throw new ACPFailure("busy");
3324
- }
3533
+ sessionIdentitySchema.parse(id);
3325
3534
  const release = await acquire(`session:${id}`);
3326
3535
  try {
3536
+ const info = await get(sessions, id);
3537
+ if (info.status === "active" || info.status === "opening" || info.worktreeStatus === "reclaiming")
3538
+ throw new ACPFailure("busy");
3327
3539
  await sessions.remove(id);
3328
3540
  } finally {
3329
3541
  await release();