paseo-plugin-zcode-provider 0.4.2 → 0.4.4

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
@@ -10,7 +10,7 @@ This is an unofficial plugin. It is not endorsed or maintained by ZCode or Z.ai.
10
10
 
11
11
  | Setting | Requirement |
12
12
  | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
13
- | Paseo | 0.8.0 or later; development SDK 0.12.0 |
13
+ | Paseo | 0.9.0 or later; development SDK 0.12.0 |
14
14
  | Plugin Node.js | 22.12.0 or later (the Paseo daemon's runtime) |
15
15
  | Managed setup | darwin-arm64, linux-x64, linux-arm64, win-x64, win-arm64 |
16
16
  | ZCode | Managed: 3.16.2 (release `3.16.2-paseo.1`) with Node.js 24.21.0. Overrides: stable Server 3.14.0+ / Agent 0.16.9+ with Node.js 24.14.0+ |
@@ -30,7 +30,7 @@ To follow the `main` branch instead, install the Git repository with `paseo plug
30
30
 
31
31
  ## Setup
32
32
 
33
- Open **Settings → Plugins → zcode-provider → Settings**. The screen has two tabs: **Runtime** installs and removes the runtime, and **Account** signs in and manages model providers.
33
+ Open **Settings → Plugins → zcode-provider → Settings**. The screen has three tabs: **Runtime** installs and removes the runtime, **Account** signs in and manages model providers, and **Timeline** chooses what ZCode agents add to the timeline.
34
34
 
35
35
  On the **Runtime** tab, choose **Download and install**. The screen lists every download, its SHA-256, size and license before you start. Setup runs on the machine hosting the daemon:
36
36
 
@@ -57,6 +57,10 @@ The **Account** tab uses ZCode's own account and provider services, the same one
57
57
 
58
58
  API keys are sent to ZCode, which stores them as Desktop does, and are never shown again. The plugin itself stores no credentials. Afterwards, choose **ZCode** when creating an agent; the model list is refreshed after each change on Paseo 0.9 or later.
59
59
 
60
+ ### Timeline
61
+
62
+ ZCode adds a line when a turn runs on a different model than the previous turn, such as `Model switched magpie/GLM-5.3-Flash → magpie/auto/glm-5.3-flash`. These lines are hidden by default; turn on **Show model changes** on the **Timeline** tab to show them. The setting is stored by Paseo on the daemon host. It decides each line when the line first arrives: lines already shown stay, and lines that arrived while it was off are not added later. A reopened agent shows its history with the current setting (ADR 24).
63
+
60
64
  ### Coding Plan usage
61
65
 
62
66
  On Paseo 0.11 and later, Paseo's **Usage** screen and sidebar usage summary show a **ZCode** card for the signed-in account's Individual Coding Plan (Z.ai or BigModel). It lists the 5-hour, weekly, monthly tool-call and ZCode MCP quotas with their reset times, as ZCode Desktop does. The plugin asks ZCode's official usage service for this plan only, on the same ZCode Server as the Account tab. The service never uses an API key from the environment. Team Plan and Start Plan are not shown. Paseo 0.12.0 does not yet show usage in a ZCode agent's popover.
@@ -81,8 +85,10 @@ The source baseline is `3c5b227649371507ddc4eb46ac5133afe6db1cab` (ZCode 3.16.2,
81
85
  - Models and reasoning options come from ZCode. Editing modes are `build`, `edit`, `guarded` and `yolo`; `settings.plan_mode` is independent. `guarded` (ZCode's Autonomous mode, Server 3.15.1 or later) runs tools without approval but asks once, each time, before a command that ZCode's safety rules consider risky; it is not offered on older runtimes.
82
86
  - Text, thoughts, tools, subagent progress, usage and history use V4 snapshots and deltas. Tool output is marked when ZCode truncates it. Usage is cumulative; repeated snapshots do not add it again.
83
87
  - Text submitted during generation uses native guidance. Attachments use the native queue. Paseo reports one run across these native turns and completes it only after all accepted input has been consumed and foreground work has ended.
88
+ - Paseo sends every message typed in the app during a run as a steer that asks to clear pending permissions. The plugin queues it first, then declines pending permissions, questions and Plan approvals with their deny action until ZCode reads the message, including requests opened in the meantime. Requests that appear after it is read are left to the user. Declining a Plan approval in Plan mode ends ZCode's turn; the message then starts the next native turn in the same Paseo run (ADR 22).
89
+ - A failed turn reports a code classified from the attribution of ZCode's error: `MODEL_RATE_LIMITED`, `MODEL_AUTH_FAILED`, `MODEL_CONTEXT_EXCEEDED`, `MODEL_NETWORK_ERROR`, `MODEL_PROVIDER_ERROR` or `MODEL_REQUEST_FAILED` when the model provider or network failed, and `NATIVE_TURN_FAILED` otherwise. The message is the plugin's own text with the HTTP status and the provider's error code when known. The provider's own message, which can include a quota reset time, is not shown; Coding Plan reset times appear on Paseo 0.11's Usage screen (ADR 23).
84
90
  - Acceptance is reported once, after the native acknowledgement. Unknown delivery results are never automatically resent. Stop identifies the current native execution, disables automatic queue execution and removes pending input. A new explicit run enables the queue again.
85
- - As in ZCode Desktop, successful hooks are not shown. A finished hook invocation appears once, as a notification, only when a hook was blocked, failed, timed out or was cancelled; context compaction also appears once, when it ends. Paseo appends every notification it receives, so progress is not reported.
91
+ - As in ZCode Desktop, successful hooks are not shown. A finished hook invocation appears once, as a notification, only when a hook was blocked, failed, timed out or was cancelled; context compaction also appears once, when it ends. Paseo appends every notification it receives, so progress is not reported. Model changes appear only when turned on (see [Timeline](#timeline)).
86
92
  - Native permission IDs, option values, questions and Plan approval retain their meanings. Question auto-resolution is disabled for each owned Server. Workspace hook trust is reviewed through the official CLI; it is not represented as “allow once.”
87
93
  - Each session owns its Server process and environment. Metadata requests use temporary Servers. Closing stdin gives ZCode time to clean up before process termination.
88
94
 
@@ -3,10 +3,12 @@ import { Pressable, Text, View } from "react-native";
3
3
  import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
4
4
  import { AccountTab } from "./account";
5
5
  import { RuntimeTab } from "./runtime";
6
+ import { TimelineTab } from "./timeline";
6
7
 
7
8
  const TABS = [
8
9
  { id: "runtime", label: "Runtime" },
9
10
  { id: "account", label: "Account" },
11
+ { id: "timeline", label: "Timeline" },
10
12
  ] as const;
11
13
  type Tab = (typeof TABS)[number]["id"];
12
14
 
@@ -76,8 +78,10 @@ export function SettingsScreen(props: PluginSurfaceProps) {
76
78
  <Tabs value={tab} onChange={setTab} theme={props.theme} />
77
79
  {tab === "runtime" ? (
78
80
  <RuntimeTab {...props} />
79
- ) : (
81
+ ) : tab === "account" ? (
80
82
  <AccountTab {...props} onOpenRuntime={() => setTab("runtime")} />
83
+ ) : (
84
+ <TimelineTab {...props} />
81
85
  )}
82
86
  </View>
83
87
  );
@@ -0,0 +1,78 @@
1
+ import { useCallback } from "react";
2
+ import { type PluginSurfaceProps, useSettings } from "@getpaseo/plugin/client";
3
+ import {
4
+ SettingsAction,
5
+ SettingsCard,
6
+ SettingsRow,
7
+ SettingsSection,
8
+ SettingsSwitch,
9
+ } from "@getpaseo/plugin/client/ui";
10
+ import { zcodeTimelineSettings } from "../shared/timeline";
11
+ import { Value } from "./value";
12
+
13
+ const LABEL = "Show model changes";
14
+
15
+ export function TimelineTab({ theme, layout }: PluginSurfaceProps) {
16
+ const settings = useSettings(zcodeTimelineSettings);
17
+ const toggle = useCallback(
18
+ (showModelChanges: boolean) => {
19
+ if (settings.status === "ready")
20
+ void settings.save(
21
+ { ...settings.values, showModelChanges },
22
+ settings.revision,
23
+ );
24
+ },
25
+ [settings],
26
+ );
27
+
28
+ if (settings.status === "loading")
29
+ return (
30
+ <SettingsSection title="Timeline">
31
+ <SettingsCard>
32
+ <SettingsRow label={LABEL}>
33
+ <Value
34
+ color={theme.colors.foregroundMuted}
35
+ compact={layout.compact}
36
+ >
37
+ Loading…
38
+ </Value>
39
+ </SettingsRow>
40
+ </SettingsCard>
41
+ </SettingsSection>
42
+ );
43
+ if (settings.status !== "ready")
44
+ return (
45
+ <SettingsSection title="Timeline">
46
+ <SettingsCard>
47
+ <SettingsRow label={LABEL} error={settings.error} />
48
+ <SettingsAction
49
+ label="Try again"
50
+ actionLabel="Reload"
51
+ onPress={() => void settings.reload()}
52
+ />
53
+ {settings.status === "invalid" ? (
54
+ <SettingsAction
55
+ label="Restore the default"
56
+ actionLabel="Reset"
57
+ disabled={settings.saving}
58
+ onPress={() => void settings.reset()}
59
+ />
60
+ ) : null}
61
+ </SettingsCard>
62
+ </SettingsSection>
63
+ );
64
+ return (
65
+ <SettingsSection title="Timeline">
66
+ <SettingsCard>
67
+ <SettingsSwitch
68
+ label={LABEL}
69
+ hint="Adds a line when ZCode runs a turn on a different model than the previous turn. Applies to lines that arrive after the change; reopened agents show their history with the current setting."
70
+ value={settings.values.showModelChanges}
71
+ disabled={settings.saving}
72
+ error={settings.saveError}
73
+ onValueChange={toggle}
74
+ />
75
+ </SettingsCard>
76
+ </SettingsSection>
77
+ );
78
+ }
package/index.server.ts CHANGED
@@ -5,6 +5,7 @@ import { createHost, createZCodeProvider } from "./server/provider.js";
5
5
  import { ManagedRuntimeInstaller } from "./server/runtime/managed.js";
6
6
  import { createRuntimeSetupHandlers } from "./server/runtime-setup.js";
7
7
  import { createDiagnosticsHandler } from "./server/status.js";
8
+ import { followTimelineSettings } from "./server/timeline-settings.js";
8
9
  import { createUsageSource } from "./server/usage.js";
9
10
  import { zcodeAccountChange, zcodeAccountView } from "./shared/account.js";
10
11
  import { zcodeDiagnostics } from "./shared/diagnostics.js";
@@ -13,9 +14,15 @@ import {
13
14
  zcodeRuntimeRemove,
14
15
  zcodeRuntimeStatus,
15
16
  } from "./shared/runtime-setup.js";
17
+ import { zcodeTimelineSettings } from "./shared/timeline.js";
16
18
 
17
19
  export default function contribute(server: PluginServerContext): () => void {
18
- server.registerProvider(createZCodeProvider());
20
+ const timeline = followTimelineSettings(
21
+ server.registerSettings(zcodeTimelineSettings),
22
+ );
23
+ server.registerProvider(
24
+ createZCodeProvider(undefined, undefined, undefined, timeline.current),
25
+ );
19
26
  server.handle(zcodeDiagnostics, createDiagnosticsHandler());
20
27
  const setup = createRuntimeSetupHandlers(new ManagedRuntimeInstaller());
21
28
  server.handle(zcodeRuntimeStatus, setup.status);
@@ -33,6 +40,7 @@ export default function contribute(server: PluginServerContext): () => void {
33
40
  server.registerUsageSource(usage.source);
34
41
  return () => {
35
42
  usage.dispose();
43
+ timeline.dispose();
36
44
  abort.abort();
37
45
  void account.close();
38
46
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-zcode-provider",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "Unofficial Paseo provider plugin for ZCode, using the official stdio Services Server of the integrated ZCode CLI.",
5
5
  "keywords": [
6
6
  "paseo",
package/paseo-plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "zcode-provider",
3
3
  "requirements": {
4
- "paseo": ">=0.8.0"
4
+ "paseo": ">=0.9.0"
5
5
  }
6
6
  }
@@ -1,2 +1,2 @@
1
1
  // Generated from package.json by npm prepare / prebuild.
2
- export const PROVIDER_VERSION = "0.4.2";
2
+ export const PROVIDER_VERSION = "0.4.4";
@@ -15,6 +15,50 @@ const stages = [
15
15
  "notification",
16
16
  "transport",
17
17
  "session",
18
+ "turn",
19
+ ] as const;
20
+ // ZCode's ModelFailureReason (apps/zcode-cli/packages/contracts/src/model/index.ts at 3c5b227).
21
+ export const modelFailureReasons = [
22
+ "rate_limited",
23
+ "provider_overloaded",
24
+ "server_error",
25
+ "network_error",
26
+ "timeout",
27
+ "stream_idle_timeout",
28
+ "stale_connection",
29
+ "auth_refresh",
30
+ "reasoning_signature_repair",
31
+ "offpeak_queued",
32
+ "auth_failed",
33
+ "cancelled",
34
+ "context_exceeded",
35
+ "invalid_request",
36
+ "provider_not_configured",
37
+ "proxy_error",
38
+ "tls_error",
39
+ "unknown",
40
+ ] as const;
41
+ export type ModelFailureReason = (typeof modelFailureReasons)[number];
42
+ // V4 errorAttributionSchema enums.
43
+ const failureSources = ["provider", "runtime", "tool", "network"] as const;
44
+ const errorPhases = [
45
+ "prepare",
46
+ "configuration",
47
+ "connect",
48
+ "response",
49
+ "stream",
50
+ "parse",
51
+ "validation",
52
+ "unhandled",
53
+ ] as const;
54
+ const exceptionKinds = [
55
+ "api_call",
56
+ "generic",
57
+ "protocol",
58
+ "provider_business",
59
+ "transport",
60
+ "type_error",
61
+ "validation",
18
62
  ] as const;
19
63
  const checks = [
20
64
  "bundle-metadata",
@@ -146,6 +190,44 @@ export interface RuntimeDiagnostic {
146
190
  readonly nativeCode?: number;
147
191
  readonly exitCode?: number;
148
192
  readonly validation?: readonly { path: string; code: string }[];
193
+ readonly failure?: TurnFailureDiagnostic;
194
+ }
195
+
196
+ /** Attribution of a failed turn from V4 `control.lastError`; never its message. */
197
+ export interface TurnFailureDiagnostic {
198
+ readonly source?: string;
199
+ readonly reason?: string;
200
+ readonly errorPhase?: string;
201
+ readonly exceptionKind?: string;
202
+ readonly statusCode?: number;
203
+ readonly providerErrorCode?: string;
204
+ readonly retryable?: boolean;
205
+ }
206
+
207
+ export function reportableStatusCode(
208
+ value: number | undefined,
209
+ ): number | undefined {
210
+ return Number.isInteger(value) && value! >= 100 && value! <= 599
211
+ ? value
212
+ : undefined;
213
+ }
214
+
215
+ /** Provider error codes are free text. Only numeric or word codes such as `1310` or `insufficient_quota` are reported. */
216
+ export function reportableProviderErrorCode(
217
+ value: string | undefined,
218
+ ): string | undefined {
219
+ return value &&
220
+ value.length <= 64 &&
221
+ /^(?:\d+|[A-Za-z]+(?:[_.][A-Za-z]+)*)$/u.test(value)
222
+ ? value
223
+ : undefined;
224
+ }
225
+
226
+ function allowed(
227
+ values: readonly string[],
228
+ value: string | undefined,
229
+ ): string | undefined {
230
+ return value !== undefined && values.includes(value) ? value : undefined;
149
231
  }
150
232
 
151
233
  export function runtimeDiagnostic(
@@ -222,6 +304,21 @@ export function formatDiagnostic(error: unknown): string {
222
304
  for (const key of ["nativeCode", "exitCode"] as const) {
223
305
  if (Number.isSafeInteger(context[key])) result[key] = context[key];
224
306
  }
307
+ if (context.failure) {
308
+ const f = context.failure;
309
+ const failure = Object.fromEntries(
310
+ Object.entries({
311
+ source: allowed(failureSources, f.source),
312
+ reason: allowed(modelFailureReasons, f.reason),
313
+ errorPhase: allowed(errorPhases, f.errorPhase),
314
+ exceptionKind: allowed(exceptionKinds, f.exceptionKind),
315
+ statusCode: reportableStatusCode(f.statusCode),
316
+ providerErrorCode: reportableProviderErrorCode(f.providerErrorCode),
317
+ retryable: typeof f.retryable === "boolean" ? f.retryable : undefined,
318
+ }).filter(([, value]) => value !== undefined),
319
+ );
320
+ if (Object.keys(failure).length) result.failure = failure;
321
+ }
225
322
  if (context.validation)
226
323
  result.validation = context.validation.slice(0, 10).map((issue) => ({
227
324
  path: issue.path
package/server/errors.ts CHANGED
@@ -14,6 +14,13 @@ export type ZCodeErrorCode =
14
14
  | "NATIVE_INPUT_REJECTED"
15
15
  | "NATIVE_TIMEOUT"
16
16
  | "NATIVE_EXITED"
17
+ | "NATIVE_TURN_FAILED"
18
+ | "MODEL_RATE_LIMITED"
19
+ | "MODEL_AUTH_FAILED"
20
+ | "MODEL_CONTEXT_EXCEEDED"
21
+ | "MODEL_NETWORK_ERROR"
22
+ | "MODEL_PROVIDER_ERROR"
23
+ | "MODEL_REQUEST_FAILED"
17
24
  | "AUTH_REQUIRED"
18
25
  | "UNSUPPORTED_CONTENT"
19
26
  | "SESSION_NOT_FOUND"
@@ -233,6 +233,8 @@ export function usage(state: ConversationSnapshot): ProviderUsage {
233
233
  export interface PresentedInteraction {
234
234
  request: ProviderPermissionRequest;
235
235
  answer(response: ProviderPermissionResponse): Record<string, unknown>;
236
+ /** Native answer of the first deny action, without interrupting. */
237
+ decline: Record<string, unknown>;
236
238
  }
237
239
  export function presentInteraction(
238
240
  interaction: PendingInteraction,
@@ -262,7 +264,8 @@ export function presentInteraction(
262
264
  variant: behavior === "allow" ? "primary" : "danger",
263
265
  };
264
266
  });
265
- if (!actions.some((a) => a.behavior === "deny"))
267
+ const deny = actions.find((a) => a.behavior === "deny");
268
+ if (!deny)
266
269
  throw new AdapterError(
267
270
  "NATIVE_PROTOCOL_ERROR",
268
271
  "ZCode permission has no deny option",
@@ -299,6 +302,7 @@ export function presentInteraction(
299
302
  );
300
303
  return { optionId: action.id };
301
304
  },
305
+ decline: { optionId: deny.id },
302
306
  };
303
307
  }
304
308
  if (p.sensitive)
@@ -414,6 +418,7 @@ export function presentInteraction(
414
418
  },
415
419
  };
416
420
  },
421
+ decline: { action: "decline" },
417
422
  };
418
423
  }
419
424
  return {
@@ -445,6 +450,7 @@ export function presentInteraction(
445
450
  content: answerContent(record(response.updatedInput?.answers)),
446
451
  };
447
452
  },
453
+ decline: { action: "decline" },
448
454
  };
449
455
  }
450
456
 
@@ -452,8 +458,14 @@ function markerText(marker: TimelineMarkerPayload): string {
452
458
  switch (marker.type) {
453
459
  case "compact":
454
460
  return `Context compaction: ${marker.status}`;
455
- case "modelChange":
456
- return `Model: ${marker.toModel} (${marker.toThought})`;
461
+ case "modelChange": {
462
+ // Worded as in ZCode Desktop, which also omits the reasoning level: it
463
+ // does not count as a model change and may be empty.
464
+ const to = `${marker.toProvider}/${marker.toModel}`;
465
+ return marker.fromProvider === undefined || marker.fromModel === undefined
466
+ ? `Using ${to}`
467
+ : `Model switched ${marker.fromProvider}/${marker.fromModel} → ${to}`;
468
+ }
457
469
  case "forkNotice":
458
470
  return "Conversation continued from a parent conversation.";
459
471
  case "forkCreated":
@@ -52,6 +52,10 @@ import {
52
52
  import { SessionSnapshotSchema, SessionListSchema } from "./host/schemas.js";
53
53
  import { TimelineSnapshots } from "./timeline.js";
54
54
  import type { NativeSessionEvent } from "./session-types.js";
55
+ import {
56
+ defaultTimelinePreferences,
57
+ type TimelinePreferences,
58
+ } from "../shared/timeline.js";
55
59
 
56
60
  export const CAPABILITIES = [
57
61
  "prompt.message",
@@ -117,6 +121,7 @@ export function createZCodeProvider(
117
121
  bridgeFactory: BridgeFactory = createHost,
118
122
  persistenceStore = new SessionPersistenceStore(),
119
123
  status: ProviderRegistration["status"] = createRuntimeStatus(),
124
+ timeline: () => TimelinePreferences = () => defaultTimelinePreferences,
120
125
  ): ProviderRegistration {
121
126
  return {
122
127
  id: "zcode",
@@ -134,6 +139,7 @@ export function createZCodeProvider(
134
139
  negotiateProviderCapabilities(request.capabilities, CAPABILITIES),
135
140
  bridgeFactory,
136
141
  persistenceStore,
142
+ timeline,
137
143
  );
138
144
  },
139
145
  };
@@ -154,6 +160,7 @@ export class ZCodeConnection implements ProviderConnection {
154
160
  readonly capabilities: readonly string[],
155
161
  private readonly bridgeFactory: BridgeFactory,
156
162
  private readonly persistenceStore: SessionPersistenceStore,
163
+ private readonly timeline: () => TimelinePreferences,
157
164
  ) {}
158
165
 
159
166
  onEvent(listener: (event: ProviderEvent) => void): () => void {
@@ -220,7 +227,9 @@ export class ZCodeConnection implements ProviderConnection {
220
227
  if (input.type === "session.prompt") {
221
228
  const promptEntry = entry ?? this.sessions.get(input.sessionId);
222
229
  if (promptEntry?.messages.get(input.prompt.clientMessageId)) return;
223
- promptEntry?.messages.set(input.prompt.clientMessageId, true);
230
+ // The input was not admitted. Paseo's interrupt-and-replace fallback
231
+ // for an unavailable steer resends it with the same ID.
232
+ promptEntry?.messages.delete(input.prompt.clientMessageId);
224
233
  this.emit({
225
234
  type: "session.prompt_result",
226
235
  sessionId: input.sessionId,
@@ -374,11 +383,6 @@ export class ZCodeConnection implements ProviderConnection {
374
383
  switch (input.type) {
375
384
  case "session.prompt": {
376
385
  const prompt = input.prompt.input;
377
- if (input.prompt.clearPendingPermissions)
378
- throw new AdapterError(
379
- "INTERACTION_UNSUPPORTED",
380
- "Steering does not resolve pending ZCode permissions",
381
- );
382
386
  if (input.prompt.delivery === "steer" && !entry.native.hasActiveTurn())
383
387
  throw new AdapterError(
384
388
  "SESSION_BUSY",
@@ -439,6 +443,7 @@ export class ZCodeConnection implements ProviderConnection {
439
443
  {
440
444
  clientMessageId: input.prompt.clientMessageId,
441
445
  delivery: input.prompt.delivery,
446
+ clearPendingPermissions: input.prompt.clearPendingPermissions,
442
447
  beforeSend: async () => {
443
448
  if (!entry.submitted) {
444
449
  await this.persistenceStore.save(
@@ -561,6 +566,7 @@ export class ZCodeConnection implements ProviderConnection {
561
566
  workspace: cwd,
562
567
  snapshot,
563
568
  modelCatalog: selection.models,
569
+ timeline: this.timeline,
564
570
  onClose() {},
565
571
  });
566
572
  if (
@@ -729,7 +735,7 @@ export class ZCodeConnection implements ProviderConnection {
729
735
  state: "failed",
730
736
  error: {
731
737
  code: event.code,
732
- message: "ZCode turn failed",
738
+ message: event.error,
733
739
  diagnostic: event.diagnostic,
734
740
  },
735
741
  });
package/server/session.ts CHANGED
@@ -50,11 +50,15 @@ import type {
50
50
  } from "./session-types.js";
51
51
  import { AdapterError } from "./errors.js";
52
52
  import { diagnosticError, formatDiagnostic } from "./diagnostics.js";
53
+ import { turnFailure } from "./turn-failure.js";
54
+ import type { TimelinePreferences } from "../shared/timeline.js";
53
55
  interface Admission {
54
56
  clientMessageId?: string;
55
57
  accepted: boolean;
56
58
  consumed: boolean;
57
59
  productTurnId?: string;
60
+ /** Paseo's clearPendingPermissions: decline interactions until consumed. */
61
+ releasesInteractions?: boolean;
58
62
  }
59
63
  interface Run {
60
64
  id: string;
@@ -74,6 +78,7 @@ export class ZCodeSession {
74
78
  private readonly seenTurns = new Set<string>();
75
79
  private readonly publicTurns = new Map<string, string>();
76
80
  private readonly presented = new Map<string, NativeTimelineEntry>();
81
+ private readonly omitted = new Set<string>();
77
82
  private readonly pending = new Map<string, PresentedInteraction>();
78
83
  private readonly answering = new Set<string>();
79
84
  private readonly resolvedInteractions = new Set<string>();
@@ -92,6 +97,7 @@ export class ZCodeSession {
92
97
  private readonly workspace: string,
93
98
  private readonly snapshot: SessionSnapshot,
94
99
  private modelCatalog: readonly ModelOption[],
100
+ private readonly timeline: () => TimelinePreferences,
95
101
  private readonly onClose: () => void,
96
102
  ) {
97
103
  assertSnapshotWorkspace(snapshot, workspace);
@@ -106,6 +112,7 @@ export class ZCodeSession {
106
112
  workspace: string;
107
113
  snapshot: SessionSnapshot;
108
114
  modelCatalog: readonly ModelOption[];
115
+ timeline: () => TimelinePreferences;
109
116
  onClose: () => void;
110
117
  }): Promise<ZCodeSession> {
111
118
  const session = new ZCodeSession(
@@ -114,6 +121,7 @@ export class ZCodeSession {
114
121
  options.workspace,
115
122
  options.snapshot,
116
123
  options.modelCatalog,
124
+ options.timeline,
117
125
  options.onClose,
118
126
  );
119
127
  session.unlistenFailure = options.bridge.onFailure((error) =>
@@ -131,7 +139,7 @@ export class ZCodeSession {
131
139
  if (row.kind === "turnHeader")
132
140
  session.seenTurns.add(session.productTurn(row));
133
141
  const item = rowTimeline(row);
134
- if (item)
142
+ if (item && !session.omits(row, item.id))
135
143
  session.presented.set(item.id, {
136
144
  item,
137
145
  timestamp: new Date(row.createdAt).toISOString(),
@@ -166,6 +174,22 @@ export class ZCodeSession {
166
174
  );
167
175
  return row.productTurnId;
168
176
  }
177
+ // The setting decides when a marker is first seen. Paseo keeps the items it
178
+ // has received, and a marker shown after a later change would land at the
179
+ // end of the timeline.
180
+ private omits(row: ConversationRow, id: string): boolean {
181
+ if (
182
+ row.kind !== "timelineMarker" ||
183
+ row.marker.type !== "modelChange" ||
184
+ this.presented.has(id)
185
+ )
186
+ return false;
187
+ if (this.omitted.has(id) || !this.timeline().showModelChanges) {
188
+ this.omitted.add(id);
189
+ return true;
190
+ }
191
+ return false;
192
+ }
169
193
  private newRun(): Run {
170
194
  return {
171
195
  id: randomUUID(),
@@ -221,7 +245,7 @@ export class ZCodeSession {
221
245
  ? this.admissions.get(row.sourceCommandId)?.clientMessageId
222
246
  : undefined;
223
247
  const item = rowTimeline(row, clientMessageId);
224
- if (!item) continue;
248
+ if (!item || this.omits(row, item.id)) continue;
225
249
  const entry = { item, timestamp: new Date(row.createdAt).toISOString() };
226
250
  if (isDeepStrictEqual(entry, this.presented.get(item.id))) continue;
227
251
  this.presented.set(item.id, entry);
@@ -286,6 +310,7 @@ export class ZCodeSession {
286
310
  });
287
311
  }
288
312
  }
313
+ this.releaseInteractions();
289
314
  if (
290
315
  this.state.workspaceHookAdmission ||
291
316
  this.state.pendingInteractions.some(
@@ -323,6 +348,29 @@ export class ZCodeSession {
323
348
  }
324
349
  this.maybeComplete();
325
350
  }
351
+ /**
352
+ * ZCode reads a steer only after every tool call of the model step settles,
353
+ * so a parked turn never reads it. While an accepted steer that asked to clear
354
+ * permissions is unread, decline each pending interaction, including requests
355
+ * opened after an earlier decline.
356
+ */
357
+ private releaseInteractions(): void {
358
+ const run = this.active;
359
+ if (
360
+ !run ||
361
+ run.cancelled ||
362
+ ![...run.inputs.values()].some(
363
+ (i) => i.releasesInteractions && i.accepted && !i.consumed,
364
+ )
365
+ )
366
+ return;
367
+ for (const [id, interaction] of this.pending) {
368
+ if (this.answering.has(id)) continue;
369
+ this.resolveInteraction(id, interaction.decline).catch((error) =>
370
+ this.runtimeFailed(diagnosticError(error, this.bridge.diagnostic)),
371
+ );
372
+ }
373
+ }
326
374
  private maybeComplete(): void {
327
375
  const run = this.active;
328
376
  if (
@@ -352,23 +400,29 @@ export class ZCodeSession {
352
400
  headers.some((h) => h.state === "failed") ||
353
401
  this.state.control.phase === "error";
354
402
  this.active = undefined;
355
- this.emit(
356
- failed
357
- ? {
358
- type: "turn_failed",
359
- turnId: run.id,
360
- error: "ZCode execution failed",
361
- code: "NATIVE_PROTOCOL_ERROR",
362
- }
363
- : {
364
- type:
365
- run.cancelled ||
366
- headers.some((h) => h.state === "completedInterrupted")
367
- ? "turn_canceled"
368
- : "turn_completed",
369
- turnId: run.id,
370
- },
371
- );
403
+ if (failed) {
404
+ // ZCode sets lastError in the frame that fails the turn and clears it
405
+ // when the next turn starts.
406
+ const failure = turnFailure(
407
+ this.state.control.lastError,
408
+ this.bridge.diagnostic,
409
+ );
410
+ this.emit({
411
+ type: "turn_failed",
412
+ turnId: run.id,
413
+ error: failure.message,
414
+ code: failure.code,
415
+ diagnostic: formatDiagnostic(failure),
416
+ });
417
+ } else
418
+ this.emit({
419
+ type:
420
+ run.cancelled ||
421
+ headers.some((h) => h.state === "completedInterrupted")
422
+ ? "turn_canceled"
423
+ : "turn_completed",
424
+ turnId: run.id,
425
+ });
372
426
  this.changed();
373
427
  }
374
428
  private changed(): void {
@@ -537,6 +591,7 @@ export class ZCodeSession {
537
591
  options?: {
538
592
  clientMessageId: string;
539
593
  delivery?: "auto" | "steer";
594
+ clearPendingPermissions?: boolean;
540
595
  beforeSend?: () => Promise<void>;
541
596
  },
542
597
  ): Promise<{ turnId: string }> {
@@ -634,6 +689,7 @@ export class ZCodeSession {
634
689
  );
635
690
  this.assertOpen();
636
691
  input.accepted = true;
692
+ input.releasesInteractions = options?.clearPendingPermissions === true;
637
693
  if (options?.clientMessageId)
638
694
  this.emit({
639
695
  type: "prompt_accepted",
@@ -701,7 +757,12 @@ export class ZCodeSession {
701
757
  "SESSION_NOT_FOUND",
702
758
  "ZCode interaction is no longer pending",
703
759
  );
704
- const answer = pending.answer(response);
760
+ await this.resolveInteraction(id, pending.answer(response));
761
+ }
762
+ private async resolveInteraction(
763
+ id: string,
764
+ answer: Record<string, unknown>,
765
+ ): Promise<void> {
705
766
  this.answering.add(id);
706
767
  try {
707
768
  await this.control("resolveInteraction", { interactionId: id, answer });
@@ -0,0 +1,50 @@
1
+ import type {
2
+ PluginSettings,
3
+ PluginSettingsState,
4
+ } from "@getpaseo/plugin/server";
5
+ import { logger } from "./logger.js";
6
+ import {
7
+ defaultTimelinePreferences,
8
+ type TimelinePreferences,
9
+ type zcodeTimelineSettings,
10
+ } from "../shared/timeline.js";
11
+
12
+ type Schema = (typeof zcodeTimelineSettings)["schema"];
13
+
14
+ /**
15
+ * Follows the saved timeline settings. The defaults apply until the first read
16
+ * completes and while the stored document is invalid.
17
+ */
18
+ export function followTimelineSettings(settings: PluginSettings<Schema>): {
19
+ current: () => TimelinePreferences;
20
+ dispose: () => void;
21
+ } {
22
+ let current = defaultTimelinePreferences,
23
+ changed = false,
24
+ disposed = false;
25
+ const apply = (state: PluginSettingsState<Schema>) => {
26
+ if (disposed) return;
27
+ if (state.status === "invalid")
28
+ logger.log("warn", "zcode.settings.timeline.invalid");
29
+ current =
30
+ state.status === "ready" ? state.values : defaultTimelinePreferences;
31
+ };
32
+ const unsubscribe = settings.subscribe((state) => {
33
+ changed = true;
34
+ apply(state);
35
+ });
36
+ settings.read().then(
37
+ (state) => {
38
+ // A save notified meanwhile is newer than this read.
39
+ if (!changed) apply(state);
40
+ },
41
+ (error: unknown) => logger.error("zcode.settings.timeline.failed", error),
42
+ );
43
+ return {
44
+ current: () => current,
45
+ dispose() {
46
+ disposed = true;
47
+ void unsubscribe();
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,111 @@
1
+ import type { SessionErrorInfo } from "./vendor/zcode/packages/shared/src/zcode-protocol-v4/snapshot.js";
2
+ import { AdapterError, type ZCodeErrorCode } from "./errors.js";
3
+ import {
4
+ modelFailureReasons,
5
+ reportableProviderErrorCode,
6
+ reportableStatusCode,
7
+ type ModelFailureReason,
8
+ type RuntimeDiagnostic,
9
+ } from "./diagnostics.js";
10
+
11
+ type TurnFailureCode = Extract<
12
+ ZCodeErrorCode,
13
+ "NATIVE_TURN_FAILED" | `MODEL_${string}`
14
+ >;
15
+
16
+ // Reasons without an entry fall back to the attribution source.
17
+ const reasonCodes: Partial<Record<ModelFailureReason, TurnFailureCode>> = {
18
+ rate_limited: "MODEL_RATE_LIMITED",
19
+ offpeak_queued: "MODEL_RATE_LIMITED",
20
+ auth_failed: "MODEL_AUTH_FAILED",
21
+ auth_refresh: "MODEL_AUTH_FAILED",
22
+ provider_not_configured: "MODEL_AUTH_FAILED",
23
+ context_exceeded: "MODEL_CONTEXT_EXCEEDED",
24
+ network_error: "MODEL_NETWORK_ERROR",
25
+ timeout: "MODEL_NETWORK_ERROR",
26
+ stream_idle_timeout: "MODEL_NETWORK_ERROR",
27
+ stale_connection: "MODEL_NETWORK_ERROR",
28
+ proxy_error: "MODEL_NETWORK_ERROR",
29
+ tls_error: "MODEL_NETWORK_ERROR",
30
+ server_error: "MODEL_PROVIDER_ERROR",
31
+ provider_overloaded: "MODEL_PROVIDER_ERROR",
32
+ };
33
+
34
+ const messages: Record<
35
+ TurnFailureCode,
36
+ readonly [summary: string, advice?: string]
37
+ > = {
38
+ NATIVE_TURN_FAILED: ["ZCode turn failed"],
39
+ MODEL_RATE_LIMITED: [
40
+ "The model provider's usage or rate limit was reached",
41
+ "Wait for it to reset or switch models. For a ZCode Coding Plan, Paseo 0.11 and later show the reset times on the Usage screen.",
42
+ ],
43
+ MODEL_AUTH_FAILED: [
44
+ "The model provider is not signed in or rejected the credentials",
45
+ "Check the account and model providers in the Account tab of the zcode-provider Settings.",
46
+ ],
47
+ MODEL_CONTEXT_EXCEEDED: [
48
+ "The conversation exceeds the model's context window",
49
+ "Start a new session or switch to a model with a larger context window.",
50
+ ],
51
+ MODEL_NETWORK_ERROR: [
52
+ "ZCode could not reach the model provider",
53
+ "Check the network connection and try again.",
54
+ ],
55
+ MODEL_PROVIDER_ERROR: [
56
+ "The model provider returned a server error or is overloaded",
57
+ "Try again later.",
58
+ ],
59
+ MODEL_REQUEST_FAILED: ["The model provider rejected the request"],
60
+ };
61
+
62
+ /**
63
+ * Classifies a failed turn by the attribution of V4 `control.lastError`
64
+ * (ADR 23). ZCode's message and detail are never used: they can carry
65
+ * provider text, request content or credentials (ADR 7).
66
+ */
67
+ export function turnFailure(
68
+ lastError: SessionErrorInfo | null,
69
+ context: RuntimeDiagnostic,
70
+ ): AdapterError {
71
+ const attribution = lastError?.attribution;
72
+ const source = attribution?.source ?? lastError?.source;
73
+ const reason = modelFailureReasons.find((r) => r === attribution?.reason);
74
+ const code: TurnFailureCode =
75
+ source === "provider" || source === "network"
76
+ ? ((reason && reasonCodes[reason]) ??
77
+ (source === "network" ? "MODEL_NETWORK_ERROR" : "MODEL_REQUEST_FAILED"))
78
+ : "NATIVE_TURN_FAILED";
79
+ const statusCode = reportableStatusCode(attribution?.statusCode);
80
+ const providerErrorCode = reportableProviderErrorCode(
81
+ attribution?.providerErrorCode,
82
+ );
83
+ const facts = [
84
+ ...(statusCode ? [`HTTP ${statusCode}`] : []),
85
+ ...(providerErrorCode ? [`provider code ${providerErrorCode}`] : []),
86
+ ];
87
+ const [summary, advice] = messages[code];
88
+ return new AdapterError(
89
+ code,
90
+ `${summary}${facts.length ? ` (${facts.join(", ")})` : ""}.${advice ? ` ${advice}` : ""}`,
91
+ {},
92
+ undefined,
93
+ {
94
+ ...context,
95
+ stage: "turn",
96
+ ...(lastError
97
+ ? {
98
+ failure: {
99
+ source,
100
+ reason: attribution?.reason,
101
+ errorPhase: attribution?.errorPhase,
102
+ exceptionKind: attribution?.exceptionKind,
103
+ statusCode: attribution?.statusCode,
104
+ providerErrorCode: attribution?.providerErrorCode,
105
+ retryable: attribution?.retryable,
106
+ },
107
+ }
108
+ : {}),
109
+ },
110
+ );
111
+ }
package/server/usage.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- // Types only, from the module every supported Paseo resolves; Paseo 0.8–0.10
2
+ // Types only, from the module every supported Paseo resolves; Paseo 0.9–0.10
3
3
  // reject `@getpaseo/plugin/server/usage` even as a type import.
4
4
  import type {
5
5
  UsageReport,
@@ -0,0 +1,12 @@
1
+ import { defineSettings } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+
4
+ export const zcodeTimelineSettings = defineSettings({
5
+ id: "timeline",
6
+ scope: "host",
7
+ version: 1,
8
+ schema: z.object({ showModelChanges: z.boolean().default(false) }),
9
+ });
10
+ export type TimelinePreferences = z.output<typeof zcodeTimelineSettings.schema>;
11
+ export const defaultTimelinePreferences: TimelinePreferences =
12
+ zcodeTimelineSettings.schema.parse({});