@hyperdreamer/pi-webui 1.24.1 → 1.25.0

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 CHANGED
@@ -36,7 +36,7 @@ Requirements:
36
36
 
37
37
  - Node.js 22.19.0 or newer
38
38
  - npm
39
- - Pi Coding Agent `>=0.87.0 <0.88`, configured for your user
39
+ - Pi Coding Agent `>=1.2.0 <2`, configured for your user
40
40
  - git and the development tools your agents need
41
41
 
42
42
  Install PI WEBUI from npm or clone from GitHub:
@@ -33,8 +33,9 @@ import { SessionUnreadStore, } from "./sessionUnreadStore.js";
33
33
  import { createModelTierRegistry, isModelTier, runtimeThinkingLevels, TierResolutionError, } from "./modelTierRegistry.js";
34
34
  import { createUtilityModelExtension, } from "./utilityModelExtension.js";
35
35
  import { createUtilityModelResolver, runWithUtilityModelFallback, } from "./utilityModelResolver.js";
36
- import { inspectSessionModelPolicy, planSessionModelPolicyInitialization, planSessionModelPolicyUpdate, serializeSessionModelPolicy, SessionModelPolicyResolutionError, SESSION_MODEL_POLICY_CUSTOM_TYPE, } from "./sessionModelPolicy.js";
36
+ import { inspectSessionModelPolicy, planSessionModelPolicyInitialization, planSessionModelPolicyUpdate, readPersistedSessionModelPolicy, serializeSessionModelPolicy, SessionModelPolicyResolutionError, SESSION_MODEL_POLICY_CUSTOM_TYPE, } from "./sessionModelPolicy.js";
37
37
  import { fallbackSessionModelPolicy, initialPolicyUnavailableError, } from "./sessionModelPolicyFallback.js";
38
+ import { inspectSessionRuntimeSelection, planSessionRuntimeRestore, } from "./sessionRuntimeRestore.js";
38
39
  import { inspectSessionCreationRootEligibility, inspectSessionCreationSource, serializeSessionCreationSource, SESSION_CREATION_SOURCE_CUSTOM_TYPE, } from "./sessionCreationSource.js";
39
40
  import { RememberCurrentModelPolicyCommand, } from "./rememberCurrentModelPolicy.js";
40
41
  import { StarterModelPolicyPreferenceStore } from "./starterModelPolicyPreferenceStore.js";
@@ -321,7 +322,7 @@ export function createPiWebUiCustomToolDefinitions(cwd, delegationEnabled, spawn
321
322
  : []),
322
323
  ];
323
324
  }
