@vaclav-synacek/pi-coding-agent-termux 0.50.7-1 → 0.51.1-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.
Files changed (168) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/dist/cli/args.d.ts.map +1 -1
  3. package/dist/cli/args.js +2 -0
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/cli/session-picker.d.ts.map +1 -1
  6. package/dist/cli/session-picker.js +3 -1
  7. package/dist/cli/session-picker.js.map +1 -1
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/config.js +9 -0
  10. package/dist/config.js.map +1 -1
  11. package/dist/core/agent-session.d.ts +5 -1
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +76 -15
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/extensions/index.d.ts +3 -3
  16. package/dist/core/extensions/index.d.ts.map +1 -1
  17. package/dist/core/extensions/index.js +1 -1
  18. package/dist/core/extensions/index.js.map +1 -1
  19. package/dist/core/extensions/runner.d.ts +19 -1
  20. package/dist/core/extensions/runner.d.ts.map +1 -1
  21. package/dist/core/extensions/runner.js +42 -0
  22. package/dist/core/extensions/runner.js.map +1 -1
  23. package/dist/core/extensions/types.d.ts +88 -6
  24. package/dist/core/extensions/types.d.ts.map +1 -1
  25. package/dist/core/extensions/types.js +4 -1
  26. package/dist/core/extensions/types.js.map +1 -1
  27. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  28. package/dist/core/extensions/wrapper.js +1 -1
  29. package/dist/core/extensions/wrapper.js.map +1 -1
  30. package/dist/core/keybindings.d.ts +1 -1
  31. package/dist/core/keybindings.d.ts.map +1 -1
  32. package/dist/core/keybindings.js +8 -0
  33. package/dist/core/keybindings.js.map +1 -1
  34. package/dist/core/model-registry.d.ts.map +1 -1
  35. package/dist/core/model-registry.js +27 -18
  36. package/dist/core/model-registry.js.map +1 -1
  37. package/dist/core/package-manager.d.ts.map +1 -1
  38. package/dist/core/package-manager.js +11 -9
  39. package/dist/core/package-manager.js.map +1 -1
  40. package/dist/core/resource-loader.d.ts +24 -0
  41. package/dist/core/resource-loader.d.ts.map +1 -1
  42. package/dist/core/resource-loader.js +88 -19
  43. package/dist/core/resource-loader.js.map +1 -1
  44. package/dist/core/sdk.d.ts.map +1 -1
  45. package/dist/core/sdk.js +1 -0
  46. package/dist/core/sdk.js.map +1 -1
  47. package/dist/core/session-manager.d.ts +2 -0
  48. package/dist/core/session-manager.d.ts.map +1 -1
  49. package/dist/core/session-manager.js +2 -0
  50. package/dist/core/session-manager.js.map +1 -1
  51. package/dist/core/settings-manager.d.ts +5 -0
  52. package/dist/core/settings-manager.d.ts.map +1 -1
  53. package/dist/core/settings-manager.js +16 -0
  54. package/dist/core/settings-manager.js.map +1 -1
  55. package/dist/core/skills.d.ts.map +1 -1
  56. package/dist/core/skills.js +1 -0
  57. package/dist/core/skills.js.map +1 -1
  58. package/dist/core/tools/bash.d.ts +11 -0
  59. package/dist/core/tools/bash.d.ts.map +1 -1
  60. package/dist/core/tools/bash.js +18 -3
  61. package/dist/core/tools/bash.js.map +1 -1
  62. package/dist/core/tools/edit.d.ts +2 -0
  63. package/dist/core/tools/edit.d.ts.map +1 -1
  64. package/dist/core/tools/edit.js.map +1 -1
  65. package/dist/core/tools/find.d.ts +2 -0
  66. package/dist/core/tools/find.d.ts.map +1 -1
  67. package/dist/core/tools/find.js.map +1 -1
  68. package/dist/core/tools/grep.d.ts +2 -0
  69. package/dist/core/tools/grep.d.ts.map +1 -1
  70. package/dist/core/tools/grep.js.map +1 -1
  71. package/dist/core/tools/index.d.ts +7 -7
  72. package/dist/core/tools/index.d.ts.map +1 -1
  73. package/dist/core/tools/index.js +5 -5
  74. package/dist/core/tools/index.js.map +1 -1
  75. package/dist/core/tools/ls.d.ts +2 -0
  76. package/dist/core/tools/ls.d.ts.map +1 -1
  77. package/dist/core/tools/ls.js.map +1 -1
  78. package/dist/core/tools/read.d.ts +2 -0
  79. package/dist/core/tools/read.d.ts.map +1 -1
  80. package/dist/core/tools/read.js.map +1 -1
  81. package/dist/core/tools/write.d.ts +2 -0
  82. package/dist/core/tools/write.d.ts.map +1 -1
  83. package/dist/core/tools/write.js.map +1 -1
  84. package/dist/index.d.ts +3 -3
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +1 -1
  87. package/dist/index.js.map +1 -1
  88. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  89. package/dist/modes/interactive/components/custom-message.js +0 -7
  90. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  91. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  92. package/dist/modes/interactive/components/daxnuts.js +1 -1
  93. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  94. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  95. package/dist/modes/interactive/components/scoped-models-selector.js +4 -1
  96. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  97. package/dist/modes/interactive/components/session-selector-search.d.ts +4 -2
  98. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/session-selector-search.js +13 -4
  100. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  101. package/dist/modes/interactive/components/session-selector.d.ts +12 -2
  102. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/session-selector.js +188 -57
  104. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  105. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  106. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/settings-selector.js +12 -0
  108. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  109. package/dist/modes/interactive/components/tree-selector.d.ts +6 -0
  110. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  111. package/dist/modes/interactive/components/tree-selector.js +43 -16
  112. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  113. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  114. package/dist/modes/interactive/interactive-mode.js +24 -15
  115. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  116. package/dist/modes/print-mode.d.ts.map +1 -1
  117. package/dist/modes/print-mode.js +4 -0
  118. package/dist/modes/print-mode.js.map +1 -1
  119. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  120. package/dist/modes/rpc/rpc-mode.js +4 -0
  121. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  122. package/dist/utils/clipboard-image.d.ts.map +1 -1
  123. package/dist/utils/clipboard-image.js +52 -10
  124. package/dist/utils/clipboard-image.js.map +1 -1
  125. package/dist/utils/clipboard-native.d.ts +7 -0
  126. package/dist/utils/clipboard-native.d.ts.map +1 -0
  127. package/dist/utils/clipboard-native.js +14 -0
  128. package/dist/utils/clipboard-native.js.map +1 -0
  129. package/dist/utils/tools-manager.d.ts.map +1 -1
  130. package/dist/utils/tools-manager.js +14 -0
  131. package/dist/utils/tools-manager.js.map +1 -1
  132. package/docs/custom-provider.md +2 -1
  133. package/docs/extensions.md +57 -9
  134. package/docs/keybindings.md +9 -0
  135. package/docs/models.md +43 -14
  136. package/docs/rpc.md +188 -1
  137. package/docs/settings.md +5 -1
  138. package/docs/termux.md +127 -0
  139. package/examples/extensions/README.md +9 -0
  140. package/examples/extensions/antigravity-image-gen.ts +1 -1
  141. package/examples/extensions/bash-spawn-hook.ts +30 -0
  142. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  143. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  144. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  145. package/examples/extensions/custom-provider-qwen-cli/index.ts +345 -0
  146. package/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
  147. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  148. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  149. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  150. package/examples/extensions/dynamic-resources/index.ts +15 -0
  151. package/examples/extensions/hello.ts +1 -1
  152. package/examples/extensions/question.ts +1 -1
  153. package/examples/extensions/questionnaire.ts +1 -1
  154. package/examples/extensions/rpc-demo.ts +124 -0
  155. package/examples/extensions/sandbox/index.ts +1 -1
  156. package/examples/extensions/shutdown-command.ts +2 -2
  157. package/examples/extensions/ssh.ts +4 -4
  158. package/examples/extensions/subagent/index.ts +1 -1
  159. package/examples/extensions/titlebar-spinner.ts +58 -0
  160. package/examples/extensions/todo.ts +1 -1
  161. package/examples/extensions/tool-override.ts +1 -1
  162. package/examples/extensions/truncated-tool.ts +1 -1
  163. package/examples/extensions/with-deps/package-lock.json +2 -2
  164. package/examples/extensions/with-deps/package.json +1 -1
  165. package/examples/rpc-extension-ui.ts +632 -0
  166. package/examples/sdk/06-extensions.ts +1 -1
  167. package/examples/sdk/12-full-control.ts +1 -0
  168. package/package.json +6 -5
