ask-pro 0.1.71 → 0.2.80

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ask-pro",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Minimal browser-backed ChatGPT Pro escalation workflow for agents via $ask-pro.",
5
5
  "author": {
6
6
  "name": "Jonathan",
package/README.md CHANGED
@@ -6,47 +6,35 @@ and owns the result; ask-pro never applies generated code.
6
6
 
7
7
  ## Install
8
8
 
9
- Both options need Node.js 24+, Chrome, and a ChatGPT account with Pro access.
10
- Browser login is manual.
11
-
12
- ### Codex plugin marketplace
13
-
14
9
  ```powershell
15
- codex plugin marketplace add JJLiebig/ask-pro
16
- codex plugin add ask-pro@ask-pro
10
+ npx skills add JJLiebig/ask-pro -g
17
11
  ```
18
12
 
19
- This route needs Git and npm. The plugin's cached runner downloads pnpm, builds
20
- outside the plugin cache, and keeps the installed snapshot unchanged. If
21
- `ask-pro` is not on `PATH`, the skill uses that runner.
13
+ This installs the `ask-pro` skill for Codex, Claude Code, and the other agents
14
+ the [skills CLI](https://github.com/vercel-labs/skills) supports. The skill
15
+ contains ask-pro itself; its first run installs dependencies and builds, so no
16
+ separate CLI install is needed. Update with `npx skills update`.
22
17
 
23
- Update with `codex plugin marketplace upgrade ask-pro`, then restart Codex to
24
- load the updated skill.
25
-
26
- ### Skills CLI (Codex and other supported agents)
27
-
28
- Install the skill and its standalone CLI separately:
18
+ Codex users can install it as a plugin instead:
29
19
 
30
20
  ```powershell
31
- npx skills add JJLiebig/ask-pro
32
- npm install --global ask-pro
21
+ codex plugin marketplace add JJLiebig/ask-pro
22
+ codex plugin add ask-pro@ask-pro
33
23
  ```
34
24
 
35
- The [skills CLI](https://github.com/vercel-labs/skills) installs the skill in
36
- the current project by default. Add `-g` for a user-wide skill or `-a codex`
37
- to select Codex; it supports other agents too. The npm CLI runs without Codex's
38
- plugin cache.
39
-
40
- Update both parts:
41
-
42
- ```powershell
43
- npx skills update
44
- npm update --global ask-pro
45
- ```
25
+ Update with `codex plugin marketplace upgrade ask-pro`, then restart Codex.
26
+ Both installs run the same bundled launcher. The `ask-pro` npm package
27
+ (`npm i -g ask-pro`) still works too. All three share the same state.
46
28
 
47
- The browser runtime is developed and tested on Windows. Other operating systems
29
+ You need Node.js 24+, npm, Chrome, and a ChatGPT account with Pro access. The
30
+ browser runtime is developed and tested on Windows; other operating systems
48
31
  need validation.
49
32
 
33
+ **Upgrading from an earlier version:** nothing to do. On its first run,
34
+ ask-pro moves your signed-in browser profiles from `~/.codex/state/ask-pro` to
35
+ `~/.agents/state/ask-pro`. If Chrome still has the old profile open, ask-pro
36
+ uses it where it is and moves it on a later run.
37
+
50
38
  ## Browser and session state
51
39
 
52
40
  ask-pro never asks for, types, reads, or logs passwords, MFA codes, recovery
@@ -54,10 +42,9 @@ codes, session cookies, or raw auth tokens. A new browser profile may need one
54
42
  manual ChatGPT login. On Windows, ordinary managed Chrome runs start minimized
55
43
  and are hidden; login and recovery restore the window for human action.
56
44
 
57
- The persistent profile lives at `$CODEX_HOME/state/ask-pro/browser-profile`, or
58
- `~/.codex/state/ask-pro/browser-profile` when `CODEX_HOME` is unset. Existing
59
- legacy profiles are migrated on first use; see [Windows notes](docs/windows-work.md)
60
- for copy and recovery details.
45
+ ask-pro keeps its state in `~/.agents/state/ask-pro/`: the persistent browser
46
+ profile in `browser-profile/` and the builds of the installed skill in
47
+ `runtimes/`. Set `ASK_PRO_STATE_DIR` to use a different folder.
61
48
 
62
49
  Project sessions live under `.ask-pro/sessions/<id>/`. Add `.ask-pro/` to your
63
50
  project's `.gitignore`. At each invocation, ask-pro deletes entire session
@@ -65,7 +52,9 @@ directories at least seven days old, regardless of state.
65
52
 
66
53
  ## Use
67
54
 
68
- Ask for a recoverable repo consult:
55
+ Agents run ask-pro through the installed skill, as
56
+ `node <skill-folder>/scripts/ask-pro.mjs`; `ask-pro` below stands for that
57
+ command. Ask for a recoverable repo consult:
69
58
 
70
59
  ```powershell
71
60
  ask-pro --no-temporary --prompt-file question.md --files src --files tests
@@ -86,7 +75,7 @@ ask-pro --harvest <session-id>
86
75
 
87
76
  Use `ask-pro --help` for the full CLI. For multiline prompts, use
88
77
  `--prompt-file`. Prefer `--no-temporary` when recovery matters; `--temporary`
89
- requires Temporary Chat. The [skill](skills/ask-pro/SKILL.md) has agent guidance.
78
+ requires Temporary Chat. The [skill](SKILL.md) has agent guidance.
90
79
 
91
80
  When Pro asks native questions, ask-pro returns `awaiting_answers`, prints each
92
81
  question and its numbered choices, and saves `QUESTIONS.json`. The calling agent
@@ -154,8 +143,8 @@ pnpm run format:check
154
143
  pnpm pack --dry-run
155
144
  ```
156
145
 
157
- After changing plugin files, run `pnpm run plugin:refresh` and restart Codex.
158
- Do not edit the installed plugin cache. Live browser tests are opt-in; see
146
+ To try local changes as an installed skill, run
147
+ `npx skills add <path-to-checkout> -g`. Live browser tests are opt-in; see
159
148
  [manual tests](docs/manual-tests.md).
160
149
 
161
150
  After the build matrix passes on `main`, [CI](.github/workflows/ci.yml) publishes
package/SKILL.md ADDED
@@ -0,0 +1,229 @@
1
+ ---
2
+ name: ask-pro
3
+ description: Escalate hard engineering questions to ChatGPT Pro through browser automation with focused repo context. Use when an agent needs a stronger external review, architecture plan, migration strategy, production-debugging second opinion, or when the user explicitly asks to use $ask-pro.
4
+ ---
5
+
6
+ # $ask-pro
7
+
8
+ Use `$ask-pro` to ask ChatGPT Pro for a focused second opinion on hard engineering work.
9
+
10
+ The calling agent still owns the work. Use Pro for judgment, architecture, risk review, or implementation planning when the decision is consequential enough to justify a browser run.
11
+
12
+ ## Running ask-pro
13
+
14
+ This skill folder contains ask-pro itself; nothing else needs installing. In
15
+ the commands below, `ask-pro` stands for:
16
+
17
+ ```bash
18
+ node <skill-folder>/scripts/ask-pro.mjs
19
+ ```
20
+
21
+ `<skill-folder>` is the directory containing this `SKILL.md`. Run it from the
22
+ target repo root. The first run after an install or update installs
23
+ dependencies and builds, which can take a few minutes; wait for it. The CLI's
24
+ emitted `resume` and `harvest` commands already contain the full launcher path;
25
+ run them as printed. Node.js 24+, npm, and Chrome are required.
26
+
27
+ ## Trigger
28
+
29
+ Use this skill when the user explicitly asks for `$ask-pro`, or when a second opinion would materially reduce risk for:
30
+
31
+ - backend architecture
32
+ - schema or data migrations
33
+ - auth, sessions, permissions, or billing
34
+ - queues, workers, idempotency, caching, scaling, or latency
35
+ - production debugging and observability
36
+ - ambiguous implementation paths where a second opinion would reduce risk
37
+
38
+ Do not use it for trivial syntax fixes, formatting, obvious dependency updates, or small bugs with a clear cause.
39
+
40
+ ## Critical Reminders
41
+
42
+ - Long waits are normal. ask-pro can take a super long time to run; do not
43
+ close or kill the browser window/run until at least 3 hours have passed unless
44
+ the CLI has completed, failed, or explicitly asks for human action.
45
+
46
+ ## Workflow
47
+
48
+ When invoked:
49
+
50
+ 1. Inspect the repo and the relevant files.
51
+ 2. Identify the exact decision Pro should answer.
52
+ 3. For committed code on GitHub, prefer `--github` and give Pro the repository,
53
+ ref, relevant paths, and question. Let it retrieve the code instead of assembling
54
+ a source bundle. Add a small `--files` bundle only for uncommitted changes,
55
+ local-only evidence, or repository content the connection cannot access.
56
+ 4. Write the prompt yourself using the Prompt Shape below.
57
+ 5. Run the smallest useful command: `ask-pro --github "<prompt>"` for GitHub
58
+ evidence, or `ask-pro --no-temporary --files "<glob>" "<prompt>"` for a file bundle.
59
+ For multiline prompts, write a temporary prompt file and use
60
+ `ask-pro --no-temporary --prompt-file <path> --files "<glob>"`; do not rely
61
+ on shell multiline quoting.
62
+ 6. If auth is required, stop and ask the human to log in in the opened browser.
63
+ 7. Read the CLI's compact `ask_pro` record and run the emitted `resume` or
64
+ `harvest` command when that is the next action.
65
+ 8. Treat the answer as advisory; turn it into your own plan before editing code.
66
+
67
+ `ask-pro` selects `Latest` when available, otherwise the highest numbered available
68
+ GPT model, then `Pro` intelligence. Do not require a
69
+ different dated model label or a separate thinking-effort control in the prompt
70
+ or workflow.
71
+
72
+ Fresh runs try ChatGPT Temporary Chat by default and automatically fall back to
73
+ normal ChatGPT if the current account/UI does not expose Pro there. For repo
74
+ advisories, large bundles, review rounds, or anything where recovery matters,
75
+ prefer `--no-temporary` from the start. Add `--temporary` only when Temporary
76
+ Chat is required and falling back would be wrong. Temporary Chat is less
77
+ recoverable after browser/tab loss.
78
+
79
+ On Windows, ordinary managed Chrome runs start minimized. First login,
80
+ resume/recovery, and stale-auth paths stay visible or are restored for human
81
+ action. Local managed Chrome guards browser input while Pro is answering.
82
+ If login, MFA, a browser challenge, or incomplete-answer debugging needs human
83
+ attention, ask-pro should restore or retain the browser and emit the next
84
+ action.
85
+
86
+ Do not set `ASK_PRO_AGENT_ID` for ordinary or concurrent use; the shared
87
+ `ask-pro` browser profile under `~/.agents/state/ask-pro/` handles concurrent
88
+ agents automatically. Set `ASK_PRO_AGENT_ID` only when explicitly testing an
89
+ isolated profile or when the human requests a separate browser login. Use a
90
+ stable reusable lowercase id like `review-t1`, not a one-off task slug, because
91
+ each new id creates a new Chrome profile and may require the human to log in
92
+ again. Example:
93
+ `ASK_PRO_AGENT_ID=review-t1 ask-pro ...`.
94
+
95
+ ## Prompt Shape
96
+
97
+ Assume Pro has no caller context or local checkout. Include each material fact and
98
+ instruction once: the goal, current state, hard constraints, evidence, success
99
+ criteria, and required output. Do not rely on the agent's conversation context, repo
100
+ folklore, prior ask-pro runs, branch names, or unstated user preferences.
101
+ Keep advisory design consults as plain answer requests. Start advisory prompts
102
+ with:
103
+
104
+ ```text
105
+ Return final Markdown only, with no preamble or implementation package.
106
+ ```
107
+
108
+ The CLI wrapper already tells Pro to read `CONTEXT.zip` and call out missing or
109
+ conflicting context. Do not repeat that instruction. Add task-specific output
110
+ requirements only when needed. For risk or review work, ask Pro to rank
111
+ findings by severity. For architecture or design consults, ask directly for the
112
+ recommendation and tradeoffs.
113
+
114
+ Use `--artifacts` only when the standard implementation package is needed. The
115
+ wrapper supplies the zip name, standard files, and markdown fallback; add only
116
+ task-specific deliverables not covered by that package. Keep advisory consults
117
+ inline by default.
118
+ Keep bundles focused: source files under review, focused tests, relevant docs,
119
+ known recent changes, and validation status. Avoid whole-repo bundles unless the
120
+ question is explicitly architectural.
121
+
122
+ ## Connected GitHub (optional)
123
+
124
+ Prefer `--github` for remote repository evidence. It checks
125
+ the connection before uploading or submitting, and defaults to normal ChatGPT.
126
+ Do not require GitHub for file-based consults. Availability varies by account,
127
+ workspace, model, and ChatGPT experience.
128
+
129
+ If the CLI returns `needs_github_connection` / `connect_github_then_resume`,
130
+ direct the human to the opened GitHub page in ask-pro's browser. They install the
131
+ plugin if needed, complete sign-in, review permissions, and select repositories;
132
+ organization approval may be needed. Wait for them to finish, then run the
133
+ emitted resume command without adding `--github`. The requirement is saved with
134
+ the session and checked again. Do not start a second session or submit through
135
+ the browser yourself. Never collect GitHub credentials or automate authorization.
136
+
137
+ If available, GitHub's **Allow read actions** permission can avoid read approval
138
+ prompts. The human chooses that setting. It controls approval behavior, not the
139
+ underlying permissions of a write-capable app; see
140
+ [app permissions](https://help.openai.com/en/articles/20001495-managing-app-permissions-in-chatgpt).
141
+ The live GitHub plugin advertises write capabilities despite the Help Center's
142
+ read-only description. `--github` requests read-only work; it does not restrict
143
+ the provider's permissions or prove that writes are impossible.
144
+
145
+ If GitHub is already connected, proceed without a setup question or source-file
146
+ bundle. For the consult, name the repository (`owner/repo`), relevant paths, and
147
+ requested branch or commit in the prompt. Explicitly ask Pro
148
+ to answer the specific question. The wrapper requests the connected GitHub app,
149
+ read-only work, citations, the revision inspected, and access gaps. Do not
150
+ infer repository access from ChatGPT login or a successful CLI exit.
151
+
152
+ Keep `--files` for local/uncommitted changes, non-GitHub evidence, and snapshots
153
+ that the app cannot retrieve. Distinguish
154
+ uploaded evidence from GitHub evidence, and ask Pro to flag revision conflicts.
155
+ If the app or requested revision is unavailable, offer a new consult with a
156
+ focused file bundle and
157
+ disclose that limitation. Do not silently switch away from Pro. The CLI submits
158
+ text; it does not select an app in the composer or handle app approval prompts.
159
+ Until a live run demonstrates retrieval, describe this as an available setup
160
+ path, not a verified connection. Confirm material claims against the repo.
161
+
162
+ ## Output
163
+
164
+ Normal `ask-pro` stdout is compact TOON-style telemetry. Use `state`, `action`,
165
+ `resume`, and `harvest` to decide the next command. Browser progress may appear
166
+ on stderr and can be ignored unless diagnosing a stuck run.
167
+
168
+ `AWAITING_ANSWERS` / `answer_questions` means Pro is asking native interactive
169
+ questions. Read the printed questions/options or `QUESTIONS.json`, answer from
170
+ the caller's context, and ask the human only for decisions you cannot infer.
171
+ Write UTF-8 JSON `{"requestId":"<request_id>","answers":[2,3,"free text"]}`
172
+ with one answer per question in order, then run the emitted
173
+ `ask-pro --resume <session-id> --answers <answers.json>` command. Numbers select
174
+ 1-based choices; strings enter the native free-text field. `--answers -` accepts
175
+ piped JSON. Do not submit defaults or treat the question preamble as the answer.
176
+ Repeat for further question rounds, then harvest the final answer normally.
177
+
178
+ When present, use `profile`, `profile_path`, `chrome`, and `language` only as
179
+ diagnostic hints. They tell you whether the run used the shared profile, an
180
+ isolated agent profile, saved DevTools state, and English browser steering.
181
+ When present, `conversation_url` is a recoverable non-temporary ChatGPT
182
+ conversation URL.
183
+
184
+ `ask-pro --harvest <session-id>` prints the raw markdown answer only for
185
+ answer-bearing states such as `COMPLETED` or `HARVESTED`.
186
+ For pending/incomplete sessions it prints compact status/action instead. For
187
+ sessions run with `--artifacts`, any provided `ask-pro-response.zip` is
188
+ extracted under the session's `pro-output/` directory and described in
189
+ `PRO_OUTPUT_MANIFEST.json`. Inline-default sessions should not expect a zip.
190
+
191
+ `INCOMPLETE_ANSWER` / `stopped_without_answer` means ChatGPT stopped without
192
+ an answer after ask-pro attempted one automatic `continue`. Present the caller
193
+ with the emitted resume command or a full retry of the original request in a new
194
+ chat, and wait for their choice. Do not automatically resume or retry this state.
195
+ An explicit `--resume` allows one more continuation attempt.
196
+
197
+ `COMPLETED` means harvest now; the run browser may already be closed. If the
198
+ state is `INCOMPLETE_ANSWER` / `preamble_without_artifacts`, do not treat
199
+ `ANSWER.md` as final. Try resume/harvest if recoverable; otherwise rerun with
200
+ `--no-temporary`, a tighter bundle, and a more direct prompt.
201
+
202
+ ## Commands
203
+
204
+ ```bash
205
+ ask-pro "Review the async billing webhook migration plan and return an implementation plan."
206
+ ask-pro --no-temporary --prompt-file question.md --files src --files tests
207
+ ask-pro --github "In owner/repo at <commit>, inspect src/auth and explain token validation."
208
+ ask-pro --temporary "Review this sensitive migration plan, and fail if Temporary Chat cannot use Pro."
209
+ ask-pro --no-temporary "Review this in normal ChatGPT instead of Temporary Chat."
210
+ ask-pro --prompt-file question.md --files .\src
211
+ ask-pro --artifacts --prompt-file implementation-plan.md --files src
212
+ ask-pro --files "src/api/stripe/**" --files "prisma/**" --files "src/lib/billing/**" \
213
+ "Review whether this Stripe webhook flow should use a queue or transactional outbox."
214
+ ask-pro --dry-run "Prepare the Pro handoff but do not open the browser."
215
+ ask-pro --resume <session-id>
216
+ ask-pro --harvest <session-id>
217
+ ```
218
+
219
+ `--files` must be inside the target repo. Use repo-relative paths.
220
+
221
+ ## Safety
222
+
223
+ Never ask for, read, store, type, or log passwords, MFA codes, recovery codes, session cookies, or raw auth tokens.
224
+
225
+ Browser auth is human-controlled. Continue only after the human says the ChatGPT composer is visible.
226
+
227
+ After submit, avoid interacting with any retained Chrome run window while Pro is
228
+ thinking. ask-pro guards input after submit, but the safest agent behavior is to
229
+ let the run finish or resume/harvest from CLI telemetry.
@@ -10,7 +10,8 @@ import { Command, Option } from "commander";
10
10
  import { createAskProSession, getAskProSessionPaths, pruneExpiredAskProSessions, readAskProAnswer, readAskProStatus, updateAskProResumeCommand, updateAskProStatus, } from "../src/ask-pro/session.js";
11
11
  import { AskProNeedsAuthError, isSuspiciousPreambleAnswer, resumeAskProBrowserSession, runAskProBrowserSession, } from "../src/ask-pro/browserRunner.js";
12
12
  import { renderToonRecord } from "../src/ask-pro/toon.js";
13
- import { askProAgentIdForManagedBrowserProfileDir, defaultAskProBrowserProfileDir, } from "../src/browser/profilePaths.js";
13
+ import { askProAgentIdForLegacyBrowserProfileDir, askProAgentIdForManagedBrowserProfileDir, defaultAskProBrowserProfileDir, isLegacyAskProManagedBrowserProfileDir, } from "../src/browser/profilePaths.js";
14
+ import { migrateLegacyAskProProfiles } from "../src/browser/profileMigration.js";
14
15
  import { getCliVersion } from "../src/version.js";
15
16
  const program = new Command();
16
17
  program
@@ -60,6 +61,10 @@ async function runAskPro(question, options) {
60
61
  if (options.answers && question.trim())
61
62
  throw new Error("Use --answers with --resume, without a question argument.");
62
63
  await pruneExpiredAskProSessions({ cwd });
64
+ await migrateLegacyAskProProfiles({
65
+ log: (message) => console.error(message),
66
+ lockTimeoutMs: 5_000,
67
+ });
63
68
  if (options.status !== undefined) {
64
69
  const { status } = await readAskProStatus({ cwd, sessionId: optionSessionId(options.status) });
65
70
  printStatusRecord(status, {
@@ -522,9 +527,11 @@ async function readBrowserMetadata(cwd, sessionId) {
522
527
  function profileMode(profileDir) {
523
528
  if (!profileDir)
524
529
  return undefined;
525
- if (askProAgentIdForManagedBrowserProfileDir(profileDir))
530
+ if (askProAgentIdForManagedBrowserProfileDir(profileDir) ||
531
+ askProAgentIdForLegacyBrowserProfileDir(profileDir))
526
532
  return "agent";
527
- if (path.resolve(profileDir) === path.resolve(defaultAskProBrowserProfileDir()))
533
+ if (path.resolve(profileDir) === path.resolve(defaultAskProBrowserProfileDir()) ||
534
+ isLegacyAskProManagedBrowserProfileDir(profileDir))
528
535
  return "shared";
529
536
  return undefined;
530
537
  }
@@ -5,7 +5,8 @@ import { AssistantStoppedError, BrowserAutomationError } from "../browser/errors
5
5
  import { AssistantQuestionsError } from "../browser/actions/questions.js";
6
6
  import { readAskProQuestions, parseQuestionAnswers, writeAskProQuestions } from "./questions.js";
7
7
  import { GitHubConnectionRequiredError } from "../browser/actions/github.js";
8
- import { askProAgentIdForLegacyBrowserProfileDir, askProAgentIdForManagedBrowserProfileDir, askProBrowserProfileDirForAgentId, ensureAskProBrowserProfileDir, isLegacyAskProManagedBrowserProfileDir, isAskProManagedBrowserProfileDir, resolveAskProAgentId, } from "../browser/profilePaths.js";
8
+ import { askProAgentIdForLegacyBrowserProfileDir, askProAgentIdForManagedBrowserProfileDir, askProBrowserProfileDirForAgentId, isAskProManagedBrowserProfileDir, isLegacyAskProManagedBrowserProfileDir, resolveAskProAgentId, } from "../browser/profilePaths.js";
9
+ import { prepareAskProBrowserProfile } from "../browser/profileMigration.js";
9
10
  import { runBrowserMode } from "../browserMode.js";
10
11
  import { closeTab } from "../browser/chromeLifecycle.js";
11
12
  import { resumeBrowserSession } from "../browser/reattach.js";
@@ -28,7 +29,7 @@ async function runAskProBrowserSessionWithLease({ cwd, sessionId, temporary: req
28
29
  const temporary = requestedTemporary ?? (sessionStatus.github ? false : undefined);
29
30
  const artifactsRequested = sessionStatus.artifacts === true;
30
31
  const agentId = agentIdOverride !== undefined ? agentIdOverride : resolveAskProAgentId();
31
- const browserProfile = browserProfileDir ?? (await ensureAskProBrowserProfileDir(agentId));
32
+ const browserProfile = browserProfileDir ?? (await prepareAskProBrowserProfile(agentId));
32
33
  const metadata = await readBrowserMetadata(paths.browser).catch(() => null);
33
34
  const chatgptUrl = chatgptUrlOverride ??
34
35
  (temporary === true
@@ -721,36 +722,34 @@ async function resolveResumeBrowserProfile(metadata) {
721
722
  const profileDir = metadata.profileDir;
722
723
  const profileAgentId = profileDir ? askProAgentIdForManagedBrowserProfileDir(profileDir) : null;
723
724
  const legacyAgentId = profileDir ? askProAgentIdForLegacyBrowserProfileDir(profileDir) : null;
724
- if (profileAgentId && profileAgentId !== metadata.agentId) {
725
- throw new Error("Stored ask-pro agent profile does not match stored agent id.");
726
- }
727
- if (legacyAgentId && legacyAgentId !== metadata.agentId) {
725
+ if ((profileAgentId ?? legacyAgentId) && (profileAgentId ?? legacyAgentId) !== metadata.agentId) {
728
726
  throw new Error("Stored ask-pro agent profile does not match stored agent id.");
729
727
  }
730
728
  if (profileAgentId && agentProfile) {
731
729
  return profileDir;
732
730
  }
731
+ // Sessions from earlier versions record the old profile location; resume where it is now.
733
732
  if (legacyAgentId && agentProfile) {
734
- return ensureAskProBrowserProfileDir(metadata.agentId);
733
+ return prepareAskProBrowserProfile(metadata.agentId);
735
734
  }
736
735
  if (profileDir &&
737
736
  !profileAgentId &&
738
737
  !legacyAgentId &&
739
738
  !agentProfile &&
740
739
  isAskProManagedBrowserProfileDir(profileDir)) {
741
- return ensureAskProBrowserProfileDir(null);
740
+ return askProBrowserProfileDirForAgentId(null);
742
741
  }
743
742
  if (profileDir &&
744
743
  !profileAgentId &&
745
744
  !legacyAgentId &&
746
745
  !agentProfile &&
747
746
  isLegacyAskProManagedBrowserProfileDir(profileDir)) {
748
- return ensureAskProBrowserProfileDir(null);
747
+ return prepareAskProBrowserProfile(null);
749
748
  }
750
749
  if (profileDir) {
751
750
  throw new Error("Stored ask-pro profile path is invalid.");
752
751
  }
753
- return ensureAskProBrowserProfileDir(metadata.agentId);
752
+ return prepareAskProBrowserProfile(metadata.agentId);
754
753
  }
755
754
  function resolveStoredAgentProfile(agentId) {
756
755
  if (!agentId)
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { promisify } from "node:util";
9
9
  import CDP from "chrome-remote-interface";
10
10
  import { Launcher } from "chrome-launcher";
11
- import { clearChromeLaunchStarting, cleanupStaleProfileState, hasChromeLaunchStarting, markChromeLaunchStarting, readChromePid, readDevToolsPort, verifyDevToolsReachable, } from "./profileState.js";
11
+ import { clearChromeLaunchStarting, clearIdleBrowserProfileCaches, cleanupStaleProfileState, hasChromeLaunchStarting, markChromeLaunchStarting, readChromePid, readDevToolsPort, verifyDevToolsReachable, } from "./profileState.js";
12
12
  import { delay } from "./utils.js";
13
13
  import { formatElapsed } from "./format.js";
14
14
  import { withTimeout } from "./reattachHelpers.js";
@@ -20,13 +20,14 @@ const CPU_THROTTLING_OVERRIDE_FLAGS = new Set([
20
20
  "--disable-ipc-flooding-protection",
21
21
  ]);
22
22
  const CHROME_STARTUP_HANDOFF_MS = 26_000;
23
- export async function launchChrome(config, userDataDir, logger) {
23
+ export async function launchChrome(config, userDataDir, logger, options = {}) {
24
24
  const connectHost = resolveRemoteDebugHost();
25
25
  const debugBindAddress = connectHost && connectHost !== "127.0.0.1" ? "0.0.0.0" : connectHost;
26
26
  const debugPort = config.debugPort ?? parseDebugPortEnv();
27
27
  const chromeFlags = buildChromeLaunchFlags(buildChromeFlags(config.headless ?? false, debugBindAddress, config.acceptLanguage, {
28
28
  startMinimized: shouldLaunchChromeMinimized(config),
29
29
  }));
30
+ await clearIdleBrowserProfileCaches(userDataDir, options);
30
31
  await markChromeLaunchStarting(userDataDir);
31
32
  try {
32
33
  const launcher = await launchManagedChrome({
@@ -581,6 +582,7 @@ export function buildChromeFlags(headless, debugBindAddress, acceptLanguage = "e
581
582
  const primaryLanguage = acceptLanguage.split(",", 1)[0]?.trim() || "en-US";
582
583
  const flags = [
583
584
  "--disable-background-networking",
585
+ "--disk-cache-size=16777216",
584
586
  "--disable-breakpad",
585
587
  "--disable-client-side-phishing-detection",
586
588
  "--disable-default-apps",
@@ -394,7 +394,7 @@ export async function runBrowserMode(options) {
394
394
  (await launchChrome({
395
395
  ...config,
396
396
  remoteChrome: config.remoteChrome,
397
- }, userDataDir, logger));
397
+ }, userDataDir, logger, { ignoreLockId: profileLock?.lockId }));
398
398
  // Persist profile state so future manual-login runs can reuse this Chrome.
399
399
  if (manualLogin && chrome.port) {
400
400
  await writeDevToolsActivePort(userDataDir, chrome.port);