@maxmo74/pi-coding-agent 1.4.0-max.2 → 1.4.0-max.3
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/README.md +8 -2
- package/dist/bundle/chunks/{chunk-CROFGA3S.js → chunk-N6ZHTIEL.js} +1 -1
- package/dist/bundle/chunks/{chunk-BRAJAC52.js → chunk-UH6VPJL7.js} +9 -9
- package/dist/bundle/chunks/{virtual-modules-UF6ZXK6X.js → virtual-modules-TW6KBQM5.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +5 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/session-ownership.d.ts +9 -0
- package/dist/core/session-ownership.d.ts.map +1 -1
- package/dist/core/session-ownership.js +59 -27
- package/dist/core/session-ownership.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -3
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +8 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts +5 -0
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +27 -13
- package/dist/package-manager-cli.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{dist_exports as dist_exports3}from"./chunk-
|
|
2
|
+
import{dist_exports as dist_exports3}from"./chunk-N6ZHTIEL.js";import{all_exports,compat_exports,compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-UH6VPJL7.js";import{build_exports}from"./chunk-AFNTYPTW.js";import"./chunk-ZN2R65UF.js";import{dist_exports}from"./chunk-LAMEVJ4W.js";import"./chunk-KFM2CJ7Q.js";import"./chunk-HQBQWHLD.js";import"./chunk-HODJBMOY.js";import"./chunk-6QGV3IWD.js";import"./chunk-BSS6T6KQ.js";import"./chunk-USJZMAIR.js";import"./chunk-5AGIVGSV.js";import"./chunk-UKVNB6C4.js";import"./chunk-TMTOQ7H7.js";import"./chunk-7DDKXS2Q.js";import"./chunk-FFMDRXC4.js";import{models_exports}from"./chunk-4UNN5OGR.js";import"./chunk-LPXNMA2W.js";import"./chunk-BPHHHEET.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/models":models_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/models":models_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-UH6VPJL7.js";import"./chunks/chunk-AFNTYPTW.js";import"./chunks/chunk-ZN2R65UF.js";import"./chunks/chunk-LAMEVJ4W.js";import"./chunks/chunk-KFM2CJ7Q.js";import"./chunks/chunk-HQBQWHLD.js";import"./chunks/chunk-HODJBMOY.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-BSS6T6KQ.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-4UNN5OGR.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-BPHHHEET.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-
|
|
2
|
+
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-N6ZHTIEL.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-UH6VPJL7.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatReadLineRange,formatSize,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-AFNTYPTW.js";import{ArminComponent}from"./chunks/chunk-ZN2R65UF.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-LAMEVJ4W.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-KFM2CJ7Q.js";import{readStoredCredential}from"./chunks/chunk-HQBQWHLD.js";import{getPowerShellConfig,getShellConfig}from"./chunks/chunk-HODJBMOY.js";import"./chunks/chunk-6QGV3IWD.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-BSS6T6KQ.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-4UNN5OGR.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-BPHHHEET.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatReadLineRange,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-UH6VPJL7.js";import"./chunks/chunk-AFNTYPTW.js";import"./chunks/chunk-ZN2R65UF.js";import"./chunks/chunk-LAMEVJ4W.js";import"./chunks/chunk-KFM2CJ7Q.js";import"./chunks/chunk-HQBQWHLD.js";import"./chunks/chunk-HODJBMOY.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-BSS6T6KQ.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-UKVNB6C4.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-4UNN5OGR.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-BPHHHEET.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-runtime.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,6BAA6B,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACvG,OAAO,KAAK,EACX,mBAAmB,EACnB,sBAAsB,EAEtB,iBAAiB,EACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD;;;;;GAKG;AACH,MAAM,WA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GAKG;AACH,wBAAsB,yBAAyB,CAC9C,aAAa,EAAE,gCAAgC,EAC/C,OAAO,EAAE;IACR,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC,GACC,OAAO,CAAC,mBAAmB,CAAC,CAU9B;AAED,OAAO,EACN,KAAK,6BAA6B,EAClC,KAAK,oBAAoB,EACzB,KAAK,qCAAqC,EAC1C,KAAK,iCAAiC,EACtC,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC"}
|
|
@@ -4,7 +4,7 @@ import { resolvePath } from "../utils/paths.js";
|
|
|
4
4
|
import { emitSessionShutdownEvent } from "./extensions/runner.js";
|
|
5
5
|
import { assertSessionCwdExists } from "./session-cwd.js";
|
|
6
6
|
import { SessionManager } from "./session-manager.js";
|
|
7
|
-
import { withSessionOwnershipGate } from "./session-ownership.js";
|
|
7
|
+
import { getSessionOpenRefusal, withSessionOwnershipGate } from "./session-ownership.js";
|
|
8
8
|
/**
|
|
9
9
|
* Thrown when /import references a JSONL file path that does not exist.
|
|
10
10
|
*/
|
|
@@ -151,6 +151,10 @@ export class AgentSessionRuntime {
|
|
|
151
151
|
return beforeResult;
|
|
152
152
|
}
|
|
153
153
|
const previousSessionFile = this.session.sessionFile;
|
|
154
|
+
const refusal = getSessionOpenRefusal(sessionPath);
|
|
155
|
+
if (refusal) {
|
|
156
|
+
throw new Error(refusal);
|
|
157
|
+
}
|
|
154
158
|
const sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);
|
|
155
159
|
await this.replaceWithManager(sessionManager, "resume", previousSessionFile, options?.projectTrustContextFactory);
|
|
156
160
|
await this.finishSessionReplacement(options?.withSession);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mapp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B,CAAC,cAAc,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC;QAC7E,MAAM,IAAI,CAAC,wBAAwB,EAAE,CAAC;QACtC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,OAAO;QACZ,MAAM,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE;YAC5D,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,MAAM;SACd,CAAC,CAAC;QACH,IAAI,CAAC,uBAAuB,EAAE,EAAE,CAAC;QACjC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,aAA+C,EAC/C,OAKC;IAED,sBAAsB,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,IAAI,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,CAC3B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { constants, copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, parse, resolve } from \"node:path\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\nimport { withSessionOwnershipGate } from \"./session-ownership.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\tprivate _session: AgentSession;\n\tprivate _services: AgentSessionServices;\n\tprivate readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tprivate _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tprivate _modelFallbackMessage?: string;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\t// Settle any active response first so the aborted turn (including tool\n\t\t// results) is persisted to the outgoing session before it is replaced.\n\t\tawait this.session.abort();\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t\tthis.session.sessionManager.dispose();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t}\n\n\tprivate async replaceWithManager(\n\t\tsessionManager: SessionManager,\n\t\treason: \"new\" | \"resume\" | \"fork\",\n\t\tpreviousSessionFile: string | undefined,\n\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\t\tawait this.teardownCurrent(reason, sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason, previousSessionFile },\n\t\t\t\t\tprojectTrustContext: projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t\t}),\n\t\t\t);\n\t\t} finally {\n\t\t\t// Once installed, the runtime owns the manager even if subsequent UI rebinding fails.\n\t\t\tif (this.session.sessionManager !== sessionManager) sessionManager.dispose();\n\t\t}\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tawait this.replaceWithManager(sessionManager, \"resume\", previousSessionFile, options?.projectTrustContextFactory);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = this.session.sessionManager.isPersisted()\n\t\t\t? SessionManager.create(this.cwd, sessionDir, { parentSession: options?.parentSession })\n\t\t\t: SessionManager.inMemory(this.cwd, { parentSession: options?.parentSession });\n\t\tawait this.replaceWithManager(sessionManager, \"new\", previousSessionFile);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.refreshContext();\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir, { parentSession: currentSessionFile });\n\t\t\t\tawait this.replaceWithManager(sessionManager, \"fork\", previousSessionFile);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\"This session has not been saved yet. Send a message before cloning or forking it.\");\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\ttry {\n\t\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\t\tif (!forkedSessionPath) throw new Error(\"Failed to create forked session\");\n\t\t\t\tawait this.replaceWithManager(sessionManager, \"fork\", previousSessionFile);\n\t\t\t} finally {\n\t\t\t\tif (this.session.sessionManager !== sessionManager) sessionManager.dispose();\n\t\t\t}\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: previousSessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tlet destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst sourceAlreadyStored = resolve(destinationPath) === resolvedPath;\n\t\tif (!sourceAlreadyStored) {\n\t\t\tconst { name, ext } = parse(destinationPath);\n\t\t\tlet suffix = 1;\n\t\t\twhile (existsSync(destinationPath)) {\n\t\t\t\tdestinationPath = join(sessionDir, `${name}-${suffix++}${ext}`);\n\t\t\t}\n\t\t}\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (!sourceAlreadyStored) {\n\t\t\t// The gate keeps a concurrent relocation from moving the file being copied.\n\t\t\twithSessionOwnershipGate(() => copyFileSync(resolvedPath, destinationPath, constants.COPYFILE_EXCL));\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tawait this.replaceWithManager(sessionManager, \"resume\", previousSessionFile);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t\tthis.session.sessionManager.dispose();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAShD,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AA4BzF;;GAEG;AACH,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAC/C,QAAQ,CAAS;IAE1B,YAAY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OAAO,CAAC,OAAO,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,aAA+C,EAC/C,OAKC;IAED,sBAAsB,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,IAAI,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,CAC3B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { constants, copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, parse, resolve } from \"node:path\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\nimport { getSessionOpenRefusal, withSessionOwnershipGate } from \"./session-ownership.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\tprivate _session: AgentSession;\n\tprivate _services: AgentSessionServices;\n\tprivate readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tprivate _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tprivate _modelFallbackMessage?: string;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\t// Settle any active response first so the aborted turn (including tool\n\t\t// results) is persisted to the outgoing session before it is replaced.\n\t\tawait this.session.abort();\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t\tthis.session.sessionManager.dispose();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t}\n\n\tprivate async replaceWithManager(\n\t\tsessionManager: SessionManager,\n\t\treason: \"new\" | \"resume\" | \"fork\",\n\t\tpreviousSessionFile: string | undefined,\n\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\t\tawait this.teardownCurrent(reason, sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason, previousSessionFile },\n\t\t\t\t\tprojectTrustContext: projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t\t}),\n\t\t\t);\n\t\t} finally {\n\t\t\t// Once installed, the runtime owns the manager even if subsequent UI rebinding fails.\n\t\t\tif (this.session.sessionManager !== sessionManager) sessionManager.dispose();\n\t\t}\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst refusal = getSessionOpenRefusal(sessionPath);\n\t\tif (refusal) {\n\t\t\tthrow new Error(refusal);\n\t\t}\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tawait this.replaceWithManager(sessionManager, \"resume\", previousSessionFile, options?.projectTrustContextFactory);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = this.session.sessionManager.isPersisted()\n\t\t\t? SessionManager.create(this.cwd, sessionDir, { parentSession: options?.parentSession })\n\t\t\t: SessionManager.inMemory(this.cwd, { parentSession: options?.parentSession });\n\t\tawait this.replaceWithManager(sessionManager, \"new\", previousSessionFile);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.refreshContext();\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir, { parentSession: currentSessionFile });\n\t\t\t\tawait this.replaceWithManager(sessionManager, \"fork\", previousSessionFile);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\"This session has not been saved yet. Send a message before cloning or forking it.\");\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\ttry {\n\t\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\t\tif (!forkedSessionPath) throw new Error(\"Failed to create forked session\");\n\t\t\t\tawait this.replaceWithManager(sessionManager, \"fork\", previousSessionFile);\n\t\t\t} finally {\n\t\t\t\tif (this.session.sessionManager !== sessionManager) sessionManager.dispose();\n\t\t\t}\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: previousSessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tlet destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst sourceAlreadyStored = resolve(destinationPath) === resolvedPath;\n\t\tif (!sourceAlreadyStored) {\n\t\t\tconst { name, ext } = parse(destinationPath);\n\t\t\tlet suffix = 1;\n\t\t\twhile (existsSync(destinationPath)) {\n\t\t\t\tdestinationPath = join(sessionDir, `${name}-${suffix++}${ext}`);\n\t\t\t}\n\t\t}\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (!sourceAlreadyStored) {\n\t\t\t// The gate keeps a concurrent relocation from moving the file being copied.\n\t\t\twithSessionOwnershipGate(() => copyFileSync(resolvedPath, destinationPath, constants.COPYFILE_EXCL));\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tawait this.replaceWithManager(sessionManager, \"resume\", previousSessionFile);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t\tthis.session.sessionManager.dispose();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\n"]}
|
|
@@ -10,4 +10,13 @@ export declare function markSessionMoved(path: string, destination: string): voi
|
|
|
10
10
|
export declare function unmarkSessionMoved(path: string): void;
|
|
11
11
|
/** Reject live users and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */
|
|
12
12
|
export declare function assertSessionUnused(path: string): void;
|
|
13
|
+
/**
|
|
14
|
+
* Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two
|
|
15
|
+
* writers on one file fork its history and a later read follows the branch that appended last,
|
|
16
|
+
* hiding the other one without warning. This process's own registrations never refuse, so
|
|
17
|
+
* re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns
|
|
18
|
+
* the message instead of throwing so the interactive picker can refuse without ending its session.
|
|
19
|
+
* Set PI_ALLOW_SHARED_SESSION to resume anyway.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getSessionOpenRefusal(path: string): string | undefined;
|
|
13
22
|
//# sourceMappingURL=session-ownership.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-ownership.d.ts","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAyBA,6FAA6F;AAC7F,wBAAgB,wBAAwB,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAiCjE;AAED,2FAA2F;AAC3F,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,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 function removeStaleRecord(path) {
|
|
|
126
126
|
/**
|
|
127
127
|
* Report whether a recorded owner process is still running. Anything other than a confirmed
|
|
128
128
|
* absence counts as running, including a permission error, so an uncertain check never allows
|
|
129
|
-
*
|
|
130
|
-
* which can refuse
|
|
129
|
+
* the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as
|
|
130
|
+
* running, which can refuse an operation that would have been safe.
|
|
131
131
|
*/
|
|
132
132
|
function processIsLive(pid) {
|
|
133
133
|
try {
|
|
@@ -141,7 +141,60 @@ function processIsLive(pid) {
|
|
|
141
141
|
/** Reject live users and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */
|
|
142
142
|
export function assertSessionUnused(path) {
|
|
143
143
|
const canonical = canonicalSessionPath(path);
|
|
144
|
-
const
|
|
144
|
+
const owners = collectLiveOwners();
|
|
145
|
+
for (const owner of owners) {
|
|
146
|
+
if (owner.sessions.includes(canonical))
|
|
147
|
+
throw new Error(`Session is open in process ${owner.pid}. Close it before moving.`);
|
|
148
|
+
}
|
|
149
|
+
// Detecting Pi processes that predate ownership requires scanning the process table, and the
|
|
150
|
+
// portable process list is not reliable enough to do so outside Linux. Those platforms only
|
|
151
|
+
// enforce ownership registered by cooperating Pi instances.
|
|
152
|
+
if (process.platform !== "linux")
|
|
153
|
+
return;
|
|
154
|
+
const registered = new Set(owners.map((owner) => owner.pid));
|
|
155
|
+
const processes = execFileSync("ps", ["-u", String(process.getuid()), "-o", "pid=,comm=,args="], {
|
|
156
|
+
encoding: "utf8",
|
|
157
|
+
});
|
|
158
|
+
for (const line of processes.split("\n")) {
|
|
159
|
+
const match = line.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);
|
|
160
|
+
if (!match)
|
|
161
|
+
continue;
|
|
162
|
+
const pid = Number(match[1]);
|
|
163
|
+
if (pid === process.pid || registered.has(pid))
|
|
164
|
+
continue;
|
|
165
|
+
const isPi = match[2] === "pi" ||
|
|
166
|
+
/(?:^|\s)\S*(?:pi-coding-agent\/(?:dist|src)\/cli\.(?:js|ts)|\/pi\/packages\/coding-agent\/src\/cli\.ts)(?:\s|$)/.test(match[3]);
|
|
167
|
+
if (isPi)
|
|
168
|
+
throw new Error(`Pi process ${pid} does not report session ownership. Close older Pi instances before moving.`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two
|
|
173
|
+
* writers on one file fork its history and a later read follows the branch that appended last,
|
|
174
|
+
* hiding the other one without warning. This process's own registrations never refuse, so
|
|
175
|
+
* re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns
|
|
176
|
+
* the message instead of throwing so the interactive picker can refuse without ending its session.
|
|
177
|
+
* Set PI_ALLOW_SHARED_SESSION to resume anyway.
|
|
178
|
+
*/
|
|
179
|
+
export function getSessionOpenRefusal(path) {
|
|
180
|
+
if (process.env.PI_ALLOW_SHARED_SESSION)
|
|
181
|
+
return undefined;
|
|
182
|
+
const canonical = canonicalSessionPath(path);
|
|
183
|
+
for (const owner of collectLiveOwners()) {
|
|
184
|
+
if (owner.pid === process.pid)
|
|
185
|
+
continue;
|
|
186
|
+
if (owner.sessions.includes(canonical))
|
|
187
|
+
return `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Owners that a record claims are running, after records proven stale are dropped. Removal is
|
|
193
|
+
* idempotent and its failure is ignored, so this is safe with and without the ownership gate.
|
|
194
|
+
* Records are written only by Pi in a directory only this user can read.
|
|
195
|
+
*/
|
|
196
|
+
function collectLiveOwners() {
|
|
197
|
+
const owners = [];
|
|
145
198
|
for (const file of readdirSync(root)) {
|
|
146
199
|
if (!/^\d+\.json$/.test(file))
|
|
147
200
|
continue;
|
|
@@ -166,7 +219,7 @@ export function assertSessionUnused(path) {
|
|
|
166
219
|
}
|
|
167
220
|
if (record.start !== null) {
|
|
168
221
|
// Linux records carry a start identity. A mismatch means another process reused the PID,
|
|
169
|
-
// so the record is provably stale.
|
|
222
|
+
// so the record is provably stale.
|
|
170
223
|
if (start === undefined || record.start !== start) {
|
|
171
224
|
removeStaleRecord(join(root, file));
|
|
172
225
|
continue;
|
|
@@ -177,29 +230,8 @@ export function assertSessionUnused(path) {
|
|
|
177
230
|
removeStaleRecord(join(root, file));
|
|
178
231
|
continue;
|
|
179
232
|
}
|
|
180
|
-
|
|
181
|
-
if (record.sessions.includes(canonical))
|
|
182
|
-
throw new Error(`Session is open in process ${pid}. Close it before moving.`);
|
|
183
|
-
}
|
|
184
|
-
// Detecting Pi processes that predate ownership requires scanning the process table, and the
|
|
185
|
-
// portable process list is not reliable enough to do so outside Linux. Those platforms only
|
|
186
|
-
// enforce ownership registered by cooperating Pi instances.
|
|
187
|
-
if (process.platform !== "linux")
|
|
188
|
-
return;
|
|
189
|
-
const processes = execFileSync("ps", ["-u", String(process.getuid()), "-o", "pid=,comm=,args="], {
|
|
190
|
-
encoding: "utf8",
|
|
191
|
-
});
|
|
192
|
-
for (const line of processes.split("\n")) {
|
|
193
|
-
const match = line.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);
|
|
194
|
-
if (!match)
|
|
195
|
-
continue;
|
|
196
|
-
const pid = Number(match[1]);
|
|
197
|
-
if (pid === process.pid || registered.has(pid))
|
|
198
|
-
continue;
|
|
199
|
-
const isPi = match[2] === "pi" ||
|
|
200
|
-
/(?:^|\s)\S*(?:pi-coding-agent\/(?:dist|src)\/cli\.(?:js|ts)|\/pi\/packages\/coding-agent\/src\/cli\.ts)(?:\s|$)/.test(match[3]);
|
|
201
|
-
if (isPi)
|
|
202
|
-
throw new Error(`Pi process ${pid} does not report session ownership. Close older Pi instances before moving.`);
|
|
233
|
+
owners.push({ pid, sessions: record.sessions });
|
|
203
234
|
}
|
|
235
|
+
return owners;
|
|
204
236
|
}
|
|
205
237
|
//# sourceMappingURL=session-ownership.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-ownership.js","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,SAAS,EACT,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,qBAAqB,OAAO,CAAC,MAAM,EAAE,EAAE,IAAI,MAAM,EAAE,CAAC,CAAC;AACjF,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC3C,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAI,WAAW,GAAG,KAAK,CAAC;AAExB,6FAA6F;AAC7F,MAAM,UAAU,wBAAwB,CAAI,SAAkB;IAC7D,IAAI,WAAW;QAAE,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;IACtG,SAAS,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAClD,uFAAuF;IACvF,gFAAgF;IAChF,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC7B,MAAM,GAAG,GAAG,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QACD,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACpB,IAAI,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,8BAA8B,GAAG,2BAA2B,CAAC,CAAC;IAChF,CAAC;IACD,6FAA6F;IAC7F,4FAA4F;IAC5F,4DAA4D;IAC5D,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;QAAE,OAAO;IACzC,MAAM,SAAS,GAAG,YAAY,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,MAAO,EAAE,CAAC,EAAE,IAAI,EAAE,kBAAkB,CAAC,EAAE;QACjG,QAAQ,EAAE,MAAM;KAChB,CAAC,CAAC;IACH,KAAK,MAAM,IAAI,IAAI,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC1D,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,GAAG,KAAK,OAAO,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,SAAS;QACzD,MAAM,IAAI,GACT,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI;YACjB,iHAAiH,CAAC,IAAI,CACrH,KAAK,CAAC,CAAC,CAAC,CACR,CAAC;QACH,IAAI,IAAI;YACP,MAAM,IAAI,KAAK,CACd,cAAc,GAAG,6EAA6E,CAC9F,CAAC;IACJ,CAAC;AACF,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * a move. On non-Linux platforms a reused PID is indistinguishable and also counts as running,\n * which can refuse a move that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Reject live users and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst registered = new Set<number>();\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(readFileSync(join(root, file), \"utf8\"));\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale. The gate makes removing it safe.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tregistered.add(pid);\n\t\tif (record.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${pid}. Close it before moving.`);\n\t}\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tif (process.platform !== \"linux\") return;\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi)\n\t\t\tthrow new Error(\n\t\t\t\t`Pi process ${pid} does not report session ownership. Close older Pi instances before moving.`,\n\t\t\t);\n\t}\n}\n"]}
|
|
1
|
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,qCAAqC,IAAI,EAAE,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC3B,yFAAyF;YACzF,mCAAmC;YACnC,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;gBACnD,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;gBACpC,SAAS;YACV,CAAC;QACF,CAAC;aAAM,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,wFAAwF;YACxF,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;YACpC,SAAS;QACV,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as\n * running, which can refuse an operation that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Reject live users and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\tfor (const owner of owners) {\n\t\tif (owner.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${owner.pid}. Close it before moving.`);\n\t}\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tif (process.platform !== \"linux\") return;\n\tconst registered = new Set(owners.map((owner) => owner.pid));\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi)\n\t\t\tthrow new Error(\n\t\t\t\t`Pi process ${pid} does not report session ownership. Close older Pi instances before moving.`,\n\t\t\t);\n\t}\n}\n\n/**\n * Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two\n * writers on one file fork its history and a later read follows the branch that appended last,\n * hiding the other one without warning. This process's own registrations never refuse, so\n * re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns\n * the message instead of throwing so the interactive picker can refuse without ending its session.\n * Set PI_ALLOW_SHARED_SESSION to resume anyway.\n */\nexport function getSessionOpenRefusal(path: string): string | undefined {\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return undefined;\n\tconst canonical = canonicalSessionPath(path);\n\tfor (const owner of collectLiveOwners()) {\n\t\tif (owner.pid === process.pid) continue;\n\t\tif (owner.sessions.includes(canonical))\n\t\t\treturn `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;\n\t}\n\treturn undefined;\n}\n\ninterface LiveOwner {\n\tpid: number;\n\tsessions: unknown[];\n}\n\n/**\n * Owners that a record claims are running, after records proven stale are dropped. Removal is\n * idempotent and its failure is ignored, so this is safe with and without the ownership gate.\n * Records are written only by Pi in a directory only this user can read.\n */\nfunction collectLiveOwners(): LiveOwner[] {\n\tconst owners: LiveOwner[] = [];\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(readFileSync(join(root, file), \"utf8\"));\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\towners.push({ pid, sessions: record.sessions });\n\t}\n\treturn owners;\n}\n"]}
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,KAAK,IAAI,EAAyD,MAAM,eAAe,CAAC;AAkCjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAalE,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,KAAK,IAAI,EAAyD,MAAM,eAAe,CAAC;AAkCjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAalE,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGjF,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AA0T7D,wBAAsB,oBAAoB,CACzC,MAAM,EAAE,IAAI,EACZ,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,eAAe,EAAE,eAAe,GAC9B,OAAO,CAAC,cAAc,CAAC,CAsFzB;AAyHD,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,eAAe,EAAE,CAAC;CACvC;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBAsb/D"}
|
package/dist/main.js
CHANGED
|
@@ -31,6 +31,7 @@ import { restoreStdout, takeOverStdout } from "./core/output-guard.js";
|
|
|
31
31
|
import { resolveProjectTrusted } from "./core/project-trust.js";
|
|
32
32
|
import { formatMissingSessionCwdPrompt, getMissingSessionCwdIssue, MissingSessionCwdError, } from "./core/session-cwd.js";
|
|
33
33
|
import { assertValidSessionId, SessionManager } from "./core/session-manager.js";
|
|
34
|
+
import { getSessionOpenRefusal } from "./core/session-ownership.js";
|
|
34
35
|
import { collectSettingsDiagnostics, deduplicateDiagnostics } from "./core/settings-diagnostics.js";
|
|
35
36
|
import { SettingsManager } from "./core/settings-manager.js";
|
|
36
37
|
import { printTimings, resetTimings, time } from "./core/timings.js";
|
|
@@ -263,6 +264,11 @@ function validateSessionIdFlags(parsed) {
|
|
|
263
264
|
}
|
|
264
265
|
}
|
|
265
266
|
function openSessionOrExit(path, sessionDir) {
|
|
267
|
+
const refusal = getSessionOpenRefusal(path);
|
|
268
|
+
if (refusal) {
|
|
269
|
+
console.error(chalk.red(`Error: ${refusal}`));
|
|
270
|
+
process.exit(1);
|
|
271
|
+
}
|
|
266
272
|
try {
|
|
267
273
|
return SessionManager.open(path, sessionDir);
|
|
268
274
|
}
|
|
@@ -272,6 +278,17 @@ function openSessionOrExit(path, sessionDir) {
|
|
|
272
278
|
process.exit(1);
|
|
273
279
|
}
|
|
274
280
|
}
|
|
281
|
+
/** --continue picks the session file itself, so its shared-session check can only run afterwards. */
|
|
282
|
+
function refuseSharedSessionOrExit(sessionManager) {
|
|
283
|
+
const sessionFile = sessionManager.getSessionFile();
|
|
284
|
+
const refusal = sessionFile ? getSessionOpenRefusal(sessionFile) : undefined;
|
|
285
|
+
if (refusal) {
|
|
286
|
+
sessionManager.dispose();
|
|
287
|
+
console.error(chalk.red(`Error: ${refusal}`));
|
|
288
|
+
process.exit(1);
|
|
289
|
+
}
|
|
290
|
+
return sessionManager;
|
|
291
|
+
}
|
|
275
292
|
function forkSessionOrExit(sourcePath, cwd, sessionDir, sessionId) {
|
|
276
293
|
try {
|
|
277
294
|
return SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId });
|
|
@@ -332,19 +349,19 @@ export async function createSessionManager(parsed, cwd, sessionDir, settingsMana
|
|
|
332
349
|
console.log(chalk.dim("No session selected"));
|
|
333
350
|
process.exit(0);
|
|
334
351
|
}
|
|
335
|
-
return
|
|
352
|
+
return openSessionOrExit(selectedPath, sessionDir);
|
|
336
353
|
}
|
|
337
354
|
finally {
|
|
338
355
|
stopThemeWatcher();
|
|
339
356
|
}
|
|
340
357
|
}
|
|
341
358
|
if (parsed.continue) {
|
|
342
|
-
return SessionManager.continueRecent(cwd, sessionDir);
|
|
359
|
+
return refuseSharedSessionOrExit(SessionManager.continueRecent(cwd, sessionDir));
|
|
343
360
|
}
|
|
344
361
|
if (parsed.sessionId) {
|
|
345
362
|
const existingSession = findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);
|
|
346
363
|
if (existingSession) {
|
|
347
|
-
return
|
|
364
|
+
return openSessionOrExit(existingSession.path, sessionDir);
|
|
348
365
|
}
|
|
349
366
|
console.error(chalk.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`));
|
|
350
367
|
}
|