package/docs/termux.md ADDED
@@ -0,0 +1,127 @@
1
+ # Termux (Android) Setup
2
+
3
+ Pi runs on Android via [Termux](https://termux.dev/), a terminal emulator and Linux environment for Android.
4
+
5
+ ## Prerequisites
6
+
7
+ 1. Install [Termux](https://github.com/termux/termux-app#installation) from GitHub or F-Droid (not Google Play, that version is deprecated)
8
+ 2. Install [Termux:API](https://github.com/termux/termux-api#installation) from GitHub or F-Droid for clipboard and other device integrations
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ # Update packages
14
+ pkg update && pkg upgrade
15
+
16
+ # Install dependencies
17
+ pkg install nodejs termux-api git
18
+
19
+ # Install pi
20
+ npm install -g @mariozechner/pi-coding-agent
21
+
22
+ # Create config directory
23
+ mkdir -p ~/.pi/agent
24
+
25
+ # Run pi
26
+ pi
27
+ ```
28
+
29
+ ## Clipboard Support
30
+
31
+ Clipboard operations use `termux-clipboard-set` and `termux-clipboard-get` when running in Termux. The Termux:API app must be installed for these to work.
32
+
33
+ Image clipboard is not supported on Termux (the `ctrl+v` image paste feature will not work).
34
+
35
+ ## Example AGENTS.md for Termux
36
+
37
+ Create `~/.pi/agent/AGENTS.md` to help the agent understand the Termux environment:
38
+
39
+ ```markdown
40
+ # Agent Environment: Termux on Android
41
+
42
+ ## Location
43
+ - **OS**: Android (Termux terminal emulator)
44
+ - **Home**: `/data/data/com.termux/files/home`
45
+ - **Prefix**: `/data/data/com.termux/files/usr`
46
+ - **Shared storage**: `/storage/emulated/0` (Downloads, Documents, etc.)
47
+
48
+ ## Opening URLs
49
+ ```bash
50
+ termux-open-url "https://example.com"
51
+ ```
52
+
53
+ ## Opening Files
54
+ ```bash
55
+ termux-open file.pdf # Opens with default app
56
+ termux-open -c image.jpg # Choose app
57
+ ```
58
+
59
+ ## Clipboard
60
+ ```bash
61
+ termux-clipboard-set "text" # Copy
62
+ termux-clipboard-get # Paste
63
+ ```
64
+
65
+ ## Notifications
66
+ ```bash
67
+ termux-notification -t "Title" -c "Content"
68
+ ```
69
+
70
+ ## Device Info
71
+ ```bash
72
+ termux-battery-status # Battery info
73
+ termux-wifi-connectioninfo # WiFi info
74
+ termux-telephony-deviceinfo # Device info
75
+ ```
76
+
77
+ ## Sharing
78
+ ```bash
79
+ termux-share -a send file.txt # Share file
80
+ ```
81
+
82
+ ## Other Useful Commands
83
+ ```bash
84
+ termux-toast "message" # Quick toast popup
85
+ termux-vibrate # Vibrate device
86
+ termux-tts-speak "hello" # Text to speech
87
+ termux-camera-photo out.jpg # Take photo
88
+ ```
89
+
90
+ ## Notes
91
+ - Termux:API app must be installed for `termux-*` commands
92
+ - Use `pkg install termux-api` for the command-line tools
93
+ - Storage permission needed for `/storage/emulated/0` access
94
+ ```
95
+
96
+ ## Limitations
97
+
98
+ - **No image clipboard**: Termux clipboard API only supports text
99
+ - **No native binaries**: Some optional native dependencies (like the clipboard module) are unavailable on Android ARM64 and are skipped during installation
100
+ - **Storage access**: To access files in `/storage/emulated/0` (Downloads, etc.), run `termux-setup-storage` once to grant permissions
101
+
102
+ ## Troubleshooting
103
+
104
+ ### Clipboard not working
105
+
106
+ Ensure both apps are installed:
107
+ 1. Termux (from GitHub or F-Droid)
108
+ 2. Termux:API (from GitHub or F-Droid)
109
+
110
+ Then install the CLI tools:
111
+ ```bash
112
+ pkg install termux-api
113
+ ```
114
+
115
+ ### Permission denied for shared storage
116
+
117
+ Run once to grant storage permissions:
118
+ ```bash
119
+ termux-setup-storage
120
+ ```
121
+
122
+ ### Node.js installation issues
123
+
124
+ If npm fails, try clearing the cache:
125
+ ```bash
126
+ npm cache clean --force
127
+ ```
@@ -53,9 +53,11 @@ cp permission-gate.ts ~/.pi/agent/extensions/
53
53
  | `snake.ts` | Snake game with custom UI, keyboard handling, and session persistence |
54
54
  | `send-user-message.ts` | Demonstrates `pi.sendUserMessage()` for sending user messages from extensions |
55
55
  | `timed-confirm.ts` | Demonstrates AbortSignal for auto-dismissing `ctx.ui.confirm()` and `ctx.ui.select()` dialogs |
56
+ | `rpc-demo.ts` | Exercises all RPC-supported extension UI methods; pair with [`examples/rpc-extension-ui.ts`](../rpc-extension-ui.ts) |
56
57
  | `modal-editor.ts` | Custom vim-like modal editor via `ctx.ui.setEditorComponent()` |
57
58
  | `rainbow-editor.ts` | Animated rainbow text effect via custom editor |
58
59
  | `notify.ts` | Desktop notifications via OSC 777 when agent finishes (Ghostty, iTerm2, WezTerm) |
60
+ | `titlebar-spinner.ts` | Braille spinner animation in terminal title while the agent is working |
59
61
  | `summarize.ts` | Summarize conversation with GPT-5.2 and show in transient UI |
60
62
  | `custom-footer.ts` | Custom footer with git branch and token stats via `ctx.ui.setFooter()` |
61
63
  | `custom-header.ts` | Custom header via `ctx.ui.setHeader()` |
@@ -88,6 +90,12 @@ cp permission-gate.ts ~/.pi/agent/extensions/
88
90
  |-----------|-------------|
89
91
  | `mac-system-theme.ts` | Syncs pi theme with macOS dark/light mode |
90
92
 
93
+ ### Resources
94
+
95
+ | Extension | Description |
96
+ |-----------|-------------|
97
+ | `dynamic-resources/` | Loads skills, prompts, and themes using `resources_discover` |
98
+
91
99
  ### Messages & Communication
92
100
 
93
101
  | Extension | Description |
@@ -108,6 +116,7 @@ cp permission-gate.ts ~/.pi/agent/extensions/
108
116
  |-----------|-------------|
109
117
  | `custom-provider-anthropic/` | Custom Anthropic provider with OAuth support and custom streaming implementation |
110
118
  | `custom-provider-gitlab-duo/` | GitLab Duo provider using pi-ai's built-in Anthropic/OpenAI streaming via proxy |
119
+ | `custom-provider-qwen-cli/` | Qwen CLI provider with OAuth device flow and OpenAI-compatible models |
111
120
 
112
121
  ### External Dependencies
113
122
 
@@ -352,7 +352,7 @@ export default function antigravityImageGen(pi: ExtensionAPI) {
352
352
  description:
353
353
  "Generate an image via Google Antigravity image models. Returns the image as a tool result attachment. Optional saving via save=project|global|custom|none, or PI_IMAGE_SAVE_MODE/PI_IMAGE_SAVE_DIR.",
354
354
  parameters: TOOL_PARAMS,
355
- async execute(_toolCallId, params: ToolParams, onUpdate, ctx, signal) {
355
+ async execute(_toolCallId, params: ToolParams, signal, onUpdate, ctx) {
356
356
  const { accessToken, projectId } = await getCredentials(ctx);
357
357
  const model = params.model || DEFAULT_MODEL;
358
358
  const aspectRatio = params.aspectRatio || DEFAULT_ASPECT_RATIO;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Bash Spawn Hook Example
3
+ *
4
+ * Adjusts command, cwd, and env before execution.
5
+ *
6
+ * Usage:
7
+ * pi -e ./bash-spawn-hook.ts
8
+ */
9
+
10
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
11
+ import { createBashTool } from "@mariozechner/pi-coding-agent";
12
+
13
+ export default function (pi: ExtensionAPI) {
14
+ const cwd = process.cwd();
15
+
16
+ const bashTool = createBashTool(cwd, {
17
+ spawnHook: ({ command, cwd, env }) => ({
18
+ command: `source ~/.profile\n${command}`,
19
+ cwd,
20
+ env: { ...env, PI_SPAWN_HOOK: "1" },
21
+ }),
22
+ });
23
+
24
+ pi.registerTool({
25
+ ...bashTool,
26
+ execute: async (id, params, signal, onUpdate, _ctx) => {
27
+ return bashTool.execute(id, params, signal, onUpdate);
28
+ },
29
+ });
30
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pi-extension-custom-provider",
3
- "version": "1.1.7",
3
+ "version": "1.2.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pi-extension-custom-provider",
9
- "version": "1.1.7",
9
+ "version": "1.2.1",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.52.0"
12
12
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-extension-custom-provider-anthropic",
3
3
  "private": true,
4
- "version": "1.1.7",
4
+ "version": "1.2.1",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "clean": "echo 'nothing to clean'",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-extension-custom-provider-gitlab-duo",
3
3
  "private": true,
4
- "version": "1.1.7",
4
+ "version": "1.2.1",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "clean": "echo 'nothing to clean'",
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Qwen CLI Provider Extension
3
+ *
4
+ * Provides access to Qwen models via OAuth authentication with chat.qwen.ai.
5
+ * Uses device code flow with PKCE for secure browser-based authentication.
6
+ *
7
+ * Usage:
8
+ * pi -e ./packages/coding-agent/examples/extensions/custom-provider-qwen-cli
9
+ * # Then /login qwen-cli, or set QWEN_CLI_API_KEY=...
10
+ */
11
+
12
+ import type { OAuthCredentials, OAuthLoginCallbacks } from "@mariozechner/pi-ai";
13
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
14
+
15
+ // =============================================================================
16
+ // Constants
17
+ // =============================================================================
18
+
19
+ const QWEN_DEVICE_CODE_ENDPOINT = "https://chat.qwen.ai/api/v1/oauth2/device/code";
20
+ const QWEN_TOKEN_ENDPOINT = "https://chat.qwen.ai/api/v1/oauth2/token";
21
+ const QWEN_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56";
22
+ const QWEN_SCOPE = "openid profile email model.completion";
23
+ const QWEN_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
24
+ const QWEN_DEFAULT_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
25
+ const QWEN_POLL_INTERVAL_MS = 2000;
26
+
27
+ // =============================================================================
28
+ // PKCE Helpers
29
+ // =============================================================================
30
+
31
+ async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
32
+ const array = new Uint8Array(32);
33
+ crypto.getRandomValues(array);
34
+ const verifier = btoa(String.fromCharCode(...array))
35
+ .replace(/\+/g, "-")
36
+ .replace(/\//g, "_")
37
+ .replace(/=+$/, "");
38
+
39
+ const encoder = new TextEncoder();
40
+ const data = encoder.encode(verifier);
41
+ const hash = await crypto.subtle.digest("SHA-256", data);
42
+ const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
43
+ .replace(/\+/g, "-")
44
+ .replace(/\//g, "_")
45
+ .replace(/=+$/, "");
46
+
47
+ return { verifier, challenge };
48
+ }
49
+
50
+ // =============================================================================
51
+ // OAuth Implementation
52
+ // =============================================================================
53
+
54
+ interface DeviceCodeResponse {
55
+ device_code: string;
56
+ user_code: string;
57
+ verification_uri: string;
58
+ verification_uri_complete?: string;
59
+ expires_in: number;
60
+ interval?: number;
61
+ }
62
+
63
+ interface TokenResponse {
64
+ access_token: string;
65
+ refresh_token?: string;
66
+ token_type: string;
67
+ expires_in: number;
68
+ resource_url?: string;
69
+ }
70
+
71
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
72
+ return new Promise((resolve, reject) => {
73
+ if (signal?.aborted) {
74
+ reject(new Error("Login cancelled"));
75
+ return;
76
+ }
77
+ const timeout = setTimeout(resolve, ms);
78
+ signal?.addEventListener(
79
+ "abort",
80
+ () => {
81
+ clearTimeout(timeout);
82
+ reject(new Error("Login cancelled"));
83
+ },
84
+ { once: true },
85
+ );
86
+ });
87
+ }
88
+
89
+ async function startDeviceFlow(): Promise<{ deviceCode: DeviceCodeResponse; verifier: string }> {
90
+ const { verifier, challenge } = await generatePKCE();
91
+
92
+ const body = new URLSearchParams({
93
+ client_id: QWEN_CLIENT_ID,
94
+ scope: QWEN_SCOPE,
95
+ code_challenge: challenge,
96
+ code_challenge_method: "S256",
97
+ });
98
+
99
+ const headers: Record<string, string> = {
100
+ "Content-Type": "application/x-www-form-urlencoded",
101
+ Accept: "application/json",
102
+ };
103
+ const requestId = globalThis.crypto?.randomUUID?.();
104
+ if (requestId) headers["x-request-id"] = requestId;
105
+
106
+ const response = await fetch(QWEN_DEVICE_CODE_ENDPOINT, {
107
+ method: "POST",
108
+ headers,
109
+ body: body.toString(),
110
+ });
111
+
112
+ if (!response.ok) {
113
+ const text = await response.text();
114
+ throw new Error(`Device code request failed: ${response.status} ${text}`);
115
+ }
116
+
117
+ const data = (await response.json()) as DeviceCodeResponse;
118
+
119
+ if (!data.device_code || !data.user_code || !data.verification_uri) {
120
+ throw new Error("Invalid device code response: missing required fields");
121
+ }
122
+
123
+ return { deviceCode: data, verifier };
124
+ }
125
+
126
+ async function pollForToken(
127
+ deviceCode: string,
128
+ verifier: string,
129
+ intervalSeconds: number | undefined,
130
+ expiresIn: number,
131
+ signal?: AbortSignal,
132
+ ): Promise<TokenResponse> {
133
+ const deadline = Date.now() + expiresIn * 1000;
134
+ const resolvedIntervalSeconds =
135
+ typeof intervalSeconds === "number" && Number.isFinite(intervalSeconds) && intervalSeconds > 0
136
+ ? intervalSeconds
137
+ : QWEN_POLL_INTERVAL_MS / 1000;
138
+ let intervalMs = Math.max(1000, Math.floor(resolvedIntervalSeconds * 1000));
139
+
140
+ const handleTokenError = async (error: string, description?: string): Promise<boolean> => {
141
+ switch (error) {
142
+ case "authorization_pending":
143
+ await abortableSleep(intervalMs, signal);
144
+ return true;
145
+ case "slow_down":
146
+ intervalMs = Math.min(intervalMs + 5000, 10000);
147
+ await abortableSleep(intervalMs, signal);
148
+ return true;
149
+ case "expired_token":
150
+ throw new Error("Device code expired. Please restart authentication.");
151
+ case "access_denied":
152
+ throw new Error("Authorization denied by user.");
153
+ default:
154
+ throw new Error(`Token request failed: ${error} - ${description || ""}`);
155
+ }
156
+ };
157
+
158
+ while (Date.now() < deadline) {
159
+ if (signal?.aborted) {
160
+ throw new Error("Login cancelled");
161
+ }
162
+
163
+ const body = new URLSearchParams({
164
+ grant_type: QWEN_GRANT_TYPE,
165
+ client_id: QWEN_CLIENT_ID,
166
+ device_code: deviceCode,
167
+ code_verifier: verifier,
168
+ });
169
+
170
+ const response = await fetch(QWEN_TOKEN_ENDPOINT, {
171
+ method: "POST",
172
+ headers: {
173
+ "Content-Type": "application/x-www-form-urlencoded",
174
+ Accept: "application/json",
175
+ },
176
+ body: body.toString(),
177
+ });
178
+
179
+ const responseText = await response.text();
180
+ let data: (TokenResponse & { error?: string; error_description?: string }) | null = null;
181
+ if (responseText) {
182
+ try {
183
+ data = JSON.parse(responseText) as TokenResponse & { error?: string; error_description?: string };
184
+ } catch {
185
+ data = null;
186
+ }
187
+ }
188
+
189
+ const error = data?.error;
190
+ const errorDescription = data?.error_description;
191
+
192
+ if (!response.ok) {
193
+ if (error && (await handleTokenError(error, errorDescription))) {
194
+ continue;
195
+ }
196
+ throw new Error(`Token request failed: ${response.status} ${response.statusText}. Response: ${responseText}`);
197
+ }
198
+
199
+ if (data?.access_token) {
200
+ return data;
201
+ }
202
+
203
+ if (error && (await handleTokenError(error, errorDescription))) {
204
+ continue;
205
+ }
206
+
207
+ throw new Error("Token request failed: missing access token in response");
208
+ }
209
+
210
+ throw new Error("Authentication timed out. Please try again.");
211
+ }
212
+
213
+ async function loginQwen(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
214
+ const { deviceCode, verifier } = await startDeviceFlow();
215
+
216
+ // Show verification URL and user code to user
217
+ const authUrl = deviceCode.verification_uri_complete || deviceCode.verification_uri;
218
+ const instructions = deviceCode.verification_uri_complete
219
+ ? undefined // Code is already embedded in the URL
220
+ : `Enter code: ${deviceCode.user_code}`;
221
+ callbacks.onAuth({ url: authUrl, instructions });
222
+
223
+ // Poll for token
224
+ const tokenResponse = await pollForToken(
225
+ deviceCode.device_code,
226
+ verifier,
227
+ deviceCode.interval,
228
+ deviceCode.expires_in,
229
+ callbacks.signal,
230
+ );
231
+
232
+ // Calculate expiry with 5-minute buffer
233
+ const expiresAt = Date.now() + tokenResponse.expires_in * 1000 - 5 * 60 * 1000;
234
+
235
+ return {
236
+ refresh: tokenResponse.refresh_token || "",
237
+ access: tokenResponse.access_token,
238
+ expires: expiresAt,
239
+ // Store resource_url for API base URL if provided
240
+ enterpriseUrl: tokenResponse.resource_url,
241
+ };
242
+ }
243
+
244
+ async function refreshQwenToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
245
+ const body = new URLSearchParams({
246
+ grant_type: "refresh_token",
247
+ refresh_token: credentials.refresh,
248
+ client_id: QWEN_CLIENT_ID,
249
+ });
250
+
251
+ const response = await fetch(QWEN_TOKEN_ENDPOINT, {
252
+ method: "POST",
253
+ headers: {
254
+ "Content-Type": "application/x-www-form-urlencoded",
255
+ Accept: "application/json",
256
+ },
257
+ body: body.toString(),
258
+ });
259
+
260
+ if (!response.ok) {
261
+ const text = await response.text();
262
+ throw new Error(`Token refresh failed: ${response.status} ${text}`);
263
+ }
264
+
265
+ const data = (await response.json()) as TokenResponse;
266
+
267
+ if (!data.access_token) {
268
+ throw new Error("Token refresh failed: no access token in response");
269
+ }
270
+
271
+ const expiresAt = Date.now() + data.expires_in * 1000 - 5 * 60 * 1000;
272
+
273
+ return {
274
+ refresh: data.refresh_token || credentials.refresh,
275
+ access: data.access_token,
276
+ expires: expiresAt,
277
+ enterpriseUrl: data.resource_url ?? credentials.enterpriseUrl,
278
+ };
279
+ }
280
+
281
+ function getQwenBaseUrl(resourceUrl?: string): string {
282
+ if (!resourceUrl) {
283
+ return QWEN_DEFAULT_BASE_URL;
284
+ }
285
+
286
+ let url = resourceUrl.startsWith("http") ? resourceUrl : `https://${resourceUrl}`;
287
+ if (!url.endsWith("/v1")) {
288
+ url = `${url}/v1`;
289
+ }
290
+ return url;
291
+ }
292
+
293
+ // =============================================================================
294
+ // Extension Entry Point
295
+ // =============================================================================
296
+
297
+ export default function (pi: ExtensionAPI) {
298
+ pi.registerProvider("qwen-cli", {
299
+ baseUrl: QWEN_DEFAULT_BASE_URL,
300
+ apiKey: "QWEN_CLI_API_KEY",
301
+ api: "openai-completions",
302
+
303
+ models: [
304
+ {
305
+ id: "qwen3-coder-plus",
306
+ name: "Qwen3 Coder Plus",
307
+ reasoning: false,
308
+ input: ["text"],
309
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
310
+ contextWindow: 1000000,
311
+ maxTokens: 65536,
312
+ },
313
+ {
314
+ id: "qwen3-coder-flash",
315
+ name: "Qwen3 Coder Flash",
316
+ reasoning: false,
317
+ input: ["text"],
318
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
319
+ contextWindow: 1000000,
320
+ maxTokens: 65536,
321
+ },
322
+ {
323
+ id: "vision-model",
324
+ name: "Qwen3 VL Plus",
325
+ reasoning: true,
326
+ input: ["text", "image"],
327
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
328
+ contextWindow: 262144,
329
+ maxTokens: 32768,
330
+ compat: { supportsDeveloperRole: false, thinkingFormat: "qwen" },
331
+ },
332
+ ],
333
+
334
+ oauth: {
335
+ name: "Qwen CLI",
336
+ login: loginQwen,
337
+ refreshToken: refreshQwenToken,
338
+ getApiKey: (cred) => cred.access,
339
+ modifyModels: (models, cred) => {
340
+ const baseUrl = getQwenBaseUrl(cred.enterpriseUrl as string | undefined);
341
+ return models.map((m) => (m.provider === "qwen-cli" ? { ...m, baseUrl } : m));
342
+ },
343
+ },
344
+ });
345
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "pi-extension-custom-provider-qwen-cli",
3
+ "private": true,
4
+ "version": "1.1.1",
5
+ "type": "module",
6
+ "scripts": {
7
+ "clean": "echo 'nothing to clean'",
8
+ "build": "echo 'nothing to build'",
9
+ "check": "echo 'nothing to check'"
10
+ },
11
+ "pi": {
12
+ "extensions": [
13
+ "./index.ts"
14
+ ]
15
+ }
16
+ }
@@ -0,0 +1,8 @@
1
+ ---
2
+ name: dynamic-resources
3
+ description: Example skill loaded from resources_discover
4
+ ---
5
+
6
+ # Dynamic Resources Skill
7
+
8
+ This skill is provided by the dynamic-resources extension.
@@ -0,0 +1,79 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
3
+ "name": "dynamic-resources",
4
+ "vars": {
5
+ "cyan": "#00d7ff",
6
+ "blue": "#5f87ff",
7
+ "green": "#b5bd68",
8
+ "red": "#cc6666",
9
+ "yellow": "#ffff00",
10
+ "gray": "#808080",
11
+ "dimGray": "#666666",
12
+ "darkGray": "#505050",
13
+ "accent": "#8abeb7",
14
+ "selectedBg": "#3a3a4a",
15
+ "userMsgBg": "#343541",
16
+ "toolPendingBg": "#282832",
17
+ "toolSuccessBg": "#283228",
18
+ "toolErrorBg": "#3c2828",
19
+ "customMsgBg": "#2d2838"
20
+ },
21
+ "colors": {
22
+ "accent": "accent",
23
+ "border": "blue",
24
+ "borderAccent": "cyan",
25
+ "borderMuted": "darkGray",
26
+ "success": "green",
27
+ "error": "red",
28
+ "warning": "yellow",
29
+ "muted": "gray",
30
+ "dim": "dimGray",
31
+ "text": "",
32
+ "thinkingText": "gray",
33
+ "selectedBg": "selectedBg",
34
+ "userMessageBg": "userMsgBg",
35
+ "userMessageText": "",
36
+ "customMessageBg": "customMsgBg",
37
+ "customMessageText": "",
38
+ "customMessageLabel": "#9575cd",
39
+ "toolPendingBg": "toolPendingBg",
40
+ "toolSuccessBg": "toolSuccessBg",
41
+ "toolErrorBg": "toolErrorBg",
42
+ "toolTitle": "",
43
+ "toolOutput": "gray",
44
+ "mdHeading": "#f0c674",
45
+ "mdLink": "#81a2be",
46
+ "mdLinkUrl": "dimGray",
47
+ "mdCode": "accent",
48
+ "mdCodeBlock": "green",
49
+ "mdCodeBlockBorder": "gray",
50
+ "mdQuote": "gray",
51
+ "mdQuoteBorder": "gray",
52
+ "mdHr": "gray",
53
+ "mdListBullet": "accent",
54
+ "toolDiffAdded": "green",
55
+ "toolDiffRemoved": "red",
56
+ "toolDiffContext": "gray",
57
+ "syntaxComment": "#6A9955",
58
+ "syntaxKeyword": "#569CD6",
59
+ "syntaxFunction": "#DCDCAA",
60
+ "syntaxVariable": "#9CDCFE",
61
+ "syntaxString": "#CE9178",
62
+ "syntaxNumber": "#B5CEA8",
63
+ "syntaxType": "#4EC9B0",
64
+ "syntaxOperator": "#D4D4D4",
65
+ "syntaxPunctuation": "#D4D4D4",
66
+ "thinkingOff": "darkGray",
67
+ "thinkingMinimal": "#6e6e6e",
68
+ "thinkingLow": "#5f87af",
69
+ "thinkingMedium": "#81a2be",
70
+ "thinkingHigh": "#b294bb",
71
+ "thinkingXhigh": "#d183e8",
72
+ "bashMode": "green"
73
+ },
74
+ "export": {
75
+ "pageBg": "#18181e",
76
+ "cardBg": "#1e1e24",
77
+ "infoBg": "#3c3728"
78
+ }
79
+ }
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Example prompt template loaded from resources_discover
3
+ ---
4
+
5
+ Summarize the current repository structure and mention any build or test commands.