pi-suite 0.3.0 → 0.3.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-suite",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Custom modular Pi extension suite",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,21 +1,21 @@
1
- import { createHash } from 'node:crypto';
2
1
  import type { AgentBeforeSettleEvent, BoundaryResult, ExtensionAPI, ExtensionContext, TurnEndEvent } from '@earendil-works/pi-coding-agent';
3
2
  import type { SessionBinding, Binding } from '../binding.ts';
4
- import { isolateIds, replayIds, replayPayload, resourceMismatch } from './payload.ts';
3
+ import { projectReplay, replayPayload, resourceMismatch, sha256, type RepairKind, type ReplayReferences } from './payload.ts';
5
4
 
6
5
  export const RECOVERY_ENTRY = 'pi-suite:responses-isolation';
7
- type Isolation = { version: 1; scope: string; ids: string[] };
8
- type Request = { generation: number; binding: Binding; scope: string; leaf: string | null; ids: string[]; signal?: AbortSignal };
6
+ type Isolation = { version: 2; scope: string; ids: string[]; ciphers: string[] };
7
+ type IsolationSets = { ids: Set<string>; ciphers: Set<string> };
8
+ type Request = ReplayReferences & { generation: number; binding: Binding; scope: string; leaf: string | null; signal?: AbortSignal };
9
9
  type Failure = { request: Request; entryId: string; error: string };
10
10
 
11
11
  /** Per-session request projection only; retries/backoff and their budgets belong to Pi.
12
- * The append-only branch record stores IDs and a hashed endpoint scope, never payload/auth.
12
+ * The append-only branch record stores IDs, cipher hashes and a hashed endpoint scope, never payload/auth.
13
13
  */