324
- export function createDefaultRuntimeFactory(modelRuntime, sessionManagers, utilityModelResolver, logger, spawn, subsessions, modelPolicy, modelRateLimitOwner, sdk = {
325
+ export function createDefaultRuntimeFactory(modelRuntime, sessionManagers, utilityModelResolver, logger, spawn, subsessions, modelPolicy, modelRateLimitOwner, restore, sdk = {
325
326
  createServices: createAgentSessionServices,
326
327
  createFromServices: createAgentSessionFromServices,
327
328
  }) {
@@ -348,15 +349,26 @@ export function createDefaultRuntimeFactory(modelRuntime, sessionManagers, utili
348
349
  const resolvedDelegationToolsEnabled = delegationToolsEnabled ??
349
350
  (await sessionAllowsDelegationTools(sessionManager, sessionManagers));
350
351
  const customTools = createPiWebUiCustomToolDefinitions(cwd, resolvedDelegationToolsEnabled, spawn, subsessions, modelPolicy);
352
+ const derived = restore === undefined
353
+ ? undefined
354
+ : await restore.prepare({
355
+ sessionId: sessionManager.getSessionId(),
356
+ sessionManager,
357
+ modelRuntime,
358
+ ...(initialModel === undefined ? {} : { explicitModel: initialModel }),
359
+ ...(initialThinkingLevel === undefined
360
+ ? {}
361
+ : { explicitThinkingLevel: initialThinkingLevel }),
362
+ });
363
+ const model = initialModel ?? derived?.model;
364
+ const thinkingLevel = initialThinkingLevel ?? derived?.thinkingLevel;
351
365
  const result = await sdk.createFromServices({
352
366
  services,
353
367
  sessionManager,
354
368
  customTools,
355
369
  ...(sessionStartEvent === undefined ? {} : { sessionStartEvent }),
356
- ...(initialModel === undefined ? {} : { model: initialModel }),
357
- ...(initialThinkingLevel === undefined
358
- ? {}
359
- : { thinkingLevel: initialThinkingLevel }),
370
+ ...(model === undefined ? {} : { model }),
371
+ ...(thinkingLevel === undefined ? {} : { thinkingLevel }),
360
372
  });
361
373
  const delegateStreamFunction = result.session.agent.streamFunction;
362
374
  const limitedStreamFunction = modelRateLimitOwner === undefined
@@ -542,7 +554,7 @@ export class PiSessionService {
542
554
  ? undefined
543
555
  : {
544
556
  inspect: (sessionId) => this.modelPolicyCapability(sessionId),
545
- }, deps.modelRateLimitOwner);
557
+ }, deps.modelRateLimitOwner, { prepare: (input) => this.prepareSessionRuntimeRestore(input) });
546
558
  this.createAgentRuntime =
547
559
  deps.createAgentRuntime ?? defaultCreateAgentRuntime;
548
560
  this.modelTierRegistry =
@@ -1351,12 +1363,16 @@ export class PiSessionService {
1351
1363
  }
1352
1364
  }
1353
1365
  async deliverSubsessionNotification(session, notification) {
1354
- await this.runSessionEntryMutation(session, "deliver a subsession notification", () => session.sendCustomMessage({
1355
- customType: SUBSESSION_NOTIFICATION_CUSTOM_TYPE,
1356
- content: notification.text,
1357
- display: true,
1358
- details: { sessionId: notification.childId },
1359
- }, { triggerTurn: true, deliverAs: "followUp" }));
1366
+ await this.runSessionEntryMutation(session, "deliver a subsession notification", () => {
1367
+ const blocked = this.modelPolicyBlockedReason(session) !== undefined ||
1368
+ this.isModelPolicyMutationActive(session);
1369
+ return session.sendCustomMessage({
1370
+ customType: SUBSESSION_NOTIFICATION_CUSTOM_TYPE,
1371
+ content: notification.text,
1372
+ display: true,
1373
+ details: { sessionId: notification.childId },
1374
+ }, { triggerTurn: !blocked, deliverAs: "followUp" });
1375
+ });
1360
1376
  this.publishStatus(session);
1361
1377
  }
1362
1378
  logSubsessionNotificationFailure(parentId, childId, error) {
@@ -3508,8 +3524,8 @@ export class PiSessionService {
3508
3524
  thinkingLevel: session.thinkingLevel,
3509
3525
  };
3510
3526
  }
3511
- policyEntries(session) {
3512
- return session.sessionManager.getBranch();
3527
+ sessionTranscriptEntries(session) {
3528
+ return session.sessionManager.getEntries?.() ?? session.sessionManager.getBranch();
3513
3529
  }
3514
3530
  async confirmedPolicySnapshot(ref) {
3515
3531
  const session = await this.getOrOpen(ref);
@@ -3518,17 +3534,16 @@ export class PiSessionService {
3518
3534
  const manager = persisted
3519
3535
  ? this.sessionManager.open(sessionFile)
3520
3536
  : session.sessionManager;
3521
- const activeEntries = manager.getBranch();
3522
- // Creation provenance belongs to the durable root file, even when its
3523
- // original entry is not on the currently selected conversation branch.
3524
- const creationSourceEntries = manager.getEntries?.() ?? activeEntries;
3525
- const creationSource = inspectSessionCreationSource(creationSourceEntries);
3537
+ // Creation provenance belongs to the durable root file, even when its original entry is not on the
3538
+ // currently selected conversation branch. The model policy now reads the same session-level list.
3539
+ const entries = manager.getEntries?.() ?? manager.getBranch();
3540
+ const creationSource = inspectSessionCreationSource(entries);
3526
3541
  return {
3527
3542
  cwd: canonicalizeStoredCwd(manager.getCwd()),
3528
3543
  creationSource,
3529
3544
  persisted,
3530
3545
  rootEligibility: this.sessionCreationRootEligibility(manager, creationSource),
3531
- modelPolicy: inspectSessionModelPolicy(activeEntries, this.exactSelectionFromSession(session)),
3546
+ modelPolicy: inspectSessionModelPolicy(entries, this.exactSelectionFromSession(session)),
3532
3547
  transitionInFlight: this.isModelPolicyMutationActive(session),
3533
3548
  };
3534
3549
  }
@@ -3562,7 +3577,7 @@ export class PiSessionService {
3562
3577
  });
3563
3578
  }
3564
3579
  inspectAndCacheSessionModelPolicy(session) {
3565
- const inspection = inspectSessionModelPolicy(this.policyEntries(session), this.exactSelectionFromSession(session));
3580
+ const inspection = inspectSessionModelPolicy(this.sessionTranscriptEntries(session), this.exactSelectionFromSession(session));
3566
3581
  const ladderValidation = this.modelTierRegistry.validate();
3567
3582
  this.modelPolicyInspections.set(session, inspection);
3568
3583
  this.modelPolicyLadderValidations.set(session, ladderValidation);
@@ -3574,8 +3589,99 @@ export class PiSessionService {
3574
3589
  }
3575
3590
  /** Effective block: an unproven runtime restoration outranks an entry defect. */
3576
3591
  modelPolicyBlockedReason(session) {
3577
- return (this.modelPolicyRuntimeBlocks.get(session.sessionId) ??
3578
- this.modelPolicyEntryReasons.get(session));
3592
+ const block = this.modelPolicyRuntimeBlocks.get(session.sessionId);
3593
+ if (block !== undefined)
3594
+ return `MODEL_POLICY_BLOCKED: ${block.reason}`;
3595
+ return this.modelPolicyEntryReasons.get(session);
3596
+ }
3597
+ /**
3598
+ * Restore the session-level recorded model selection into a fresh runtime.
3599
+ * Runs after `createServices` has registered extension providers/models and
3600
+ * before `createFromServices`, so a virtual or extension model is resolvable.
3601
+ */
3602
+ async prepareSessionRuntimeRestore(input) {
3603
+ if (input.explicitModel !== undefined ||
3604
+ input.explicitThinkingLevel !== undefined) {
3605
+ return {};
3606
+ }
3607
+ const entries = input.sessionManager.getEntries?.() ?? input.sessionManager.getBranch();
3608
+ const selection = inspectSessionRuntimeSelection(entries);
3609
+ if (selection.kind === "none")
3610
+ return {};
3611
+ const persistedPolicy = readPersistedSessionModelPolicy(entries);
3612
+ let boundModel;
3613
+ let resolvedModel;
3614
+ if (selection.kind === "selection") {
3615
+ const bound = await this.resolveSessionRuntimeRestoreModel(input.modelRuntime, input.sessionId, selection.model);
3616
+ boundModel = bound?.model;
3617
+ resolvedModel =
3618
+ bound === undefined
3619
+ ? undefined
3620
+ : {
3621
+ provider: bound.model.provider,
3622
+ id: bound.model.id,
3623
+ thinkingLevels: bound.thinkingLevels,
3624
+ };
3625
+ }
3626
+ const existingBlock = this.modelPolicyRuntimeBlocks.get(input.sessionId);
3627
+ const plan = planSessionRuntimeRestore({
3628
+ selection,
3629
+ persistedPolicy,
3630
+ ...(resolvedModel === undefined ? {} : { resolvedModel }),
3631
+ ...(existingBlock === undefined ? {} : { existingBlock }),
3632
+ });
3633
+ // A message-less blocked transcript takes Pi's new-session branch and gains
3634
+ // its fallback model/thinking pair, so a later credentials-return open reads
3635
+ // a disagreement and recovers only through an explicit policy update.
3636
+ if (plan.kind === "none")
3637
+ return {};
3638
+ if (plan.kind === "block") {
3639
+ this.modelPolicyRuntimeBlocks.set(input.sessionId, {
3640
+ cause: plan.cause,
3641
+ reason: plan.reason,
3642
+ });
3643
+ return {};
3644
+ }
3645
+ if (boundModel === undefined)
3646
+ throw new Error("session runtime restore produced an apply plan without a bound model");
3647
+ if (plan.clearSelectionUnavailable) {
3648
+ this.modelPolicyRuntimeBlocks.delete(input.sessionId);
3649
+ }
3650
+ const thinkingLevel = plan.thinkingLevel !== undefined && isKnownThinkingLevel(plan.thinkingLevel)
3651
+ ? plan.thinkingLevel
3652
+ : undefined;
3653
+ return {
3654
+ model: boundModel,
3655
+ ...(thinkingLevel === undefined ? {} : { thinkingLevel }),
3656
+ };
3657
+ }
3658
+ /**
3659
+ * Bind the recorded selection to the runtime catalog. Resolves first, then
3660
+ * makes one `allowNetwork: false` refresh on a miss or a missing auth answer;
3661
+ * a refresh rejection is logged and treated as unbindable.
3662
+ */
3663
+ async resolveSessionRuntimeRestoreModel(modelRuntime, sessionId, selection) {
3664
+ const bound = this.boundSessionRuntimeRestoreModel(modelRuntime, selection);
3665
+ if (bound !== undefined)
3666
+ return bound;
3667
+ try {
3668
+ await modelRuntime.refresh({ allowNetwork: false });
3669
+ }
3670
+ catch (error) {
3671
+ this.logger.info({
3672
+ sessionId,
3673
+ model: `${selection.provider}/${selection.id}`,
3674
+ error: error instanceof Error ? error.message : String(error),
3675
+ }, "session runtime restore model refresh failed");
3676
+ return undefined;
3677
+ }
3678
+ return this.boundSessionRuntimeRestoreModel(modelRuntime, selection);
3679
+ }
3680
+ boundSessionRuntimeRestoreModel(modelRuntime, selection) {
3681
+ const model = modelRuntime.getModel(selection.provider, selection.id);
3682
+ if (model === undefined || !modelRuntime.hasConfiguredAuth(model.provider))
3683
+ return undefined;
3684
+ return { model, thinkingLevels: runtimeThinkingLevels(model) };
3579
3685
  }
3580
3686
  /** Root-session policy initialization, completed before the root is visible. */
3581
3687
  async initializeSessionModelPolicy(session, initializer) {
@@ -3773,7 +3879,10 @@ export class PiSessionService {
3773
3879
  catch (error) {
3774
3880
  const reason = error instanceof Error ? error.message : String(error);
3775
3881
  if (!(await this.restoreExactSelection(session, previous))) {
3776
- this.modelPolicyRuntimeBlocks.set(session.sessionId, `MODEL_POLICY_BLOCKED: ${reason}; the previous model and thinking pair could not be restored`);
3882
+ this.modelPolicyRuntimeBlocks.set(session.sessionId, {
3883
+ cause: "runtime-tuple-unproven",
3884
+ reason: `${reason}; the previous model and thinking pair could not be restored`,
3885
+ });
3777
3886
  }
3778
3887
  this.inspectAndCacheSessionModelPolicy(session);
3779
3888
  options.onTransitionFailure?.(reason);
@@ -3855,7 +3964,7 @@ export class PiSessionService {
3855
3964
  const inspection = this.inspectAndCacheSessionModelPolicy(session);
3856
3965
  const runtimeBlock = this.modelPolicyRuntimeBlocks.get(session.sessionId);
3857
3966
  if (runtimeBlock !== undefined)
3858
- throw new Error(`Cannot ${action}: ${runtimeBlock}`);
3967
+ throw new Error(`Cannot ${action}: MODEL_POLICY_BLOCKED: ${runtimeBlock.reason}`);
3859
3968
  if (inspection.kind === "invalid") {
3860
3969
  throw new Error(`Cannot ${action}: the session model policy entry is invalid (${inspection.reason}). Repair the policy first.`);
3861
3970
  }
@@ -3889,7 +3998,10 @@ export class PiSessionService {
3889
3998
  catch (error) {
3890
3999
  const reason = error instanceof Error ? error.message : String(error);
3891
4000
  if (!(await this.restoreExactSelection(session, previous))) {
3892
- this.modelPolicyRuntimeBlocks.set(session.sessionId, `MODEL_POLICY_BLOCKED: ${reason}; the previous model and thinking pair could not be restored`);
4001
+ this.modelPolicyRuntimeBlocks.set(session.sessionId, {
4002
+ cause: "runtime-tuple-unproven",
4003
+ reason: `${reason}; the previous model and thinking pair could not be restored`,
4004
+ });
3893
4005
  }
3894
4006
  this.inspectAndCacheSessionModelPolicy(session);
3895
4007
  // Only a failure that already moved the runtime tuple is announced; an
@@ -3919,7 +4031,7 @@ export class PiSessionService {
3919
4031
  const inspection = this.inspectAndCacheSessionModelPolicy(session);
3920
4032
  const runtimeBlock = this.modelPolicyRuntimeBlocks.get(session.sessionId);
3921
4033
  if (runtimeBlock !== undefined)
3922
- throw new Error(`Cannot send a prompt: ${runtimeBlock}`);
4034
+ throw new Error(`Cannot send a prompt: MODEL_POLICY_BLOCKED: ${runtimeBlock.reason}`);
3923
4035
  if (inspection.kind === "invalid") {
3924
4036
  throw new Error(`Cannot send a prompt: the session model policy entry is invalid (${inspection.reason}). Repair the policy first.`);
3925
4037
  }
@@ -4022,7 +4134,7 @@ export class PiSessionService {
4022
4134
  sessionId: session.sessionId,
4023
4135
  sessionFile,
4024
4136
  }));
4025
- const inspection = inspectSessionCreationSource(this.policyEntries(session));
4137
+ const inspection = inspectSessionCreationSource(this.sessionTranscriptEntries(session));
4026
4138
  const rootEligibility = this.sessionCreationRootEligibility(session.sessionManager, inspection);
4027
4139
  if (inspection.kind !== "valid" ||
4028
4140
  rootEligibility.kind !== "eligible") {