@parcha/pi-browser 0.1.0-beta.28 → 0.1.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/durable.js CHANGED
@@ -4,7 +4,7 @@ import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, listedFor, WEB_TOOL_
4
4
  import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
5
  import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
7
- import { browserFailure, classifyBrowserError } from "./core/failures.js";
7
+ import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
8
8
  import { workspaceFiles } from "./core/files.js";
9
9
  import { drivingGuarded } from "./core/driving-guard.js";
10
10
  import { drivingGates, keptFor, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
@@ -256,6 +256,13 @@ async function create(c, scope, overrides, presetTag) {
256
256
  await scope.commit((tx) => c.store.move(tx, row, { state: "live", resourceId: made.id, at: now() }));
257
257
  return made;
258
258
  }, async (error) => {
259
+ // A 401 or 403 is the provider's own answer that nothing was made: the record ends at once, with no lookup by tag
260
+ // and no release delayed for a create that might still land.
261
+ if (isRefusal(error)) {
262
+ await scope.commit((tx) => c.store.move(tx, row, { state: "released", reason: "create_failed", at: now() }));
263
+ await c.store.emitReleased(scope.cid, tag, scope.read, scope.context);
264
+ throw failure(error, scope, c.redact);
265
+ }
259
266
  const found = await provider.findByTag(tag, scope.signal).catch(() => []);
260
267
  // The session found by its tag is the one kept (bindByTag releases the others first), and it is owned before it is
261
268
  // recorded, as a create's own answer is: a store that cannot record it still lets close release it.
@@ -689,9 +696,7 @@ async function chargeCall(c, api, context) {
689
696
  const record = currentRecord(await tx.doc(c.Sessions, api.conversationId), PLANE);
690
697
  if (record?.state !== "live")
691
698
  return null;
692
- const { spent, usage } = c.meter(record.spent, now());
693
- record.spent = spent;
694
- return usage;
699
+ return c.bill(tx, api.conversationId, record, now(), false, { callId: api.callId });
695
700
  }, context);
696
701
  }
697
702
  const withSessionTime = (own, charged) => {
@@ -851,10 +856,20 @@ export function createBrowserExtension(options) {
851
856
  const charged = sessionCharge(spent, at, prices, priceState, final);
852
857
  return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage };
853
858
  };
859
+ const bill = async (tx, conversationId, record, at, final, call) => {
860
+ const before = record.spent;
861
+ if (before.final)
862
+ return null;
863
+ const { spent, usage } = meter(before, at, final);
864
+ record.spent = spent;
865
+ const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
866
+ await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state }, tx, call);
867
+ return usage;
868
+ };
854
869
  const leaving = new Map();
855
870
  const owned = new Map();
856
871
  const store = custodyStore({
857
- name, Config, Sessions, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
872
+ name, Config, Sessions, meter, bill, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
858
873
  providerOf: (read, cid, plane, context) => providerOf(readers, read, cid, plane, context),
859
874
  emit: (cid, label, record, change) => {
860
875
  // A released session's poll ends with it, whatever released it, and nothing is left to release directly.
@@ -870,7 +885,7 @@ export function createBrowserExtension(options) {
870
885
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
871
886
  });
872
887
  const c = {
873
- ...readers, name, Sessions, Children, store, meter, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
888
+ ...readers, name, Sessions, Children, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), childTurns: oneAtATime(), guards: new Map(), owned, failed: false, ending: null, opened: null, incarnation: randomUUID(),
874
889
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
875
890
  };
876
891
  // Every browser tool is a model call on its session's driving gate: refused while a person drives the live view, and the viewer's input is held while it runs. The host's own
@@ -888,7 +903,14 @@ export function createBrowserExtension(options) {
888
903
  async reconcile(harness, isActive, context) {
889
904
  c.opened = { harness, context };
890
905
  c.ending = endingOf(harness);
891
- return store.reconcileAll(harness, isActive, context);
906
+ const report = await store.reconcileAll(harness, isActive, context);
907
+ // A session kept across a reopen has had no call here to arm its idle release: armed now, so one the run no longer
908
+ // uses is released an idle window after the reopen, not at the provider's session timeout.
909
+ for (const row of Object.values((await harness.snapshot(store.Inventory, context))?.rows ?? {}).filter((r) => report.kept.includes(r.tag))) {
910
+ const cid = row.conversationId;
911
+ c.idle.activity(cid, 0, ((await harness.snapshot(Config, cid, context))?.policy.idleReleaseS ?? 0) * 1000);
912
+ }
913
+ return report;
892
914
  },
893
915
  drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
894
916
  async close() {
package/dist/index.d.ts CHANGED
@@ -12,7 +12,9 @@ export * from "./core/guard.js";
12
12
  export * from "./core/host.js";
13
13
  export * from "./core/images.js";
14
14
  export * from "./core/lease.js";
15
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, readPage, type PublicAnswer, type PublicFetchOptions } from "./core/public-fetch.js";
15
+ export * from "./core/page-classifier.js";
16
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, type PublicAnswer, type PublicFetchOptions } from "./core/public-fetch.js";
17
+ export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
16
18
  export * from "./core/receipts.js";
17
19
  export * from "./core/redact.js";
18
20
  export * from "./core/sites.js";
package/dist/index.js CHANGED
@@ -13,7 +13,9 @@ export * from "./core/guard.js";
13
13
  export * from "./core/host.js";
14
14
  export * from "./core/images.js";
15
15
  export * from "./core/lease.js";
16
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, readPage } from "./core/public-fetch.js";
16
+ export * from "./core/page-classifier.js";
17
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch } from "./core/public-fetch.js";
18
+ export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage } from "./core/read-page.js";
17
19
  export * from "./core/receipts.js";