14
14
  export class ResponsesRecovery {
15
- private isolated = new Map<string, Set<string>>();
15
+ private isolated = new Map<string, IsolationSets>();
16
16
  private request?: Request;
17
17
  private failure?: Failure;
18
- private recovering?: { generation: number; scope: string };
18
+ private recovering?: { scope: string; used: Set<RepairKind> };
19
19
  private generation = 0;
20
20
  constructor(private binding: SessionBinding, private enabled: boolean) {}
21
21
 
@@ -25,15 +25,26 @@ export class ResponsesRecovery {
25
25
  if (!this.enabled || !ctx) return;
26
26
  for (const entry of ctx.sessionManager.getBranch()) {
27
27
  if (entry.type !== 'custom' || entry.customType !== RECOVERY_ENTRY) continue;
28
- const data = entry.data as Partial<Isolation> | undefined;
29
- if (!data || data.version !== 1 || typeof data.scope !== 'string' || !Array.isArray(data.ids) ||
30
- data.ids.some(id => typeof id !== 'string')) throw new Error('Invalid Responses isolation record');
31
- const ids = this.isolated.get(data.scope) ?? new Set<string>();
32
- for (const id of data.ids) ids.add(id);
33
- this.isolated.set(data.scope, ids);
28
+ const data = entry.data as Partial<Omit<Isolation, 'version'> & { version: 1 | 2 }> | undefined;
29
+ // A v1 branch only isolated IDs. Don't treat a malformed v2 record as v1
30
+ // or the next request could silently replay ciphertext already isolated.
31
+ const ciphers = data?.version === 1 ? [] : data?.ciphers;
32
+ if (!data || (data.version !== 1 && data.version !== 2) || typeof data.scope !== 'string' ||
33
+ !Array.isArray(data.ids) || data.ids.some(id => typeof id !== 'string') ||
34
+ !Array.isArray(ciphers) || ciphers.some(cipher => typeof cipher !== 'string' || !/^[a-f0-9]{64}$/.test(cipher))) {
35
+ throw new Error('Invalid Responses isolation record');
36
+ }
37
+ this.addIsolation({ version: 2, scope: data.scope, ids: data.ids, ciphers });
34
38
  }
35
39
  }
36
40
 
41
+ private addIsolation({ scope, ids, ciphers }: Isolation): void {
42
+ const known = this.isolated.get(scope) ?? { ids: new Set<string>(), ciphers: new Set<string>() };
43
+ for (const id of ids) known.ids.add(id);
44
+ for (const cipher of ciphers) known.ciphers.add(cipher);
45
+ this.isolated.set(scope, known);
46
+ }
47
+
37
48
  beforeRequest(payload: unknown, ctx: ExtensionContext): unknown {
38
49
  // A new final payload invalidates the last attempt, but not the recovery phase:
39
50
  // a native 429/5xx retry is still part of the same repair.
@@ -42,11 +53,12 @@ export class ResponsesRecovery {
42
53
  if (!this.enabled || !active || active.ctx.sessionManager !== ctx.sessionManager || model?.api !== 'openai-responses') return;
43
54
  const wire = replayPayload(payload, model.id);
44
55
  if (!wire) return;
45
- const scope = createHash('sha256').update(JSON.stringify([model.provider, model.api, model.id, model.baseUrl])).digest('hex');
56
+ const scope = sha256(JSON.stringify([model.provider, model.api, model.id, model.baseUrl]));
46
57
  if (this.recovering && this.recovering.scope !== scope) this.recovering = undefined;
47
- const projected = isolateIds(wire, this.isolated.get(scope) ?? new Set());
58
+ const { projected, ids, ciphers } = projectReplay(wire, this.isolated.get(scope));
59
+ // Raw ciphertext is needed for fragment matching, but lives only in the in-flight request state.
48
60
  this.request = { generation: ++this.generation, binding: active, scope,
49
- leaf: ctx.sessionManager.getLeafId(), ids: replayIds(projected ?? wire), signal: ctx.signal };
61
+ leaf: ctx.sessionManager.getLeafId(), ids, ciphers, signal: ctx.signal };
50
62
  return projected;
51
63
  }
52
64
 
@@ -72,24 +84,30 @@ export class ResponsesRecovery {
72
84
  beforeSettle(event: AgentBeforeSettleEvent): BoundaryResult | undefined {
73
85
  const failure = this.failure;
74
86
  if (!failure || event.outcome !== 'error' || failure.request.signal?.aborted || !this.binding.isCurrent(failure.request.binding) ||
75
- failure.request.generation !== this.request?.generation || !failure.request.ids.length ||
76
- !resourceMismatch(failure.error, failure.request.ids)) return;
77
- // One repair phase may span many native attempts, but never opens a second budget
78
- // when those attempts finally exhaust. A successful turn permits a later new phase.
79
- if (this.recovering) return;
87
+ failure.request.generation !== this.request?.generation) return;
88
+ const kind = resourceMismatch(failure.error, failure.request);
89
+ // One phase can span many native attempts. Give ID and cipher repair separate
90
+ // one-use slots: a resource repair can expose a cipher error on the very next request.
91
+ // Only a successful turn permits a later new phase at this scope.
92
+ if (!kind || this.recovering?.used.has(kind)) return;
80
93
  const source = event.context.contextEntries.find(entry => entry.sourceEntry.id === failure.entryId);
81
94
  if (!source) return; // Compaction/another projection removed the source from this boundary.
82
95
  const visible = source.messages.length;
83
96
  if (!visible && event.continue) return; // A preceding extension already owns this failure.
84
- const { scope, ids, generation } = failure.request;
85
- const known = this.isolated.get(scope) ?? new Set<string>();
86
- const fresh = ids.filter(id => !known.has(id));
87
- if (!fresh.length) return;
88
- this.recovering = { generation, scope };
89
- for (const id of fresh) known.add(id);
90
- this.isolated.set(scope, known);
97
+ const { scope, ids, ciphers } = failure.request;
98
+ const known = this.isolated.get(scope);
99
+ // Cipher repair also isolates IDs: retained tool calls and messages must not
100
+ // reference upstream state that required the dropped reasoning.
101
+ const record: Isolation = { version: 2, scope,
102
+ ids: [...new Set(ids)].filter(id => !known?.ids.has(id)),
103
+ ciphers: kind === 'cipher' ? [...new Set(ciphers.map(sha256))].filter(hash => !known?.ciphers.has(hash)) : [],
104
+ };
105
+ if (!record.ids.length && !record.ciphers.length) return;
106
+ this.recovering ??= { scope, used: new Set() };
107
+ this.recovering.used.add(kind);
108
+ this.addIsolation(record);
91
109
  return { continue: true, entries: [...event.entries,
92
- { type: 'custom', customType: RECOVERY_ENTRY, data: { version: 1, scope, ids: fresh } satisfies Isolation },
110
+ { type: 'custom', customType: RECOVERY_ENTRY, data: record },
93
111
  ...(visible ? [{ type: 'context_edit' as const, targetId: failure.entryId, replacement: null }] : []),
94
112
  ] };
95
113
  }
@@ -1,5 +1,10 @@
1
+ import { createHash } from 'node:crypto';
2
+
1
3
  type Item = Record<string, unknown>;
2
4
  export type ReplayPayload = Item & { input: Item[] };
5
+ export type ReplayReferences = { ids: string[]; ciphers: string[] };
6
+ export type RepairKind = 'id' | 'cipher';
7
+ export const sha256 = (value: string): string => createHash('sha256').update(value).digest('hex');
3
8
  const object = (value: unknown): value is Item => value !== null && typeof value === 'object' && !Array.isArray(value);
4
9
  const upstreamId = (item: Item): string | undefined => typeof item.id === 'string' &&
5
10
  /^(?:rs|msg|fc|ctc)_/.test(item.id) && !item.id.startsWith('msg_pi_') ? item.id : undefined;
@@ -41,38 +46,56 @@ export function replayPayload(value: unknown, model: string): ReplayPayload | un
41
46
  return value as ReplayPayload;
42
47
  }
43
48
 
