Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

feat(ego-browser): unify task completion retention

Aute6a67e2572b29
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1761e4a..a8f6d31 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -178,7 +178,8 @@ stdin JS → runMain() → injected helpers → CDP / DOM / AX resolution → op
A `Task Space` is an isolated browsing context provided by ego-browser: it owns its own tab set but inherits the user's login state.
Because every heredoc runs in a fresh Node process, new scripts call
`taskSpace(nameOrId)` in each round, restore Pages by durable label, and end with
-`task.finish()` or `task.close()`.
+exactly one `task.finish({ keep })` call that explicitly lists which managed
+Pages should remain.
Control is handed to the user with `task.handOff()` and resumed, after user
approval, with `takeOverTaskSpace(spaceId)`. The old global helpers remain a v1
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
index d086e95..1100d11 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs
@@ -57,7 +57,7 @@ export function profileSelectionCase() {
"profile selection cannot be applied while resuming a numeric space id"
);
} finally {
- await explicitTask.close();
+ await explicitTask.finish({ keep: [] });
}
let missingProfileId = "__ego_browser_missing_profile__";
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
index b1d3eb2..e31abd3 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs
@@ -89,27 +89,47 @@ export function taskSpaceCase() {
await resumedTask.waitForControl({ interval: 100, timeout: 5_000 });
const boundaryPage = resumedTask.userPage();
assert(Boolean(boundaryPage), "takeover captures the tab active at the user boundary");
- const closeSpaceId = resumedTask.spaceId;
- await resumedTask.close();
+ const handedOffSpaceId = resumedTask.spaceId;
+ await resumedTask.finish({ keep: "all" });
+ assert(
+ (await listTaskSpaces()).some((space) => space.id === handedOffSpaceId),
+ "task.finish keeps the handed-off browser space"
+ );
+ await completeTaskSpace(handedOffSpaceId, { keep: false });
+
+ const closeTask = await taskSpace(taskName + " v2 close through finish");
+ const closeSpaceId = closeTask.spaceId;
+ await closeTask.finish({ keep: [] });
for (let attempt = 0; attempt < 20; attempt += 1) {
if (!(await listTaskSpaces()).some((space) => space.id === closeSpaceId)) break;
await new Promise((resolve) => setTimeout(resolve, 50));
}
assert(
!(await listTaskSpaces()).some((space) => space.id === closeSpaceId),
- "task.close removes the v2 task space"
+ "task.finish with no retained Pages removes the v2 task space"
);
const finishTask = await taskSpace(taskName + " v2 finish");
- await finishTask.page("p1").goto(baseUrl + "/secondary?v2-lifecycle=finish");
+ await finishTask.page("p1").goto(baseUrl + "/secondary?v2-lifecycle=discard");
+ const retainedPage = await finishTask.newPage();
+ await retainedPage.goto(baseUrl + "/secondary?v2-lifecycle=retain");
const finishSpaceId = finishTask.spaceId;
- await finishTask.finish();
+ await finishTask.finish({ keep: [retainedPage.label] });
assert(
(await listTaskSpaces()).some((space) => space.id === finishSpaceId),
- "task.finish keeps the browser space for the user"
+ "task.finish keeps the browser space when one Page is retained"
);
const reclaimedFinishedTask = await claimTaskSpace(finishSpaceId);
- await reclaimedFinishedTask.close();
+ const retainedTabs = await reclaimedFinishedTask.tabs();
+ assert(
+ retainedTabs.some((tab) => tab.url.includes("v2-lifecycle=retain")),
+ "task.finish keeps the named Page"
+ );
+ assert(
+ !retainedTabs.some((tab) => tab.url.includes("v2-lifecycle=discard")),
+ "task.finish closes unlisted Agent Pages"
+ );
+ await completeTaskSpace(finishSpaceId, { keep: false });
`;
}
@@ -129,7 +149,7 @@ export function crossSpaceV2Case() {
assertIncludes(firstInfo.url, "space=first", "cross-space gate keeps the first request in its space");
assertIncludes(secondInfo.url, "space=second", "cross-space gate keeps the second request in its space");
- await firstTask.close();
- await secondTask.close();
+ await firstTask.finish({ keep: [] });
+ await secondTask.finish({ keep: [] });
`;
}
diff --git a/package/ego-browser/scripts/repro-popup-foreground.sh b/package/ego-browser/scripts/repro-popup-foreground.sh
index e0e9843..ba5089f 100755
--- a/package/ego-browser/scripts/repro-popup-foreground.sh
+++ b/package/ego-browser/scripts/repro-popup-foreground.sh
@@ -70,7 +70,7 @@ try {
// Leave the result visible briefly, then remove all reproduction state.
await new Promise((resolve) => setTimeout(resolve, 8_000));
} finally {
- await task.close().catch((error) => {
+ await task.finish({ keep: [] }).catch((error) => {
console.error(`Cleanup failed for TaskSpace ${task.spaceId}: ${error.message}`);
});
}
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 11f74c2..bd77ea8 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -220,7 +220,7 @@ test("taskSpace returns the new object model for a resolved space", async () =>
assert.equal(typeof task.release, "function");
assert.equal(typeof task.handOff, "function");
assert.equal(typeof task.finish, "function");
- assert.equal(typeof task.close, "function");
+ assert.equal(task.close, undefined);
},
);
});
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index 070253c..679c681 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -19,6 +19,7 @@ import {
captureTaskSpaceUserBoundary,
createTaskSpaceHandle,
initializeTaskSpaceHandle,
+ rollbackCreatedTaskSpace,
} from "./page-model.js";
import {
loadBrowserToolSource,
@@ -318,7 +319,7 @@ async function initializeResolvedTaskSpace(resolution) {
} catch (error) {
// A fresh space must not survive without its canonical p1 ledger entry.
// Preserve the initialization error if native rollback is unavailable.
- await task.close().catch(() => {});
+ await rollbackCreatedTaskSpace(task).catch(() => {});
throw error;
}
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index e609b15..ded4507 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -1321,10 +1321,19 @@ test("v2 methods reject option fields that are absent from the public schema", a
() => page.click("button", { trial: true }),
/page\.click received unknown option: trial/,
);
+ await assert.rejects(
+ () => task.finish(),
+ /task\.finish options must be an object/,
+ );
+ await assert.rejects(
+ () => task.finish({}),
+ /task\.finish requires the keep option/,
+ );
+ assert.equal(task.close, undefined, "TaskSpace has one terminal API");
});
});
-test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {
+test("TaskSpace uses spaceId and finishes while keeping every managed Page", async () => {
await withFixture(async (fixture) => {
const lifecycleCalls = [];
const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
@@ -1336,9 +1345,6 @@ test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {
async completeTaskSpace() {
lifecycleCalls.push("finish");
},
- async closeTaskSpace() {
- lifecycleCalls.push("close");
- },
};
const task = taskForRound(fixture, "round-a", services);
@@ -1347,23 +1353,134 @@ test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {
await task.handOff();
const finishTask = taskForRound(fixture, "round-b", services);
- await finishTask.newPage();
- await finishTask.finish();
+ const page = await finishTask.newPage();
+ await finishTask.finish({ keep: "all" });
assert.deepEqual((await ledger.read(7)).pages, {});
+ assert.equal(fixture.tabs.has(page.targetId), true);
- const closeTask = taskForRound(fixture, "round-c", services);
- await closeTask.close();
+ assert.deepEqual(lifecycleCalls, ["handOff", "finish"]);
+ assert(
+ fixture.calls
+ .filter(([name]) => name === "selectSpace")
+ .every(([, spaceId]) => spaceId === 7),
+ );
+ });
+});
- assert.deepEqual(lifecycleCalls, ["handOff", "finish", "close"]);
- assert.deepEqual(
- fixture.calls.filter(([name]) => name === "selectSpace"),
- [
- ["selectSpace", 7],
- ["selectSpace", 7],
- ["selectSpace", 7],
- ["selectSpace", 7],
- ],
+test("TaskSpace finish keeps named Pages and protects unknown-origin Pages", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", {
+ ledger,
+ async completeTaskSpace() {
+ lifecycleCalls.push("finish");
+ },
+ async closeTaskSpace() {
+ lifecycleCalls.push("close");
+ },
+ });
+ const p1 = await openTestPage(task, "https://example.test/one");
+ const p2 = await openTestPage(task, "https://example.test/two");
+ const p3 = await openTestPage(task, "https://example.test/three");
+ fixture.addExternalTab("target-user", "https://example.test/user");
+ await ledger.addPage(7, "target-user", {
+ as: "user-page",
+ openedBy: "unknown",
+ });
+
+ await task.finish({ keep: ["p2"] });
+
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.deepEqual([...fixture.tabs.keys()].sort(), [
+ p2.targetId,
+ "target-user",
+ ]);
+ assert.equal(fixture.tabs.has(p1.targetId), false);
+ assert.equal(fixture.tabs.has(p3.targetId), false);
+ assert.deepEqual((await ledger.read(7)).pages, {});
+ });
+});
+
+test("TaskSpace finish closes the whole space when no Pages are retained", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", {
+ ledger,
+ async completeTaskSpace() {
+ lifecycleCalls.push("finish");
+ },
+ async closeTaskSpace() {
+ lifecycleCalls.push("close");
+ },
+ });
+ await openTestPage(task, "https://example.test/one");
+
+ await task.finish({ keep: [] });
+
+ assert.deepEqual(lifecycleCalls, ["close"]);
+ assert.equal(
+ fixture.calls.some(
+ ([name, method]) => name === "cdp" && method === "Target.closeTarget",
+ ),
+ false,
+ "closing the whole space does not close its Pages one by one",
);
+ assert.deepEqual((await ledger.read(7)).pages, {});
+ });
+});
+
+test("TaskSpace finish keeps protected unmanaged tabs even with an empty keep list", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", {
+ ledger,
+ async completeTaskSpace() {
+ lifecycleCalls.push("finish");
+ },
+ async closeTaskSpace() {
+ lifecycleCalls.push("close");
+ },
+ });
+ const agentPage = await openTestPage(task, "https://example.test/agent");
+ fixture.addExternalTab("target-user", "https://example.test/user");
+ await ledger.keepUnmanaged(7, "target-user", "unknown");
+
+ await task.finish({ keep: [] });
+
+ assert.deepEqual(lifecycleCalls, ["finish"]);
+ assert.equal(fixture.tabs.has(agentPage.targetId), false);
+ assert.equal(fixture.tabs.has("target-user"), true);
+ });
+});
+
+test("TaskSpace finish validates every retained label before closing Pages", async () => {
+ await withFixture(async (fixture) => {
+ const lifecycleCalls = [];
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
+ const task = taskForRound(fixture, "round-a", {
+ ledger,
+ async completeTaskSpace() {
+ lifecycleCalls.push("finish");
+ },
+ async closeTaskSpace() {
+ lifecycleCalls.push("close");
+ },
+ });
+ const p1 = await openTestPage(task, "https://example.test/one");
+ const p2 = await openTestPage(task, "https://example.test/two");
+
+ await assert.rejects(
+ () => task.finish({ keep: ["p2", "missing"] }),
+ /page label not found: missing/,
+ );
+
+ assert.deepEqual(lifecycleCalls, []);
+ assert.equal(fixture.tabs.has(p1.targetId), true);
+ assert.equal(fixture.tabs.has(p2.targetId), true);
+ assert.deepEqual(Object.keys((await ledger.read(7)).pages), ["p1", "p2"]);
});
});
@@ -1430,7 +1547,10 @@ test("TaskSpace keeps Page state when native finish fails", async () => {
});
await openTestPage(task, "https://example.test/managed");
- await assert.rejects(() => task.finish(), /native finish failed/);
+ await assert.rejects(
+ () => task.finish({ keep: "all" }),
+ /native finish failed/,
+ );
assert.deepEqual((await ledger.read(7)).pages, {
p1: { targetId: "target-1", openedBy: "agent" },
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index ed4a1e7..f3b2f70 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -157,6 +157,10 @@ type WaitForControlOptions = {
timeout?: number;
};
+type FinishOptions = {
+ keep: "all" | string[];
+};
+
type PageWaitForFileChooserOptions = {
timeout?: number;
};
@@ -591,6 +595,7 @@ const unmanagedPageConstructorToken = Symbol("UnmanagedPage");
const captureUserBoundaryToken = Symbol("captureUserBoundary");
const initializeTaskSpaceToken = Symbol("initializeTaskSpace");
const initializeCreatedSpaceToken = Symbol("initializeCreatedSpace");
+const rollbackCreatedTaskSpaceToken = Symbol("rollbackCreatedTaskSpace");
const defaultGate: OperationGate = {
withSpace: defaultWithSpace,
@@ -730,6 +735,11 @@ export async function initializeTaskSpaceHandle(
await task.initializeBackgroundPageDiscovery(initializeTaskSpaceToken);
}
+/** Close a newly created space whose Page-model initialization did not commit. */
+export async function rollbackCreatedTaskSpace(task: TaskSpace): Promise<void> {
+ await task[rollbackCreatedTaskSpaceToken]();
+}
+
class TaskSpace {
readonly taskId?: string | number;
readonly id: number;
@@ -923,26 +933,73 @@ class TaskSpace {
});
}
- /** Finish the task, keep its browser space for the user, and drop Page state. */
- async finish(): Promise<void> {
+ /** Finish the task with an explicit managed-Page retention policy. */
+ async finish(options: FinishOptions): Promise<void> {
+ validatePublicApiOptions("TaskSpace.finish", options);
+ if (!Object.hasOwn(options, "keep") || options.keep === undefined) {
+ throw new TypeError(
+ "task.finish requires the keep option. Expected: await task.finish({ keep })",
+ );
+ }
await this.#services.gate.withSpace(this.spaceId, async () => {
+ const { ledger, tabs } = await this.#reconcilePages();
+ const keepLabels =
+ options.keep === "all"
+ ? new Set(Object.keys(ledger.pages))
+ : new Set(options.keep);
+ for (const label of keepLabels) {
+ if (!ledger.pages[label]) {
+ // Reuse the ledger's permanent-label diagnostics and validate every
+ // requested label before closing any Page.
+ await this.#services.ledger.getPage(this.spaceId, label);
+ }
+ }
+
+ const managedByTarget = new Map(
+ Object.values(ledger.pages).map((page) => [page.targetId, page]),
+ );
+ const hasProtectedTabs = tabs.some((tab) => {
+ const managed = managedByTarget.get(tab.targetId);
+ return !managed || managed.openedBy === "unknown";
+ });
+
+ if (
+ options.keep !== "all" &&
+ options.keep.length === 0 &&
+ !hasProtectedTabs
+ ) {
+ await this.#services.closeTaskSpace();
+ await this.#discardTerminalState();
+ return;
+ }
+
+ const labelsToClose = Object.entries(ledger.pages)
+ .filter(
+ ([label, page]) =>
+ page.openedBy === "agent" && !keepLabels.has(label),
+ )
+ .map(([label]) => label);
+ for (const label of labelsToClose) {
+ await this.page(label).close();
+ }
await this.#services.completeTaskSpace();
- await this.#services.ledger.discard(this.spaceId);
- this.#stopBackgroundPageDiscovery();
- clearSpacePageNotices(this.spaceId);
+ await this.#discardTerminalState();
});
}
- /** Close the task space and drop its Page state. */
- async close(): Promise<void> {
+ async [rollbackCreatedTaskSpaceToken](): Promise<void> {
await this.#services.gate.withSpace(this.spaceId, async () => {
await this.#services.closeTaskSpace();
- await this.#services.ledger.discard(this.spaceId);
- this.#stopBackgroundPageDiscovery();
- clearSpacePageNotices(this.spaceId);
+ await this.#discardTerminalState();
});
}
+ async #discardTerminalState(): Promise<void> {
+ await this.#services.ledger.discard(this.spaceId);
+ this.#stopBackgroundPageDiscovery();
+ clearSpacePageNotices(this.spaceId);
+ }
+
/** Send a Target or Browser domain command within this selected space. */
async cdp(
method: string,
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index f721d8a..9ca3cac 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -20,6 +20,7 @@ test("the public API schema contains the v2 entry points and object methods", ()
"TaskSpace.pages",
"TaskSpace.tabs",
"TaskSpace.newPage",
+ "TaskSpace.finish",
"Page.snapshot",
"Page.reload",
"Page.targetId",
@@ -38,6 +39,7 @@ test("the public API schema contains the v2 entry points and object methods", ()
assert(names.has(name), `missing public API schema entry: ${name}`);
}
assert.equal(names.has("TaskSpace.listPages"), false);
+ assert.equal(names.has("TaskSpace.close"), false);
assert.equal(names.has("Page.scrollBy"), false);
});
@@ -51,6 +53,9 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
timeout: 500,
});
validatePublicApiOptions("Page.fetch", { saveAs: "/tmp/image.png" });
+ validatePublicApiOptions("TaskSpace.finish", { keep: [] });
+ validatePublicApiOptions("TaskSpace.finish", { keep: ["p2"] });
+ validatePublicApiOptions("TaskSpace.finish", { keep: "all" });
for (const waitUntil of [
"commit",
"domcontentloaded",
@@ -87,6 +92,14 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>
() => validatePublicApiOptions("Page.click", { button: "primary" }),
/button must be one of left, middle, right/,
);
+ assert.throws(
+ () => validatePublicApiOptions("TaskSpace.finish", { keep: true }),
+ /keep must be "all" or an array of unique non-empty Page labels/,
+ );
+ assert.throws(
+ () => validatePublicApiOptions("TaskSpace.finish", { keep: ["p2", "p2"] }),
+ /keep must be "all" or an array of unique non-empty Page labels/,
+ );
});
test("the generated reference contains signatures and option descriptions", () => {
@@ -96,6 +109,11 @@ test("the generated reference contains signatures and option descriptions", () =
assert.match(markdown, /`await taskSpace\(nameOrId, \{ profileId\? \}\)`/);
assert.match(markdown, /a new space starts with managed Page p1/);
assert.match(markdown, /`await task\.newPage\(\)`/);
+ assert.match(
+ markdown,
+ /`await task\.finish\(\{ keep \}\)`.*keep selected managed Pages/,
+ );
+ assert.doesNotMatch(markdown, /task\.close/);
assert.match(
markdown,
/`await page\.goto\(url, \{ referer\?, timeout\?, waitUntil\? \}\)`/,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 4ea278c..4e0e262 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -4,6 +4,7 @@ export type PublicApiOptionKind =
| "finiteNumber"
| "nonNegativeNumber"
| "nonEmptyString"
+ | "pageRetention"
| "positiveInteger"
| "positiveMilliseconds"
| "string"
@@ -157,13 +158,15 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
},
{
name: "TaskSpace.finish",
- signature: "await task.finish()",
- summary: "Finish the task and keep the browser space for the user.",
- },
- {
- name: "TaskSpace.close",
- signature: "await task.close()",
- summary: "Close the task space.",
+ signature: "await task.finish({ keep })",
+ summary:
+ "Finish the task and keep selected managed Pages; an empty list closes the space when no protected tabs remain.",
+ options: {
+ keep: option(
+ "pageRetention",
+ 'Required Page retention policy: "all" or an array of managed Page labels.',
+ ),
+ },
},
{
name: "TaskSpace.cdp",
@@ -708,6 +711,13 @@ function validateOptionValue(
case "nonEmptyString":
valid = typeof value === "string" && value.length > 0;
break;
+ case "pageRetention":
+ valid =
+ value === "all" ||
+ (Array.isArray(value) &&
+ value.every((item) => typeof item === "string" && item.length > 0) &&
+ new Set(value).size === value.length);
+ break;
case "positiveInteger":
valid = Number.isInteger(value) && (value as number) > 0;
break;
@@ -745,6 +755,11 @@ function validateOptionValue(
`${apiName} ${optionName} must be a positive integer`,
);
}
+ if (specification.kind === "pageRetention") {
+ throw new TypeError(
+ `${apiName} ${optionName} must be "all" or an array of unique non-empty Page labels`,
+ );
+ }
if (specification.kind === "stringRecord") {
throw new TypeError(
`${apiName} ${optionName} must be an object with string values`,
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index c037fa7..92a930c 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -74,7 +74,7 @@ Supported TaskSpace API:
- State: `spaceId`, `name`, `ownership`, `page(label)`, `userPage()`
- Pages: `await task.pages()`, `await task.tabs()`, `newPage()`,
`adopt(page, { as? })`, `release(label)`
-- Control: `waitForControl(options)`, `handOff()`, `finish()`, `close()`
+- Control: `waitForControl(options)`, `handOff()`, `finish({ keep })`
- Advanced: `cdp(method, params, options)`
Pages receive permanent labels such as `p1`, `p2`, and `p3`. Prefer these labels
@@ -383,8 +383,20 @@ const task = await claimTaskSpace(7);
const userPage = task.userPage();
```
-After verifying the result, call `task.close()` by default. Use `task.finish()`
-when the pages must remain available to the user.
+Before returning a successful final response, you must call exactly one
+`await task.finish({ keep: ... })`. Do not report the browser task as complete
+until this call resolves. The `keep` option is required:
+
+```js
+await task.finish({ keep: [] }); // Keep no managed Pages.
+await task.finish({ keep: ["p2"] }); // Keep only p2.
+await task.finish({ keep: "all" }); // Keep every managed Page.
+```
+
+User-created and unmanaged tabs are preserved regardless of this list. Do not
+close unwanted Pages one by one at completion; list the Pages to keep instead.
+Use `page.close()` only while the task is still in progress. Do not call
+`finish()` when the task stops for user control or an error.
If the final output contains `[ego-browser:notice]`, finish the current browser
task, tell the user an Ego Lite update is available, and run
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 5ec6c4b..f643c87 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -22,23 +22,22 @@ Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility s
## TaskSpace
-| API | Options | Purpose |
-| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
-| `task.spaceId` | — | Stable numeric identifier for this task space. |
-| `task.name` | — | Human-readable task-space name. |
-| `task.ownership` | — | Ownership state captured when this TaskSpace was created. |
-| `task.page(label)` | — | Create a lazy Page handle for a durable page label. |
-| `task.userPage()` | — | Return the tab active at the claim/takeover boundary, when one was captured. |
-| `await task.pages()` | — | List the managed Page handles in this space. |
-| `await task.tabs()` | — | List managed Pages and unmanaged tabs in this space. |
-| `await task.newPage()` | — | Create and durably label a blank Page. |
-| `await task.adopt(unmanagedPage, { as? })` | `as` — Permanent Page label. | Bring an unmanaged tab under the Page lifecycle. |
-| `await task.release(label)` | — | Stop managing an unknown-origin Page without closing it. |
-| `await task.waitForControl({ interval?, timeout? })` | `interval` — Polling interval in milliseconds.<br>`timeout` — Maximum duration in milliseconds. | Wait for Agent control without taking it from the user. |
-| `await task.handOff()` | — | Give control of this space to the user. |
-| `await task.finish()` | — | Finish the task and keep the browser space for the user. |
-| `await task.close()` | — | Close the task space. |
-| `await task.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a Target or Browser domain CDP command. |
+| API | Options | Purpose |
+| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| `task.spaceId` | — | Stable numeric identifier for this task space. |
+| `task.name` | — | Human-readable task-space name. |
+| `task.ownership` | — | Ownership state captured when this TaskSpace was created. |
+| `task.page(label)` | — | Create a lazy Page handle for a durable page label. |
+| `task.userPage()` | — | Return the tab active at the claim/takeover boundary, when one was captured. |
+| `await task.pages()` | — | List the managed Page handles in this space. |
+| `await task.tabs()` | — | List managed Pages and unmanaged tabs in this space. |
+| `await task.newPage()` | — | Create and durably label a blank Page. |
+| `await task.adopt(unmanagedPage, { as? })` | `as` — Permanent Page label. | Bring an unmanaged tab under the Page lifecycle. |
+| `await task.release(label)` | — | Stop managing an unknown-origin Page without closing it. |
+| `await task.waitForControl({ interval?, timeout? })` | `interval` — Polling interval in milliseconds.<br>`timeout` — Maximum duration in milliseconds. | Wait for Agent control without taking it from the user. |
+| `await task.handOff()` | — | Give control of this space to the user. |
+| `await task.finish({ keep })` | `keep` — Required Page retention policy: "all" or an array of managed Page labels. | Finish the task and keep selected managed Pages; an empty list closes the space when no protected tabs remain. |
+| `await task.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a Target or Browser domain CDP command. |
## Page