opencode-copilot-account-switcher 0.1.1 → 0.1.3

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/LICENSE CHANGED
@@ -1,21 +1,151 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 jiwangyihao
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Mozilla Public License Version 2.0
2
+
3
+ 1. Definitions
4
+
5
+ 1.1. "Contributor"
6
+ means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
7
+
8
+ 1.2. "Contributor Version"
9
+ means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution.
10
+
11
+ 1.3. "Contribution"
12
+ means Covered Software of a particular Contributor.
13
+
14
+ 1.4. "Covered Software"
15
+ means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
16
+
17
+ 1.5. "Incompatible With Secondary Licenses"
18
+ means
19
+
20
+ that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
21
+ that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
22
+
23
+ 1.6. "Executable Form"
24
+ means any form of the work other than Source Code Form.
25
+
26
+ 1.7. "Larger Work"
27
+ means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
28
+
29
+ 1.8. "License"
30
+ means this document.
31
+
32
+ 1.9. "Licensable"
33
+ means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
34
+
35
+ 1.10. "Modifications"
36
+ means any of the following:
37
+
38
+ any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
39
+ any new file in Source Code Form that contains any Covered Software.
40
+
41
+ 1.11. "Patent Claims" of a Contributor
42
+ means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
43
+
44
+ 1.12. "Secondary License"
45
+ means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
46
+
47
+ 1.13. "Source Code Form"
48
+ means the form of the work preferred for making modifications.
49
+
50
+ 1.14. "You" (or "Your")
51
+ means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
52
+
53
+ 2. License Grants and Conditions
54
+
55
+ 2.1. Grants
56
+ Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
57
+
58
+ under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
59
+ under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
60
+
61
+ 2.2. Effective Date
62
+ The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.
63
+
64
+ 2.3. Limitations on Grant Scope
65
+ The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:
66
+
67
+ for any code that a Contributor has removed from Covered Software; or
68
+ for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
69
+ under Patent Claims infringed by Covered Software in the absence of its Contributions.
70
+
71
+ This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).
72
+
73
+ 2.4. Subsequent Licenses
74
+ No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).
75
+
76
+ 2.5. Representation
77
+ Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.
78
+
79
+ 2.6. Fair Use
80
+ This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.
81
+
82
+ 2.7. Conditions
83
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
84
+
85
+ 3. Responsibilities
86
+
87
+ 3.1. Distribution of Source Form
88
+ All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form.
89
+
90
+ 3.2. Distribution of Executable Form
91
+ If You distribute Covered Software in Executable Form then:
92
+
93
+ such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
94
+ You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License.
95
+
96
+ 3.3. Distribution of a Larger Work
97
+ You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).
98
+
99
+ 3.4. Notices
100
+ You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.
101
+
102
+ 3.5. Application of Additional Terms
103
+ You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
104
+
105
+ 4. Inability to Comply Due to Statute or Regulation
106
+ If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
107
+
108
+ 5. Termination
109
+
110
+ 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
111
+
112
+ 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
113
+
114
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
115
+
116
+ 6. Disclaimer of Warranty
117
+ Covered Software is provided under this License on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
118
+
119
+ 7. Limitation of Liability
120
+ Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
121
+
122
+ 8. Litigation
123
+ Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims.
124
+
125
+ 9. Miscellaneous
126
+ This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
127
+
128
+ 10. Versions of the License
129
+
130
+ 10.1. New Versions
131
+ Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
132
+
133
+ 10.2. Effect of New Versions
134
+ You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
135
+
136
+ 10.3. Modified Versions
137
+ If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).
138
+
139
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
140
+ If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
141
+
142
+ Exhibit A - Source Code Form License Notice
143
+
144
+ This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
145
+
146
+ If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
147
+ You may add additional accurate notices of copyright ownership.
148
+
149
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
150
+
151
+ This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/opencode-copilot-account-switcher.svg)](https://www.npmjs.com/package/opencode-copilot-account-switcher)
4
4
  [![npm downloads](https://img.shields.io/npm/dw/opencode-copilot-account-switcher.svg)](https://www.npmjs.com/package/opencode-copilot-account-switcher)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+ [![License: MPL-2.0](https://img.shields.io/badge/License-MPL--2.0-brightgreen.svg)](LICENSE)
6
6
 
7
7
  [English](#english) | [中文](#中文)
8
8
 
@@ -12,13 +12,14 @@
12
12
 
13
13
  ## English
14
14
 
15
- Manage and switch between multiple **GitHub Copilot** accounts in **OpenCode**. This plugin only adds account switching and quota checks — it **uses the official `github-copilot` provider** and does **not** require model reconfiguration.
15
+ Manage and switch between multiple **GitHub Copilot** accounts in **OpenCode**. This plugin adds account switching, quota checks, and an optional **Guided Loop Safety** mode — it **uses the official `github-copilot` provider** and does **not** require model reconfiguration.
16
16
 
17
17
  ## What You Get
18
18
 
19
19
  - **Multi-account support** — add multiple Copilot accounts and switch anytime
20
20
  - **Quota check** — view remaining quota per account
21
21
  - **Auth import** — import Copilot tokens from OpenCode auth storage
22
+ - **Guided Loop Safety** — inject a stricter question-first Copilot policy with fewer report interruptions and fewer unnecessary subagent calls
22
23
  - **Zero model config** — no model changes required (official provider only)
23
24
 
24
25
  ---
@@ -52,7 +53,7 @@ Install the opencode-copilot-account-switcher plugin by following: https://raw.g
52
53
  3. **Login** to GitHub Copilot:
53
54
 
54
55
  ```bash
55
- opencode auth login github-copilot
56
+ opencode auth login --provider github-copilot
56
57
  ```
57
58
 
58
59
  </details>
@@ -80,7 +81,7 @@ Install the opencode-copilot-account-switcher plugin by following: https://raw.g
80
81
  ### Verification
81
82
 
82
83
  ```bash
83
- opencode auth login github-copilot
84
+ opencode auth login --provider github-copilot
84
85
  ```
85
86
 
86
87
  </details>
@@ -92,7 +93,7 @@ opencode auth login github-copilot
92
93
  Run inside the GitHub Copilot auth flow:
93
94
 
94
95
  ```bash
95
- opencode auth login github-copilot
96
+ opencode auth login --provider github-copilot
96
97
  ```
97
98
 
98
99
  You will see an interactive menu (arrow keys + enter) with actions:
@@ -100,10 +101,13 @@ You will see an interactive menu (arrow keys + enter) with actions:
100
101
  - **Add account**
101
102
  - **Import from auth.json**
102
103
  - **Check quotas**
104
+ - **Guided Loop Safety** — prompt-guided question-first reporting that requires `question` for user-facing reports when available, reduces report interruptions, and avoids unnecessary subagent calls
103
105
  - **Switch account**
104
106
  - **Remove account**
105
107
  - **Remove all**
106
108
 
109
+ If you want stricter question-first reporting and fewer unnecessary subagent calls in GitHub Copilot sessions, enable Guided Loop Safety from the account menu.
110
+
107
111
  ---
108
112
 
109
113
  ## Storage
@@ -130,13 +134,14 @@ No. It uses the official provider and only adds account switching + quota checks
130
134
 
131
135
  ## 中文
132
136
 
133
- 在 **OpenCode** 中管理并切换多个 **GitHub Copilot** 账号。本插件只提供**账号切换与配额查询**,**完全依赖官方 `github-copilot` provider**,无需修改模型配置。
137
+ 在 **OpenCode** 中管理并切换多个 **GitHub Copilot** 账号。本插件提供**账号切换、配额查询**以及可选的 **Guided Loop Safety** 模式,**完全依赖官方 `github-copilot` provider**,无需修改模型配置。
134
138
 
135
139
  ## 功能一览
136
140
 
137
141
  - **多账号管理** — 添加多个 Copilot 账号,随时切换
138
142
  - **配额查询** — 查看每个账号的剩余额度
139
143
  - **导入认证** — 可从 OpenCode 认证存储导入
144
+ - **Guided Loop Safety** — 为 Copilot 注入更严格的 question-first 提示词规则,减少汇报打断,并避免不必要的子代理调用
140
145
  - **无需模型配置** — 使用官方 provider,无需改模型
141
146
 
142
147
  ---
@@ -170,7 +175,7 @@ No. It uses the official provider and only adds account switching + quota checks
170
175
  3. **登录 GitHub Copilot**:
171
176
 
172
177
  ```bash
173
- opencode auth login github-copilot
178
+ opencode auth login --provider github-copilot
174
179
  ```
175
180
 
176
181
  </details>
@@ -198,7 +203,7 @@ No. It uses the official provider and only adds account switching + quota checks
198
203
  ### 验证
199
204
 
200
205
  ```bash
201
- opencode auth login github-copilot
206
+ opencode auth login --provider github-copilot
202
207
  ```
203
208
 
204
209
  </details>
@@ -210,7 +215,7 @@ opencode auth login github-copilot
210
215
  在 Copilot 认证流程中运行:
211
216
 
212
217
  ```bash
213
- opencode auth login github-copilot
218
+ opencode auth login --provider github-copilot
214
219
  ```
215
220
 
216
221
  会出现交互式菜单(方向键 + 回车):
@@ -218,10 +223,13 @@ opencode auth login github-copilot
218
223
  - **添加账号**
219
224
  - **从 auth.json 导入**
220
225
  - **检查配额**
226
+ - **Guided Loop Safety 开关** — 通过提示词引导模型在可用时必须使用 `question` 做用户可见汇报、减少汇报打断,并避免不必要的子代理调用
221
227
  - **切换账号**
222
228
  - **删除账号**
223
229
  - **全部删除**
224
230
 
231
+ 如果你希望 GitHub Copilot 会话更严格地优先使用 `question` 工具汇报、减少汇报打断,并避免不必要的子代理调用,可以在账号菜单中开启 Guided Loop Safety。
232
+
225
233
  ---
226
234
 
227
235
  ## 存储位置
@@ -246,4 +254,4 @@ opencode auth login github-copilot
246
254
 
247
255
  ## License
248
256
 
249
- MIT License. See [LICENSE](LICENSE) for details.
257
+ MPL-2.0 License. See [LICENSE](LICENSE) for details.
package/dist/index.d.ts CHANGED
@@ -1 +1,3 @@
1
- export { CopilotAccountSwitcher } from "./plugin";
1
+ export { CopilotAccountSwitcher } from "./plugin.js";
2
+ export { applyMenuAction } from "./plugin-actions.js";
3
+ export { buildPluginHooks } from "./plugin-hooks.js";
package/dist/index.js CHANGED
@@ -1 +1,3 @@
1
- export { CopilotAccountSwitcher } from "./plugin";
1
+ export { CopilotAccountSwitcher } from "./plugin.js";
2
+ export { applyMenuAction } from "./plugin-actions.js";
3
+ export { buildPluginHooks } from "./plugin-hooks.js";
@@ -0,0 +1,21 @@
1
+ import type { Hooks } from "@opencode-ai/plugin";
2
+ import { type StoreFile } from "./store.js";
3
+ export declare const LOOP_SAFETY_POLICY = "Guided Loop Safety Policy\n- When the question tool is available and permitted in the current session, all user-facing reports must be delivered through the question tool.\n- The question tool is considered available and permitted when it appears in the active tool list and the current session has not denied its use.\n- Direct assistant text is allowed only when the question tool is unavailable, denied, or absent from the current session.\n- When reporting multiple related items, prefer a single question tool call with multiple well-grouped questions instead of multiple separate interruptions.\n- Group related items into clear question batches such as current progress, key findings, and next-step choices.\n- For long or complex reports, split the report into paginated or sequential question batches instead of overloading one large message.\n- Present the highest-priority information first and defer secondary details to later question batches when needed.\n- Even when no explicit decision is required, prefer brief question-tool status updates over direct assistant text whenever the tool is available.\n- Avoid unnecessary question frequency; combine small related updates when a single question call can cover them clearly.\n- Dispatching task or subagent work is expensive and should be avoided unless it materially improves the result.\n- Materially improves the result means clearly beneficial cases such as parallel analysis of independent areas; it does not include routine local searches, small file reads, or straightforward edits.\n- If task or subagent delegation is used, keep the number minimal and explain the reason briefly through the question tool when available.";
4
+ export type ExperimentalChatSystemTransformHook = (input: {
5
+ sessionID: string;
6
+ model: {
7
+ providerID: string;
8
+ };
9
+ }, output: {
10
+ system: string[];
11
+ }) => Promise<void>;
12
+ export type CopilotPluginHooks = Hooks & {
13
+ "experimental.chat.system.transform"?: ExperimentalChatSystemTransformHook;
14
+ };
15
+ export declare function isCopilotProvider(providerID: string): boolean;
16
+ export declare function applyLoopSafetyPolicy(input: {
17
+ providerID: string;
18
+ enabled: boolean;
19
+ system: string[];
20
+ }): string[];
21
+ export declare function createLoopSafetySystemTransform(loadStore?: () => Promise<StoreFile | undefined>): ExperimentalChatSystemTransformHook;
@@ -0,0 +1,39 @@
1
+ import { readStoreSafe } from "./store.js";
2
+ export const LOOP_SAFETY_POLICY = `Guided Loop Safety Policy
3
+ - When the question tool is available and permitted in the current session, all user-facing reports must be delivered through the question tool.
4
+ - The question tool is considered available and permitted when it appears in the active tool list and the current session has not denied its use.
5
+ - Direct assistant text is allowed only when the question tool is unavailable, denied, or absent from the current session.
6
+ - When reporting multiple related items, prefer a single question tool call with multiple well-grouped questions instead of multiple separate interruptions.
7
+ - Group related items into clear question batches such as current progress, key findings, and next-step choices.
8
+ - For long or complex reports, split the report into paginated or sequential question batches instead of overloading one large message.
9
+ - Present the highest-priority information first and defer secondary details to later question batches when needed.
10
+ - Even when no explicit decision is required, prefer brief question-tool status updates over direct assistant text whenever the tool is available.
11
+ - Avoid unnecessary question frequency; combine small related updates when a single question call can cover them clearly.
12
+ - Dispatching task or subagent work is expensive and should be avoided unless it materially improves the result.
13
+ - Materially improves the result means clearly beneficial cases such as parallel analysis of independent areas; it does not include routine local searches, small file reads, or straightforward edits.
14
+ - If task or subagent delegation is used, keep the number minimal and explain the reason briefly through the question tool when available.`;
15
+ export function isCopilotProvider(providerID) {
16
+ return providerID === "github-copilot" || providerID === "github-copilot-enterprise";
17
+ }
18
+ export function applyLoopSafetyPolicy(input) {
19
+ if (!input.enabled)
20
+ return input.system;
21
+ if (!isCopilotProvider(input.providerID))
22
+ return input.system;
23
+ if (input.system.includes(LOOP_SAFETY_POLICY))
24
+ return input.system;
25
+ return [...input.system, LOOP_SAFETY_POLICY];
26
+ }
27
+ export function createLoopSafetySystemTransform(loadStore = readStoreSafe) {
28
+ return async (input, output) => {
29
+ const store = await loadStore().catch(() => undefined);
30
+ const next = applyLoopSafetyPolicy({
31
+ providerID: input.model.providerID,
32
+ enabled: store?.loopSafetyEnabled === true,
33
+ system: output.system,
34
+ });
35
+ if (next.length === output.system.length)
36
+ return;
37
+ output.system.push(LOOP_SAFETY_POLICY);
38
+ };
39
+ }
@@ -0,0 +1,7 @@
1
+ import type { StoreFile } from "./store.js";
2
+ import type { MenuAction } from "./ui/menu.js";
3
+ export declare function applyMenuAction(input: {
4
+ action: MenuAction;
5
+ store: StoreFile;
6
+ writeStore: (store: StoreFile) => Promise<void>;
7
+ }): Promise<boolean>;
@@ -0,0 +1,7 @@
1
+ export async function applyMenuAction(input) {
2
+ if (input.action.type !== "toggle-loop-safety")
3
+ return false;
4
+ input.store.loopSafetyEnabled = input.store.loopSafetyEnabled !== true;
5
+ await input.writeStore(input.store);
6
+ return true;
7
+ }
@@ -0,0 +1,6 @@
1
+ import { type CopilotPluginHooks } from "./loop-safety-plugin.js";
2
+ import { type StoreFile } from "./store.js";
3
+ export declare function buildPluginHooks(input: {
4
+ auth: CopilotPluginHooks["auth"];
5
+ loadStore?: () => Promise<StoreFile | undefined>;
6
+ }): CopilotPluginHooks;
@@ -0,0 +1,8 @@
1
+ import { createLoopSafetySystemTransform } from "./loop-safety-plugin.js";
2
+ import { readStoreSafe } from "./store.js";
3
+ export function buildPluginHooks(input) {
4
+ return {
5
+ auth: input.auth,
6
+ "experimental.chat.system.transform": createLoopSafetySystemTransform(input.loadStore ?? readStoreSafe),
7
+ };
8
+ }
package/dist/plugin.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { stdin as input, stdout as output } from "node:process";
3
- import { isTTY } from "./ui/ansi";
4
- import { showAccountActions, showMenu } from "./ui/menu";
5
- import { authPath, readAuth, readStore, writeStore } from "./store";
3
+ import { applyMenuAction } from "./plugin-actions.js";
4
+ import { buildPluginHooks } from "./plugin-hooks.js";
5
+ import { isTTY } from "./ui/ansi.js";
6
+ import { showAccountActions, showMenu } from "./ui/menu.js";
7
+ import { authPath, readAuth, readStore, writeStore } from "./store.js";
6
8
  function now() {
7
9
  return Date.now();
8
10
  }
@@ -442,6 +444,32 @@ async function switchAccount(client, entry) {
442
444
  });
443
445
  }
444
446
  export const CopilotAccountSwitcher = async ({ client }) => {
447
+ const methods = [
448
+ {
449
+ type: "oauth",
450
+ label: "Manage GitHub Copilot accounts",
451
+ async authorize() {
452
+ const entry = await runMenu();
453
+ return {
454
+ url: "",
455
+ instructions: "",
456
+ method: "auto",
457
+ async callback() {
458
+ if (!entry)
459
+ return { type: "failed" };
460
+ return {
461
+ type: "success",
462
+ provider: entry.enterpriseUrl ? "github-copilot-enterprise" : "github-copilot",
463
+ refresh: entry.refresh,
464
+ access: entry.access,
465
+ expires: entry.expires,
466
+ ...(entry.enterpriseUrl ? { enterpriseUrl: entry.enterpriseUrl } : {}),
467
+ };
468
+ },
469
+ };
470
+ },
471
+ },
472
+ ];
445
473
  async function runMenu() {
446
474
  const store = await readStore();
447
475
  const auth = await readAuth().catch(() => ({}));
@@ -533,11 +561,14 @@ export const CopilotAccountSwitcher = async ({ client }) => {
533
561
  : undefined,
534
562
  }));
535
563
  const refresh = { enabled: store.autoRefresh === true, minutes: store.refreshMinutes ?? 15 };
536
- const action = await showMenu(accounts, refresh, store.lastQuotaRefresh);
564
+ const action = await showMenu(accounts, refresh, store.lastQuotaRefresh, store.loopSafetyEnabled === true);
537
565
  if (action.type === "cancel") {
538
566
  const active = store.active ? store.accounts[store.active] : undefined;
539
567
  return active;
540
568
  }
569
+ if (await applyMenuAction({ action, store, writeStore })) {
570
+ continue;
571
+ }
541
572
  if (action.type === "add") {
542
573
  const mode = await promptText("Add via device login? (y/n): ");
543
574
  const useDevice = mode.toLowerCase() === "y" || mode.toLowerCase() === "yes";
@@ -673,35 +704,10 @@ export const CopilotAccountSwitcher = async ({ client }) => {
673
704
  }
674
705
  }
675
706
  }
676
- return {
707
+ return buildPluginHooks({
677
708
  auth: {
678
709
  provider: "github-copilot",
679
- methods: [
680
- {
681
- type: "oauth",
682
- label: "Manage GitHub Copilot accounts",
683
- async authorize() {
684
- const entry = await runMenu();
685
- return {
686
- url: "",
687
- instructions: "",
688
- method: "auto",
689
- async callback() {
690
- if (!entry)
691
- return { type: "failed" };
692
- return {
693
- type: "success",
694
- provider: entry.enterpriseUrl ? "github-copilot-enterprise" : "github-copilot",
695
- refresh: entry.refresh,
696
- access: entry.access,
697
- expires: entry.expires,
698
- ...(entry.enterpriseUrl ? { enterpriseUrl: entry.enterpriseUrl } : {}),
699
- };
700
- },
701
- };
702
- },
703
- },
704
- ],
710
+ methods,
705
711
  },
706
- };
712
+ });
707
713
  };
