opencode-qwen-cli-auth 1.0.2 → 1.0.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.
Files changed (48) hide show
  1. package/dist/index.d.ts +20 -20
  2. package/dist/index.js +166 -180
  3. package/dist/lib/prompts/fallback/opencode-qwen-prompt.txt +109 -0
  4. package/dist/lib/prompts/opencode-qwen.d.ts +14 -0
  5. package/dist/lib/prompts/opencode-qwen.d.ts.map +1 -0
  6. package/dist/lib/prompts/opencode-qwen.js +121 -0
  7. package/dist/lib/prompts/opencode-qwen.js.map +1 -0
  8. package/dist/lib/prompts/qwen-code.d.ts +25 -0
  9. package/dist/lib/prompts/qwen-code.d.ts.map +1 -0
  10. package/dist/lib/prompts/qwen-code.js +307 -0
  11. package/dist/lib/prompts/qwen-code.js.map +1 -0
  12. package/dist/lib/prompts/qwen-opencode-bridge.d.ts +15 -0
  13. package/dist/lib/prompts/qwen-opencode-bridge.d.ts.map +1 -0
  14. package/dist/lib/prompts/qwen-opencode-bridge.js +81 -0
  15. package/dist/lib/prompts/qwen-opencode-bridge.js.map +1 -0
  16. package/dist/lib/request/fetch-helpers.d.ts +19 -0
  17. package/dist/lib/request/fetch-helpers.d.ts.map +1 -0
  18. package/dist/lib/request/fetch-helpers.js +50 -0
  19. package/dist/lib/request/fetch-helpers.js.map +1 -0
  20. package/dist/lib/request/header-utils.d.ts +38 -0
  21. package/dist/lib/request/header-utils.d.ts.map +1 -0
  22. package/dist/lib/request/header-utils.js +75 -0
  23. package/dist/lib/request/header-utils.js.map +1 -0
  24. package/dist/lib/request/openai-chunk-builder.d.ts +68 -0
  25. package/dist/lib/request/openai-chunk-builder.d.ts.map +1 -0
  26. package/dist/lib/request/openai-chunk-builder.js +110 -0
  27. package/dist/lib/request/openai-chunk-builder.js.map +1 -0
  28. package/dist/lib/request/payload-analyzer.d.ts +34 -0
  29. package/dist/lib/request/payload-analyzer.d.ts.map +1 -0
  30. package/dist/lib/request/payload-analyzer.js +114 -0
  31. package/dist/lib/request/payload-analyzer.js.map +1 -0
  32. package/dist/lib/request/request-transformer.d.ts +39 -0
  33. package/dist/lib/request/request-transformer.d.ts.map +1 -0
  34. package/dist/lib/request/request-transformer.js +108 -0
  35. package/dist/lib/request/request-transformer.js.map +1 -0
  36. package/dist/lib/request/response-handler.d.ts +15 -0
  37. package/dist/lib/request/response-handler.d.ts.map +1 -0
  38. package/dist/lib/request/response-handler.js +90 -0
  39. package/dist/lib/request/response-handler.js.map +1 -0
  40. package/dist/lib/request/sse-parser.d.ts +36 -0
  41. package/dist/lib/request/sse-parser.d.ts.map +1 -0
  42. package/dist/lib/request/sse-parser.js +85 -0
  43. package/dist/lib/request/sse-parser.js.map +1 -0
  44. package/dist/lib/request/stream-normalizer.d.ts +18 -0
  45. package/dist/lib/request/stream-normalizer.d.ts.map +1 -0
  46. package/dist/lib/request/stream-normalizer.js +140 -0
  47. package/dist/lib/request/stream-normalizer.js.map +1 -0
  48. package/package.json +66 -66