44
- export function replayIds(payload: ReplayPayload): string[] {
45
- return payload.input.flatMap(item => {
46
- if (!['reasoning', 'message', 'function_call', 'custom_tool_call'].includes(String(item.type))) return [];
47
- const id = upstreamId(item); return id ? [id] : [];
48
- });
49
- }
50
-
51
- /** Copy only the changed path. Body, cipher, phase, arguments and call_id retain identity. */
52
- export function isolateIds(payload: ReplayPayload, ids: ReadonlySet<string>): ReplayPayload | undefined {
53
- let changed = false;
54
- const input = payload.input.map(item => {
49
+ /** Capture only what actually leaves after projection so a later failure can be
50
+ * matched even when an earlier ID repair already removed every upstream ID.
51
+ * Copy only the changed path; retained body, phase, arguments and call_id keep identity.
52
+ */
53
+ export function projectReplay(payload: ReplayPayload, isolated?: { ids: ReadonlySet<string>; ciphers: ReadonlySet<string> }):
54
+ ReplayReferences & { projected?: ReplayPayload } {
55
+ const ids: string[] = [], ciphers: string[] = [];
56
+ let input: Item[] | undefined;
57
+ for (const [index, item] of payload.input.entries()) {
58
+ if (item.type === 'reasoning') {
59
+ const cipher = item.encrypted_content as string; // replayPayload validated the wire shape.
60
+ // The ciphertext belongs to the former account, so removing only the ID cannot make it replayable.
61
+ if (isolated?.ciphers.size && isolated.ciphers.has(sha256(cipher))) {
62
+ input ??= payload.input.slice(0, index);
63
+ continue;
64
+ }
65
+ ciphers.push(cipher);
66
+ }
55
67
  const id = upstreamId(item);
56
- if (!id || !ids.has(id)) return item;
57
- changed = true;
58
- const { id: _id, ...replay } = item;
59
- return replay;
60
- });
61
- return changed ? { ...payload, input } : undefined;
68
+ if (id && isolated?.ids.has(id)) {
69
+ const { id: _id, ...replay } = item;
70
+ (input ??= payload.input.slice(0, index)).push(replay);
71
+ } else {
72
+ if (id && ['reasoning', 'message', 'function_call', 'custom_tool_call'].includes(String(item.type))) ids.push(id);
73
+ input?.push(item);
74
+ }
75
+ }
76
+ return { ids, ciphers, projected: input && { ...payload, input } };
62
77
  }
63
78
 
64
79
  /** SDK errors are normalized even when an HTTP status callback is unavailable.
65
- * Require a specific ownership/dependency failure, not a generic HTTP 400 or crypto error.
80
+ * Require a specific ownership/dependency or encrypted reasoning failure, not a generic HTTP 400 or crypto error.
66
81
  */
67
- export function resourceMismatch(error: string, ids: readonly string[]): boolean {
82
+ export function resourceMismatch(error: string, { ids, ciphers }: ReplayReferences): RepairKind | undefined {
68
83
  const text = error.toLowerCase();
69
- if (/\b(?:401|403|429|5\d\d)\b|rate.?limit|quota|billing|context.{0,20}(?:length|window)|maximum context/.test(text)) return false;
84
+ if (/\b(?:401|403|429|5\d\d)\b|rate.?limit|quota|billing|context.{0,20}(?:length|window)|maximum context/.test(text)) return;
85
+ if (/\bencrypted\b[^\r\n]*?\b(?:cannot|could not) be (?:verified|decrypted)\b/.test(text)) {
86
+ if (!ciphers.length) return;
87
+ // Gateways can identify a ciphertext without naming its item. Compare any
88
+ // reported fragment case-sensitively; a mismatch invalidates the correlation.
89
+ for (const [, prefix, suffix] of error.matchAll(/(?<![A-Za-z0-9_-])([A-Za-z0-9_-]{4,})\.{3}([A-Za-z0-9_-]{4,})/g)) {
90
+ if (!ciphers.some(cipher => cipher.startsWith(prefix) && cipher.endsWith(suffix))) return;
91
+ }
92
+ return 'cipher';
93
+ }
70
94
  const namedItem = ids.some(id => error.includes(id));
71
95
  const resource = /(?:different|another|across|cross)[ -](?:openai[ -])?(?:resource|organization|project)|(?:resource|organization|project).{0,50}(?:mismatch|does not match|not belong)/.test(text);
72
96
  // Gateways may omit the item ID and qualify/redact the resource name. Recognize
73
97
  // the explicit creation-origin sentence, not arbitrary words between "different" and "resource".
74
98
  const createdElsewhere = /\bitem was created (?:under|in) (?:a different|another) [^.!?\r\n]{0,80}\b(?:resource|organization|project)\b/.test(text);
75
99
  const ownership = namedItem && /not found|does not exist|belongs to|was created in|provided without.{0,80}required|not owned by/.test(text);
76
- const cipher = namedItem && /encrypted.{0,40}(?:cannot|could not|failed|invalid|verif|decrypt)|(?:decrypt|verif).{0,40}(?:encrypted|reasoning)/.test(text);
77
- return resource || createdElsewhere || ownership || cipher;
100
+ if (resource || createdElsewhere || ownership) return 'id';
78
101
  }