18
20
  export * from "./core/redact.js";
19
21
  export * from "./core/sites.js";
@@ -1,6 +1,7 @@
1
1
  // Credentials come from the host's env and live in this module's memory only: a ref is `{ id, tag }`, and the connect
2
2
  // URL (it carries a signing key) is held here, found again by `retrieve` after a restart.
3
3
  import { createReadStream } from "node:fs";
4
+ import { isRefusal } from "../core/failures.js";
4
5
  import { fetchUsage, resolvePrices, searchUsage } from "../core/usage.js";
5
6
  import { cdpCall } from "./cdp-call.js";
6
7
  import { applyBrowserbaseNoProxy, bindConnectDial, installWebSocketWrapper, rewriteConnectUrl, unbindConnectDial } from "./browserbase-net.js";
@@ -154,8 +155,12 @@ export function browserbaseProvider(options = {}) {
154
155
  throw error;
155
156
  }
156
157
  // At most once: an SDK retry of a create the server already served would open a second paid browser. A failed send keeps
157
- // the profile's claim until findByTag has looked: the session may exist.
158
- const created = await (await client()).sessions.create(body, { maxRetries: 0, signal });
158
+ // the profile's claim until findByTag has looked: the session may exist. A refusal (401, 403) made none, so it frees the claim.
159
+ const created = await (await client()).sessions.create(body, { maxRetries: 0, signal }).catch((error) => {
160
+ if (isRefusal(error))
161
+ freeWriter(spec.tag);
162
+ throw error;
163
+ });
159
164
  connectUrls.set(held(created.id), created.connectUrl);
160
165
  noteWriter(spec.tag, running({ id: created.id, tag: spec.tag }), () => sleep(options.profileSettleMs ?? 5_000));
161
166
  return { id: created.id, tag: spec.tag };
@@ -2,6 +2,7 @@
2
2
  // No error carries the key, the URL or Kernel's text: only the call, the status and the code.
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { readFile } from "node:fs/promises";
5
+ import { isRefusal } from "../core/failures.js";
5
6
  import { directFetch } from "./http.js";
6
7
  import { claimWriter, freeWriter, isWriter, noteWriter } from "./profiles.js";
7
8
  import { accountKey, assertTag, defaultSleep, DEFAULT_CONFIRM, extensionArchive, kernelHoldings, nonEmpty, releaseAndConfirm, tagValue, untilAborted, uploadOnce } from "./shared.js";
@@ -192,8 +193,12 @@ export function kernelProvider(options = {}) {
192
193
  throw error;
193
194
  }
194
195
  // At most once: a lost answer is found again by its tag (findByTag), never by a second create. A failed send keeps the
195
- // profile's claim until findByTag has looked: the browser may exist.
196
- const created = await call("POST", "/browsers", { body, signal });
196
+ // profile's claim until findByTag has looked: the browser may exist. A refusal (401, 403) made none, so it frees the claim.
197
+ const created = await call("POST", "/browsers", { body, signal }).catch((error) => {
198
+ if (isRefusal(error))
199
+ freeWriter(spec.tag);
200
+ throw error;
201
+ });
197
202
  const id = nonEmpty(created.json?.session_id);
198
203
  const url = nonEmpty(created.json?.cdp_ws_url);
199
204
  if (created.status === 404 || !id || !url)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/pi-browser",
3
- "version": "0.1.0-beta.28",
3
+ "version": "0.1.0-beta.30",
4
4
  "description": "Your agent gets its own browser, and you can take over and hand it back.",
5
5
  "keywords": [
6
6
  "pi-package",