package/dist/store.d.ts CHANGED
@@ -54,9 +54,12 @@ export type StoreFile = {
54
54
  autoRefresh?: boolean;
55
55
  refreshMinutes?: number;
56
56
  lastQuotaRefresh?: number;
57
+ loopSafetyEnabled?: boolean;
57
58
  };
58
59
  export declare function storePath(): string;
59
60
  export declare function authPath(): string;
60
- export declare function readStore(): Promise<StoreFile>;
61
+ export declare function parseStore(raw: string): StoreFile;
62
+ export declare function readStore(filePath?: string): Promise<StoreFile>;
63
+ export declare function readStoreSafe(filePath?: string): Promise<StoreFile | undefined>;
61
64
  export declare function readAuth(filePath?: string): Promise<Record<string, AccountEntry>>;
62
65
  export declare function writeStore(store: StoreFile): Promise<void>;
package/dist/store.js CHANGED
@@ -12,12 +12,12 @@ export function authPath() {
12
12
  const dataDir = xdgData ?? path.join(os.homedir(), ".local", "share");
13
13
  return path.join(dataDir, "opencode", authFile);
14
14
  }
15
- export async function readStore() {
16
- const file = storePath();
17
- const raw = await fs.readFile(file, "utf-8").catch(() => "");
15
+ export function parseStore(raw) {
18
16
  const data = raw ? JSON.parse(raw) : { accounts: {} };
19
17
  if (!data.accounts)
20
18
  data.accounts = {};
19
+ if (data.loopSafetyEnabled !== true)
20
+ data.loopSafetyEnabled = false;
21
21
  for (const [name, entry] of Object.entries(data.accounts)) {
22
22
  const info = entry;
23
23
  if (!info.name)
@@ -25,6 +25,26 @@ export async function readStore() {
25
25
  }
26
26
  return data;
27
27
  }
28
+ export async function readStore(filePath = storePath()) {
29
+ const raw = await fs.readFile(filePath, "utf-8").catch((error) => {
30
+ if (error.code === "ENOENT")
31
+ return "";
32
+ throw error;
33
+ });
34
+ return parseStore(raw);
35
+ }
36
+ export async function readStoreSafe(filePath = storePath()) {
37
+ try {
38
+ const raw = await fs.readFile(filePath, "utf-8");
39
+ return parseStore(raw);
40
+ }
41
+ catch (error) {
42
+ const issue = error;
43
+ if (issue.code === "ENOENT")
44
+ return parseStore("");
45
+ return undefined;
46
+ }
47
+ }
28
48
  export async function readAuth(filePath) {
29
49
  const dataFile = path.join(xdgData ?? path.join(os.homedir(), ".local", "share"), "opencode", authFile);
30
50
  const configFile = path.join(xdgConfig ?? path.join(os.homedir(), ".config"), "opencode", authFile);
@@ -1,4 +1,4 @@
1
- import { select } from "./select";
1
+ import { select } from "./select.js";
2
2
  export async function confirm(message, defaultYes = false) {
3
3
  const items = defaultYes
4
4
  ? [
package/dist/ui/menu.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type MenuItem } from "./select.js";
1
2
  export type AccountStatus = "active" | "expired" | "unknown";
2
3
  export interface AccountInfo {
3
4
  name: string;
@@ -52,6 +53,8 @@ export type MenuAction = {
52
53
  type: "toggle-refresh";
53
54
  } | {
54
55
  type: "set-interval";
56
+ } | {
57
+ type: "toggle-loop-safety";
55
58
  } | {
56
59
  type: "switch";
57
60
  account: AccountInfo;
@@ -63,8 +66,17 @@ export type MenuAction = {
63
66
  } | {
64
67
  type: "cancel";
65
68
  };
69
+ export declare function buildMenuItems(input: {
70
+ accounts: AccountInfo[];
71
+ refresh?: {
72
+ enabled: boolean;
73
+ minutes: number;
74
+ };
75
+ lastQuotaRefresh?: number;
76
+ loopSafetyEnabled: boolean;
77
+ }): MenuItem<MenuAction>[];
66
78
  export declare function showMenu(accounts: AccountInfo[], refresh?: {
67
79
  enabled: boolean;
68
80
  minutes: number;
69
- }, lastQuotaRefresh?: number): Promise<MenuAction>;
81
+ }, lastQuotaRefresh?: number, loopSafetyEnabled?: boolean): Promise<MenuAction>;
70
82
  export declare function showAccountActions(account: AccountInfo): Promise<"switch" | "remove" | "back">;
package/dist/ui/menu.js CHANGED
@@ -1,6 +1,6 @@
1
- import { ANSI } from "./ansi";
2
- import { select } from "./select";
3
- import { confirm } from "./confirm";
1
+ import { ANSI } from "./ansi.js";
2
+ import { select } from "./select.js";
3
+ import { confirm } from "./confirm.js";
4
4
  function formatRelativeTime(timestamp) {
5
5
  if (!timestamp)
6
6
  return "never";
@@ -25,9 +25,9 @@ function getStatusBadge(status) {
25
25
  return `${ANSI.red}[expired]${ANSI.reset}`;
26
26
  return "";
27
27
  }
28
- export async function showMenu(accounts, refresh, lastQuotaRefresh) {
29
- const quotaHint = lastQuotaRefresh ? `last ${formatRelativeTime(lastQuotaRefresh)}` : undefined;
30
- const items = [
28
+ export function buildMenuItems(input) {
29
+ const quotaHint = input.lastQuotaRefresh ? `last ${formatRelativeTime(input.lastQuotaRefresh)}` : undefined;
30
+ return [
31
31
  { label: "Actions", value: { type: "cancel" }, kind: "heading" },
32
32
  { label: "Add account", value: { type: "add" }, color: "cyan", hint: "device login or manual" },
33
33
  { label: "Import from auth.json", value: { type: "import" }, color: "cyan" },
@@ -35,15 +35,21 @@ export async function showMenu(accounts, refresh, lastQuotaRefresh) {
35
35
  { label: "Refresh identity", value: { type: "refresh-identity" }, color: "cyan" },
36
36
  { label: "Check models", value: { type: "check-models" }, color: "cyan" },
37
37
  {
38
- label: refresh?.enabled ? "Disable auto refresh" : "Enable auto refresh",
38
+ label: input.refresh?.enabled ? "Disable auto refresh" : "Enable auto refresh",
39
39
  value: { type: "toggle-refresh" },
40
40
  color: "cyan",
41
- hint: refresh ? `${refresh.minutes}m` : undefined,
41
+ hint: input.refresh ? `${input.refresh.minutes}m` : undefined,
42
42
  },
43
43
  { label: "Set refresh interval", value: { type: "set-interval" }, color: "cyan" },
44
+ {
45
+ label: input.loopSafetyEnabled ? "Disable guided loop safety" : "Enable guided loop safety",
46
+ value: { type: "toggle-loop-safety" },
47
+ color: "cyan",
48
+ hint: "Prompt-guided: fewer report interruptions, fewer unnecessary subagents",
49
+ },
44
50
  { label: "", value: { type: "cancel" }, separator: true },
45
51
  { label: "Accounts", value: { type: "cancel" }, kind: "heading" },
46
- ...accounts.map((account) => {
52
+ ...input.accounts.map((account) => {
47
53
  const statusBadge = getStatusBadge(account.status);
48
54
  const currentBadge = account.isCurrent ? ` ${ANSI.cyan}*${ANSI.reset}` : "";
49
55
  const format = (s) => s?.unlimited ? "∞" : s?.remaining !== undefined && s?.entitlement !== undefined ? `${s.remaining}/${s.entitlement}` : "?";
@@ -69,6 +75,14 @@ export async function showMenu(accounts, refresh, lastQuotaRefresh) {
69
75
  { label: "Danger zone", value: { type: "cancel" }, kind: "heading" },
70
76
  { label: "Remove all accounts", value: { type: "remove-all" }, color: "red" },
71
77
  ];
78
+ }
79
+ export async function showMenu(accounts, refresh, lastQuotaRefresh, loopSafetyEnabled = false) {
80
+ const items = buildMenuItems({
81
+ accounts,
82
+ refresh,
83
+ lastQuotaRefresh,
84
+ loopSafetyEnabled,
85
+ });
72
86
  while (true) {
73
87
  const result = await select(items, {
74
88
  message: "GitHub Copilot accounts",
package/dist/ui/select.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ANSI, isTTY, parseKey } from "./ansi";
1
+ import { ANSI, isTTY, parseKey } from "./ansi.js";
2
2
  const ESCAPE_TIMEOUT_MS = 50;
3
3
  const ANSI_REGEX = new RegExp("\\x1b\\[[0-9;]*m", "g");
4
4
  const ANSI_LEADING_REGEX = new RegExp("^\\x1b\\[[0-9;]*m");
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "opencode-copilot-account-switcher",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "GitHub Copilot account switcher plugin for OpenCode",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "type": "module",
8
- "license": "MIT",
8
+ "license": "MPL-2.0",
9
9
  "author": "jiwangyihao",
10
10
  "repository": {
11
11
  "type": "git",
@@ -32,6 +32,7 @@
32
32
  ],
33
33
  "scripts": {
34
34
  "build": "tsc -p tsconfig.build.json",
35
+ "test": "npm run build && node --test",
35
36
  "typecheck": "tsc --noEmit",
36
37
  "prepublishOnly": "npm run build"
37
38
  },