package/dist/index.d.ts CHANGED
@@ -1,21 +1,21 @@
1
- /**
2
- * Alibaba Qwen OAuth Authentication Plugin for opencode
3
- *
4
- * @license MIT with Usage Disclaimer (see LICENSE file)
5
- * @repository https://github.com/TVD-00/opencode-qwen-cli-auth
6
- */
7
- import type { Plugin } from "@opencode-ai/plugin";
8
- /**
9
- * Alibaba Qwen OAuth authentication plugin for opencode
10
- *
11
- * @example
12
- * ```json
13
- * {
14
- * "plugin": ["opencode-qwen-cli-auth"],
15
- * "model": "alibaba/coder-model"
16
- * }
17
- * ```
18
- */
19
- export declare const QwenAuthPlugin: Plugin;
20
- export default QwenAuthPlugin;
1
+ /**
2
+ * Alibaba Qwen OAuth Authentication Plugin for opencode
3
+ *
4
+ * @license MIT with Usage Disclaimer (see LICENSE file)
5
+ * @repository https://github.com/TVD-00/opencode-qwen-cli-auth
6
+ */
7
+ import type { Plugin } from "@opencode-ai/plugin";
8
+ /**
9
+ * Alibaba Qwen OAuth authentication plugin for opencode
10
+ *
11
+ * @example
12
+ * ```json
13
+ * {
14
+ * "plugin": ["opencode-alibaba-qwen-cli-auth"],
15
+ * "model": "alibaba/coder-model"
16
+ * }
17
+ * ```
18
+ */
19
+ export declare const QwenAuthPlugin: Plugin;
20
+ export default QwenAuthPlugin;
21
21
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,181 +1,167 @@
1
- /**
2
- * Alibaba Qwen OAuth Authentication Plugin for opencode
3
- *
4
- * Plugin don gian: chi xu ly OAuth login + tra apiKey/baseURL cho SDK.
5
- * SDK tu xu ly streaming, headers, request format.
6
- *
7
- * @license MIT with Usage Disclaimer (see LICENSE file)
8
- * @repository https://github.com/TVD-00/opencode-qwen-cli-auth
9
- */
10
- import { createPKCE, requestDeviceCode, pollForToken, getApiBaseUrl, saveToken, refreshAccessToken, loadStoredToken } from "./lib/auth/auth.js";
11
- import { PROVIDER_ID, AUTH_LABELS, DEVICE_FLOW } from "./lib/constants.js";
12
- import { logError, logInfo, LOGGING_ENABLED } from "./lib/logger.js";
13
- /**
14
- * Lay access token hop le tu SDK auth state, refresh neu het han
15
- * Dung getAuth() cua SDK thay vi doc file truc tiep
16
- *
17
- * @param getAuth - Ham lay auth state tu SDK
18
- * @returns access token hoac null
19
- */
20
- async function getValidAccessToken(getAuth) {
21
- const auth = await getAuth();
22
- if (!auth || auth.type !== "oauth") {
23
- return null;
24
- }
25
- let accessToken = auth.access;
26
- // Refresh neu het han (buffer 60 giay)
27
- if (accessToken && auth.expires && Date.now() > auth.expires - 60000 && auth.refresh) {
28
- try {
29
- const refreshResult = await refreshAccessToken(auth.refresh);
30
- if (refreshResult.type === "success") {
31
- accessToken = refreshResult.access;
32
- saveToken(refreshResult);
33
- }
34
- else {
35
- if (LOGGING_ENABLED) {
36
- logError("Token refresh failed");
37
- }
38
- accessToken = undefined;
39
- }
40
- }
41
- catch (e) {
42
- if (LOGGING_ENABLED) {
43
- logError("Token refresh error:", e);
44
- }
45
- accessToken = undefined;
46
- }
47
- }
48
- return accessToken ?? null;
49
- }
50
- /**
51
- * Lay base URL tu token luu tren disk (resource_url)
52
- * Fallback ve portal.qwen.ai/v1 neu khong co
53
- */
54
- function getBaseUrl() {
55
- try {
56
- const stored = loadStoredToken();
57
- if (stored?.resource_url) {
58
- return getApiBaseUrl(stored.resource_url);
59
- }
60
- }
61
- catch (_) {
62
- // Loi doc file, dung default
63
- }
64
- return getApiBaseUrl();
65
- }
66
- /**
67
- * Alibaba Qwen OAuth authentication plugin for opencode
68
- *
69
- * @example
70
- * ```json
71
- * {
72
- * "plugin": ["opencode-qwen-cli-auth"],
73
- * "model": "alibaba/coder-model"
74
- * }
75
- * ```
76
- */
77
- export const QwenAuthPlugin = async (_input) => {
78
- return {
79
- auth: {
80
- provider: PROVIDER_ID,
81
- /**
82
- * Loader: lay token + base URL, tra ve cho SDK
83
- * Khong can custom fetch - SDK tu xu ly streaming va headers
84
- */
85
- async loader(getAuth, provider) {
86
- const auth = await getAuth();
87
- // Chi xu ly OAuth, bo qua API key auth
88
- if (auth.type !== "oauth") {
89
- return {};
90
- }
91
- const accessToken = await getValidAccessToken(getAuth);
92
- if (!accessToken) {
93
- return null;
94
- }
95
- const baseUrl = getBaseUrl();
96
- // Tra ve apiKey + baseURL, SDK tu xu ly phan con lai
97
- return {
98
- apiKey: accessToken,
99
- baseURL: baseUrl,
100
- };
101
- },
102
- methods: [
103
- {
104
- label: AUTH_LABELS.OAUTH,
105
- type: "oauth",
106
- /**
107
- * Device Authorization Grant OAuth flow (RFC 8628)
108
- */
109
- authorize: async () => {
110
- // Generate PKCE
111
- const pkce = await createPKCE();
112
- // Request device code
113
- const deviceAuth = await requestDeviceCode(pkce);
114
- if (!deviceAuth) {
115
- throw new Error("Failed to request device code");
116
- }
117
- // Hien thi user code
118
- console.log(`\nPlease visit: ${deviceAuth.verification_uri}`);
119
- console.log(`And enter code: ${deviceAuth.user_code}\n`);
120
- // URL xac thuc - SDK se tu mo browser khi method=auto
121
- const verificationUrl = deviceAuth.verification_uri_complete || deviceAuth.verification_uri;
122
- return {
123
- url: verificationUrl,
124
- method: "auto",
125
- instructions: AUTH_LABELS.INSTRUCTIONS,
126
- callback: async () => {
127
- // Poll for token
128
- let pollInterval = (deviceAuth.interval || 5) * 1000;
129
- const POLLING_MARGIN_MS = 3000;
130
- const maxInterval = DEVICE_FLOW.MAX_POLL_INTERVAL;
131
- const startTime = Date.now();
132
- const expiresIn = deviceAuth.expires_in * 1000;
133
- while (Date.now() - startTime < expiresIn) {
134
- await new Promise(resolve => setTimeout(resolve, pollInterval + POLLING_MARGIN_MS));
135
- const result = await pollForToken(deviceAuth.device_code, pkce.verifier);
136
- if (result.type === "success") {
137
- saveToken(result);
138
- // Tra ve cho SDK luu auth state
139
- return {
140
- type: "success",
141
- access: result.access,
142
- refresh: result.refresh,
143
- expires: result.expires,
144
- };
145
- }
146
- if (result.type === "slow_down") {
147
- pollInterval = Math.min(pollInterval + 5000, maxInterval);
148
- continue;
149
- }
150
- if (result.type === "pending") {
151
- continue;
152
- }
153
- // denied, expired, failed -> dung lai
154
- return { type: "failed" };
155
- }
156
- console.error("[qwen-oauth-plugin] Device authorization timed out");
157
- return { type: "failed" };
158
- },
159
- };
160
- },
161
- },
162
- ],
163
- },
164
- /**
165
- * Them header X-DashScope-AuthType cho Portal API (OAuth)
166
- * CLI goc gui header nay de server nhan biet auth method
167
- */
168
- "chat.headers": async (input, output) => {
169
- try {
170
- if (input?.provider?.info?.id === PROVIDER_ID && output?.headers) {
171
- output.headers["X-DashScope-AuthType"] = "qwen-oauth";
172
- }
173
- }
174
- catch (_) {
175
- // Khong de loi hook lam treo request
176
- }
177
- },
178
- };
179
- };
180
- export default QwenAuthPlugin;
1
+ /**
2
+ * Alibaba Qwen OAuth Authentication Plugin for opencode
3
+ *
4
+ * Plugin don gian: chi xu ly OAuth login + tra apiKey/baseURL cho SDK.
5
+ * SDK tu xu ly streaming, headers, request format.
6
+ *
7
+ * @license MIT with Usage Disclaimer (see LICENSE file)
8
+ * @repository https://github.com/TVD-00/opencode-qwen-cli-auth
9
+ */
10
+ import { createPKCE, requestDeviceCode, pollForToken, getApiBaseUrl, saveToken, refreshAccessToken, loadStoredToken } from "./lib/auth/auth.js";
11
+ import { PROVIDER_ID, AUTH_LABELS, DEVICE_FLOW } from "./lib/constants.js";
12
+ import { logError, logInfo, LOGGING_ENABLED } from "./lib/logger.js";
13
+ /**
14
+ * Lay access token hop le tu SDK auth state, refresh neu het han
15
+ * Dung getAuth() cua SDK thay vi doc file truc tiep
16
+ *
17
+ * @param getAuth - Ham lay auth state tu SDK
18
+ * @returns access token hoac null
19
+ */
20
+ async function getValidAccessToken(getAuth) {
21
+ const auth = await getAuth();
22
+ if (!auth || auth.type !== "oauth") {
23
+ return null;
24
+ }
25
+ let accessToken = auth.access;
26
+ // Refresh neu het han (buffer 60 giay)
27
+ if (accessToken && auth.expires && Date.now() > auth.expires - 60000 && auth.refresh) {
28
+ try {
29
+ const refreshResult = await refreshAccessToken(auth.refresh);
30
+ if (refreshResult.type === "success") {
31
+ accessToken = refreshResult.access;
32
+ saveToken(refreshResult);
33
+ }
34
+ else {
35
+ if (LOGGING_ENABLED) {
36
+ logError("Token refresh failed");
37
+ }
38
+ accessToken = undefined;
39
+ }
40
+ }
41
+ catch (e) {
42
+ if (LOGGING_ENABLED) {
43
+ logError("Token refresh error:", e);
44
+ }
45
+ accessToken = undefined;
46
+ }
47
+ }
48
+ return accessToken ?? null;
49
+ }
50
+ /**
51
+ * Lay base URL tu token luu tren disk (resource_url)
52
+ * Fallback ve portal.qwen.ai/v1 neu khong co
53
+ */
54
+ function getBaseUrl() {
55
+ try {
56
+ const stored = loadStoredToken();
57
+ if (stored?.resource_url) {
58
+ return getApiBaseUrl(stored.resource_url);
59
+ }
60
+ }
61
+ catch (_) {
62
+ // Loi doc file, dung default
63
+ }
64
+ return getApiBaseUrl();
65
+ }
66
+ /**
67
+ * Alibaba Qwen OAuth authentication plugin for opencode
68
+ *
69
+ * @example
70
+ * ```json
71
+ * {
72
+ * "plugin": ["opencode-alibaba-qwen-cli-auth"],
73
+ * "model": "alibaba/coder-model"
74
+ * }
75
+ * ```
76
+ */
77
+ export const QwenAuthPlugin = async (_input) => {
78
+ return {
79
+ auth: {
80
+ provider: PROVIDER_ID,
81
+ /**
82
+ * Loader: lay token + base URL, tra ve cho SDK
83
+ * Khong can custom fetch - SDK tu xu ly streaming va headers
84
+ */
85
+ async loader(getAuth, provider) {
86
+ const auth = await getAuth();
87
+ // Chi xu ly OAuth, bo qua API key auth
88
+ if (auth.type !== "oauth") {
89
+ return {};
90
+ }
91
+ const accessToken = await getValidAccessToken(getAuth);
92
+ if (!accessToken) {
93
+ return null;
94
+ }
95
+ const baseUrl = getBaseUrl();
96
+ // Tra ve apiKey + baseURL, SDK tu xu ly phan con lai
97
+ return {
98
+ apiKey: accessToken,
99
+ baseURL: baseUrl,
100
+ };
101
+ },
102
+ methods: [
103
+ {
104
+ label: AUTH_LABELS.OAUTH,
105
+ type: "oauth",
106
+ /**
107
+ * Device Authorization Grant OAuth flow (RFC 8628)
108
+ */
109
+ authorize: async () => {
110
+ // Generate PKCE
111
+ const pkce = await createPKCE();
112
+ // Request device code
113
+ const deviceAuth = await requestDeviceCode(pkce);
114
+ if (!deviceAuth) {
115
+ throw new Error("Failed to request device code");
116
+ }
117
+ // Hien thi user code
118
+ console.log(`\nPlease visit: ${deviceAuth.verification_uri}`);
119
+ console.log(`And enter code: ${deviceAuth.user_code}\n`);
120
+ // URL xac thuc - SDK se tu mo browser khi method=auto
121
+ const verificationUrl = deviceAuth.verification_uri_complete || deviceAuth.verification_uri;
122
+ return {
123
+ url: verificationUrl,
124
+ method: "auto",
125
+ instructions: AUTH_LABELS.INSTRUCTIONS,
126
+ callback: async () => {
127
+ // Poll for token
128
+ let pollInterval = (deviceAuth.interval || 5) * 1000;
129
+ const POLLING_MARGIN_MS = 3000;
130
+ const maxInterval = DEVICE_FLOW.MAX_POLL_INTERVAL;
131
+ const startTime = Date.now();
132
+ const expiresIn = deviceAuth.expires_in * 1000;
133
+ while (Date.now() - startTime < expiresIn) {
134
+ await new Promise(resolve => setTimeout(resolve, pollInterval + POLLING_MARGIN_MS));
135
+ const result = await pollForToken(deviceAuth.device_code, pkce.verifier);
136
+ if (result.type === "success") {
137
+ saveToken(result);
138
+ // Tra ve cho SDK luu auth state
139
+ return {
140
+ type: "success",
141
+ access: result.access,
142
+ refresh: result.refresh,
143
+ expires: result.expires,
144
+ };
145
+ }
146
+ if (result.type === "slow_down") {
147
+ pollInterval = Math.min(pollInterval + 5000, maxInterval);
148
+ continue;
149
+ }
150
+ if (result.type === "pending") {
151
+ continue;
152
+ }
153
+ // denied, expired, failed -> dung lai
154
+ return { type: "failed" };
155
+ }
156
+ console.error("[qwen-oauth-plugin] Device authorization timed out");
157
+ return { type: "failed" };
158
+ },
159
+ };
160
+ },
161
+ },
162
+ ],
163
+ },
164
+ };
165
+ };
166
+ export default QwenAuthPlugin;
181
167
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,109 @@
1
+ You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
2
+
3
+ IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
4
+ IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
5
+ IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
6
+
7
+ If the user asks for help or wants to give feedback inform them of the following:
8
+ - /help: Get help with using opencode
9
+ - To give feedback, users should report the issue at https://github.com/sst/opencode/issues
10
+
11
+ When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
12
+
13
+ # Tone and style
14
+ You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
15
+ Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
16
+ Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
17
+ If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
18
+ Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
19
+ IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
20
+ IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
21
+ IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
22
+ <example>
23
+ user: 2 + 2
24
+ assistant: 4
25
+ </example>
26
+
27
+ <example>
28
+ user: what is 2+2?
29
+ assistant: 4
30
+ </example>
31
+
32
+ <example>
33
+ user: is 11 a prime number?
34
+ assistant: Yes
35
+ </example>
36
+
37
+ <example>
38
+ user: what command should I run to list files in the current directory?
39
+ assistant: ls
40
+ </example>
41
+
42
+ <example>
43
+ user: what command should I run to watch files in the current directory?
44
+ assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
45
+ npm run dev
46
+ </example>
47
+
48
+ <example>
49
+ user: How many golf balls fit inside a jetta?
50
+ assistant: 150000
51
+ </example>
52
+
53
+ <example>
54
+ user: what files are in the directory src/?
55
+ assistant: [runs ls and sees foo.c, bar.c, baz.c]
56
+ user: which file contains the implementation of foo?
57
+ assistant: src/foo.c
58
+ </example>
59
+
60
+ <example>
61
+ user: write tests for new feature
62
+ assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
63
+ </example>
64
+
65
+ # Proactiveness
66
+ You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
67
+ 1. Doing the right thing when asked, including taking actions and follow-up actions
68
+ 2. Not surprising the user with actions you take without asking
69
+ For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
70
+ 3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
71
+
72
+ # Following conventions
73
+ When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
74
+ - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
75
+ - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
76
+ - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
77
+ - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
78
+
79
+ # Code style
80
+ - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
81
+
82
+ # Doing tasks
83
+ The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
84
+ - Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
85
+ - Implement the solution using all tools available to you
86
+ - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
87
+ - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
88
+ NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
89
+
90
+ - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
91
+
92
+ # Tool usage policy
93
+ - When doing file search, prefer to use the Task tool in order to reduce context usage.
94
+ - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
95
+
96
+ You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
97
+
98
+ IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
99
+ IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
100
+
101
+ # Code References
102
+
103
+ When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
104
+
105
+ <example>
106
+ user: Where are errors from the client handled?
107
+ assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
108
+ </example>
109
+
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Fetch OpenCode qwen.txt prompt from GitHub with ETag caching
3
+ * @returns OpenCode qwen.txt content
4
+ */
5
+ export declare function getOpenCodeQwenPrompt(): Promise<string>;
6
+ /**
7
+ * Check if message content matches OpenCode qwen.txt prompt
8
+ * Used for filtering in QWEN_MODE
9
+ * @param content - Message content to check
10
+ * @param qwenPrompt - OpenCode qwen.txt content
11
+ * @returns True if content matches OpenCode prompt
12
+ */
13
+ export declare function isOpenCodeQwenPrompt(content: string, qwenPrompt: string): boolean;
14
+ //# sourceMappingURL=opencode-qwen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opencode-qwen.d.ts","sourceRoot":"","sources":["../../../lib/prompts/opencode-qwen.ts"],"names":[],"mappings":"AAoCA;;;GAGG;AACH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,CAkF7D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAcjF"}
@@ -0,0 +1,121 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
+ import { getCacheDir } from "../config.js";
3
+ import { join } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { dirname } from "path";
6
+ // Get the directory of the current module for loading the fallback file
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ /**
10
+ * Load the bundled OpenCode qwen.txt fallback
11
+ * This is used when GitHub is unavailable and no cache exists
12
+ */
13
+ function loadBundledFallback() {
14
+ const fallbackPath = join(__dirname, "fallback", "opencode-qwen-prompt.txt");
15
+ return readFileSync(fallbackPath, "utf-8");
16
+ }
17
+ /**
18
+ * OpenCode qwen.txt prompt URL
19
+ */
20
+ const OPENCODE_QWEN_URL = "https://raw.githubusercontent.com/sst/opencode/dev/packages/opencode/src/session/prompt/qwen.txt";
21
+ /**
22
+ * Cache paths
23
+ */
24
+ const CACHE_FILE = "opencode-qwen.txt";
25
+ const META_FILE = "opencode-qwen-meta.json";
26
+ /**
27
+ * Fetch OpenCode qwen.txt prompt from GitHub with ETag caching
28
+ * @returns OpenCode qwen.txt content
29
+ */
30
+ export async function getOpenCodeQwenPrompt() {
31
+ const cacheDir = getCacheDir();
32
+ const cachePath = join(cacheDir, CACHE_FILE);
33
+ const metaPath = join(cacheDir, META_FILE);
34
+ // Ensure cache directory exists
35
+ if (!existsSync(cacheDir)) {
36
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
37
+ }
38
+ // Load cached metadata
39
+ let metadata = null;
40
+ if (existsSync(metaPath)) {
41
+ try {
42
+ const content = readFileSync(metaPath, "utf-8");
43
+ metadata = JSON.parse(content);
44
+ }
45
+ catch {
46
+ // Ignore invalid metadata
47
+ }
48
+ }
49
+ // Fetch with ETag
50
+ const headers = {};
51
+ if (metadata?.etag) {
52
+ headers["If-None-Match"] = metadata.etag;
53
+ }
54
+ try {
55
+ const res = await fetch(OPENCODE_QWEN_URL, { headers });
56
+ // 304 Not Modified - use cache
57
+ if (res.status === 304 && existsSync(cachePath)) {
58
+ const cached = readFileSync(cachePath, "utf-8");
59
+ // Update last checked time
60
+ if (metadata) {
61
+ metadata.lastChecked = Date.now();
62
+ writeFileSync(metaPath, JSON.stringify(metadata, null, 2), "utf-8");
63
+ }
64
+ return cached;
65
+ }
66
+ // 200 OK - update cache
67
+ if (res.ok) {
68
+ const content = await res.text();
69
+ const etag = res.headers.get("etag");
70
+ // Save content
71
+ writeFileSync(cachePath, content, "utf-8");
72
+ // Save metadata
73
+ const newMetadata = {
74
+ etag,
75
+ lastChecked: Date.now(),
76
+ url: OPENCODE_QWEN_URL,
77
+ };
78
+ writeFileSync(metaPath, JSON.stringify(newMetadata, null, 2), "utf-8");
79
+ return content;
80
+ }
81
+ // Fetch failed - use cache if available
82
+ if (existsSync(cachePath)) {
83
+ console.warn("[qwen-oauth-plugin] Failed to fetch OpenCode qwen.txt (status: " + res.status + "), using cache");
84
+ return readFileSync(cachePath, "utf-8");
85
+ }
86
+ // No cache available - use bundled fallback
87
+ console.warn("[qwen-oauth-plugin] No cache available, using bundled fallback for OpenCode qwen.txt");
88
+ return loadBundledFallback();
89
+ }
90
+ catch (error) {
91
+ // Network error - use cache if available
92
+ if (existsSync(cachePath)) {
93
+ console.warn("[qwen-oauth-plugin] Network error fetching OpenCode qwen.txt, using cache");
94
+ return readFileSync(cachePath, "utf-8");
95
+ }
96
+ // No cache available - use bundled fallback as last resort
97
+ console.warn("[qwen-oauth-plugin] Network error and no cache, using bundled fallback for OpenCode qwen.txt");
98
+ return loadBundledFallback();
99
+ }
100
+ }
101
+ /**
102
+ * Check if message content matches OpenCode qwen.txt prompt
103
+ * Used for filtering in QWEN_MODE
104
+ * @param content - Message content to check
105
+ * @param qwenPrompt - OpenCode qwen.txt content
106
+ * @returns True if content matches OpenCode prompt
107
+ */
108
+ export function isOpenCodeQwenPrompt(content, qwenPrompt) {
109
+ // Exact match
110
+ if (content === qwenPrompt) {
111
+ return true;
112
+ }
113
+ // Fuzzy match - check for signature phrases
114
+ const signatures = [
115
+ "You are opencode, an interactive CLI tool",
116
+ "IMPORTANT: Refuse to write code or explain code that may be used maliciously",
117
+ "When the user directly asks about opencode",
118
+ ];
119
+ return signatures.every(sig => content.includes(sig));
120
+ }
121
+ //# sourceMappingURL=opencode-qwen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opencode-qwen.js","sourceRoot":"","sources":["../../../lib/prompts/opencode-qwen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,wEAAwE;AACxE,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEtC;;;GAGG;AACH,SAA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