libre-webui 0.40.0 → 0.41.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.
- package/backend/dist/routes/work.d.ts.map +1 -1
- package/backend/dist/routes/work.js +98 -9
- package/backend/dist/routes/work.js.map +1 -1
- package/backend/dist/services/agentCliService.d.ts +15 -1
- package/backend/dist/services/agentCliService.d.ts.map +1 -1
- package/backend/dist/services/agentCliService.js +158 -25
- package/backend/dist/services/agentCliService.js.map +1 -1
- package/backend/dist/services/authorizationService.d.ts +1 -1
- package/backend/dist/services/authorizationService.d.ts.map +1 -1
- package/backend/dist/services/authorizationService.js +18 -1
- package/backend/dist/services/authorizationService.js.map +1 -1
- package/backend/dist/services/codexOAuthService.d.ts +11 -0
- package/backend/dist/services/codexOAuthService.d.ts.map +1 -1
- package/backend/dist/services/codexOAuthService.js +33 -7
- package/backend/dist/services/codexOAuthService.js.map +1 -1
- package/backend/dist/services/kiroLoginDatabase.d.ts +15 -0
- package/backend/dist/services/kiroLoginDatabase.d.ts.map +1 -0
- package/backend/dist/services/kiroLoginDatabase.js +104 -0
- package/backend/dist/services/kiroLoginDatabase.js.map +1 -0
- package/backend/dist/services/pluginService.d.ts.map +1 -1
- package/backend/dist/services/pluginService.js +9 -2
- package/backend/dist/services/pluginService.js.map +1 -1
- package/backend/dist/services/titleGenerationService.d.ts +10 -1
- package/backend/dist/services/titleGenerationService.d.ts.map +1 -1
- package/backend/dist/services/titleGenerationService.js +53 -15
- package/backend/dist/services/titleGenerationService.js.map +1 -1
- package/backend/dist/services/workAgentAccessService.d.ts +21 -0
- package/backend/dist/services/workAgentAccessService.d.ts.map +1 -0
- package/backend/dist/services/workAgentAccessService.js +94 -0
- package/backend/dist/services/workAgentAccessService.js.map +1 -0
- package/backend/dist/services/workAgentCatalog.d.ts +38 -0
- package/backend/dist/services/workAgentCatalog.d.ts.map +1 -0
- package/backend/dist/services/workAgentCatalog.js +173 -0
- package/backend/dist/services/workAgentCatalog.js.map +1 -0
- package/backend/dist/services/workAgentCliRunner.d.ts +56 -0
- package/backend/dist/services/workAgentCliRunner.d.ts.map +1 -0
- package/backend/dist/services/workAgentCliRunner.js +403 -0
- package/backend/dist/services/workAgentCliRunner.js.map +1 -0
- package/backend/dist/services/workAgentHostLogins.d.ts +181 -0
- package/backend/dist/services/workAgentHostLogins.d.ts.map +1 -0
- package/backend/dist/services/workAgentHostLogins.js +982 -0
- package/backend/dist/services/workAgentHostLogins.js.map +1 -0
- package/backend/dist/services/workAgentService.d.ts +15 -0
- package/backend/dist/services/workAgentService.d.ts.map +1 -1
- package/backend/dist/services/workAgentService.js +218 -0
- package/backend/dist/services/workAgentService.js.map +1 -1
- package/backend/dist/services/workAgentStream.d.ts +57 -0
- package/backend/dist/services/workAgentStream.d.ts.map +1 -0
- package/backend/dist/services/workAgentStream.js +378 -0
- package/backend/dist/services/workAgentStream.js.map +1 -0
- package/backend/dist/services/workAgentToolchainService.d.ts +51 -0
- package/backend/dist/services/workAgentToolchainService.d.ts.map +1 -0
- package/backend/dist/services/workAgentToolchainService.js +337 -0
- package/backend/dist/services/workAgentToolchainService.js.map +1 -0
- package/backend/dist/services/workAgents.d.ts +44 -0
- package/backend/dist/services/workAgents.d.ts.map +1 -0
- package/backend/dist/services/workAgents.js +142 -0
- package/backend/dist/services/workAgents.js.map +1 -0
- package/backend/dist/services/workEgressProxy.d.ts +138 -0
- package/backend/dist/services/workEgressProxy.d.ts.map +1 -0
- package/backend/dist/services/workEgressProxy.js +561 -0
- package/backend/dist/services/workEgressProxy.js.map +1 -0
- package/backend/dist/services/workEgressRelay.d.ts +68 -0
- package/backend/dist/services/workEgressRelay.d.ts.map +1 -0
- package/backend/dist/services/workEgressRelay.js +315 -0
- package/backend/dist/services/workEgressRelay.js.map +1 -0
- package/backend/dist/services/workEventService.d.ts.map +1 -1
- package/backend/dist/services/workEventService.js +3 -1
- package/backend/dist/services/workEventService.js.map +1 -1
- package/backend/dist/services/workKubernetesDriver.d.ts +2 -1
- package/backend/dist/services/workKubernetesDriver.d.ts.map +1 -1
- package/backend/dist/services/workKubernetesDriver.js +45 -0
- package/backend/dist/services/workKubernetesDriver.js.map +1 -1
- package/backend/dist/services/workModelProviderService.d.ts.map +1 -1
- package/backend/dist/services/workModelProviderService.js +15 -1
- package/backend/dist/services/workModelProviderService.js.map +1 -1
- package/backend/dist/services/workRuntimeDriver.d.ts +32 -1
- package/backend/dist/services/workRuntimeDriver.d.ts.map +1 -1
- package/backend/dist/services/workRuntimeDriver.js +80 -4
- package/backend/dist/services/workRuntimeDriver.js.map +1 -1
- package/backend/dist/services/workRuntimeShared.d.ts +9 -0
- package/backend/dist/services/workRuntimeShared.d.ts.map +1 -1
- package/backend/dist/services/workRuntimeShared.js +17 -0
- package/backend/dist/services/workRuntimeShared.js.map +1 -1
- package/backend/dist/services/workTaskService.d.ts +2 -2
- package/backend/dist/services/workTaskService.d.ts.map +1 -1
- package/backend/dist/services/workTaskService.js +8 -5
- package/backend/dist/services/workTaskService.js.map +1 -1
- package/backend/dist/types/work.d.ts +10 -1
- package/backend/dist/types/work.d.ts.map +1 -1
- package/backend/dist/utils/bedrockMantle.d.ts +9 -1
- package/backend/dist/utils/bedrockMantle.d.ts.map +1 -1
- package/backend/dist/utils/bedrockMantle.js +34 -3
- package/backend/dist/utils/bedrockMantle.js.map +1 -1
- package/backend/dist/utils/pluginChatAdapter.d.ts.map +1 -1
- package/backend/dist/utils/pluginChatAdapter.js +16 -4
- package/backend/dist/utils/pluginChatAdapter.js.map +1 -1
- package/backend/dist/utils/pluginDefinitionTrust.js +2 -2
- package/backend/dist/utils/x509.d.ts +28 -0
- package/backend/dist/utils/x509.d.ts.map +1 -0
- package/backend/dist/utils/x509.js +206 -0
- package/backend/dist/utils/x509.js.map +1 -0
- package/backend/package.json +4 -4
- package/frontend/dist/artifact-runtime/.build-fingerprint +1 -1
- package/frontend/dist/artifact-runtime/framer-motion.js +3 -3
- package/frontend/dist/artifact-runtime/lucide-react.js +1 -1
- package/frontend/dist/artifact-runtime/mermaid.js +360 -360
- package/frontend/dist/assets/index-KsiiOLzU.js +87 -0
- package/frontend/dist/assets/markdown-math-Ngnvt50Q.css +1 -0
- package/frontend/dist/index.html +25 -25
- package/frontend/dist/js/{ArtifactContainer-BjzltfdU.js → ArtifactContainer-ZRc3iGTP.js} +1 -1
- package/frontend/dist/js/{ArtifactDemoPage-DWua6xj9.js → ArtifactDemoPage-D5tBk02B.js} +1 -1
- package/frontend/dist/js/{ArtifactSandboxFrame-CR9ghP0A.js → ArtifactSandboxFrame-DFBbDNYt.js} +1 -1
- package/frontend/dist/js/{ArtifactSlideOutPanel-DX2nL3AS.js → ArtifactSlideOutPanel-JxYwQhb3.js} +1 -1
- package/frontend/dist/js/{AutomationModal-DZe-C2jN.js → AutomationModal-d2KdJtri.js} +1 -1
- package/frontend/dist/js/{AutomationsPage-CrCcnTyk.js → AutomationsPage-C9zK5Svl.js} +1 -1
- package/frontend/dist/js/{AvatarUpload-nPS0QHod.js → AvatarUpload-Cxdp4Imm.js} +1 -1
- package/frontend/dist/js/{CalendarPage-D2WiWglM.js → CalendarPage-Di0wpPHv.js} +1 -1
- package/frontend/dist/js/{ChannelsPage-COp2T8FQ.js → ChannelsPage-D4I12rSV.js} +1 -1
- package/frontend/dist/js/ChatPage-BPVykNDN.js +14 -0
- package/frontend/dist/js/{ConnectModels-emc3dv4A.js → ConnectModels-D4bfRr_C.js} +1 -1
- package/frontend/dist/js/{EvaluationsPage-CbyeDkz_.js → EvaluationsPage-BHNu-Yuv.js} +1 -1
- package/frontend/dist/js/{FirstTimeSetup-C4ffQRMN.js → FirstTimeSetup-DwAazkKS.js} +1 -1
- package/frontend/dist/js/{GalleryPage-D4Ci_3dv.js → GalleryPage-CiWQz3MO.js} +1 -1
- package/frontend/dist/js/{HomePage-C3IhEERN.js → HomePage--BXg7yYq.js} +1 -1
- package/frontend/dist/js/{LanguageSwitcher-BQqDJPwm.js → LanguageSwitcher-BytOonLT.js} +1 -1
- package/frontend/dist/js/{ModelManagerModals-DhY8Rme6.js → ModelManagerModals-luKNvxGZ.js} +1 -1
- package/frontend/dist/js/{NotesPage-j812I1BN.js → NotesPage-BmSY4zjn.js} +1 -1
- package/frontend/dist/js/{PasswordStrengthMeter-BSEtQBJp.js → PasswordStrengthMeter-Dnvy9FTf.js} +1 -1
- package/frontend/dist/js/{PersonasPage--YWoThqF.js → PersonasPage-D4lLqYL7.js} +1 -1
- package/frontend/dist/js/PluginUsagePage-BrAUsPF1.js +1 -0
- package/frontend/dist/js/RichMessageContent-BLr0i8PB.js +1 -0
- package/frontend/dist/js/{RichMessageContent-BLI0hhzR.js → RichMessageContent-JqidvjnA.js} +2 -2
- package/frontend/dist/js/SettingsModal-BHsYfMHh.js +19 -0
- package/frontend/dist/js/{ShareDialog-DQskc17d.js → ShareDialog-LLptgA-s.js} +1 -1
- package/frontend/dist/js/{StrandsPage-DENhVKcz.js → StrandsPage-Bygb-VLO.js} +1 -1
- package/frontend/dist/js/SystemPage-BNRBHrES.js +1 -0
- package/frontend/dist/js/{TurnstileWidget-tI50c7Kc.js → TurnstileWidget-7oVjbntG.js} +1 -1
- package/frontend/dist/js/{UserManagementPage-UvPjA9RP.js → UserManagementPage-M2ZhkF7m.js} +1 -1
- package/frontend/dist/js/{UserManagementPanel-D1CS0KPn.js → UserManagementPanel-DBZKnZ-G.js} +1 -1
- package/frontend/dist/js/{WhatsNewModal-B31A_UQY.js → WhatsNewModal-C65J_hEe.js} +1 -1
- package/frontend/dist/js/WorkPage-WQ3tojri.js +7 -0
- package/frontend/dist/js/{api-Dcz1G4Ib.js → api-Bnbon_Rp.js} +1 -1
- package/frontend/dist/js/api-CtbDCatP.js +1 -0
- package/frontend/dist/js/{appNavigation-C5A9BF_G.js → appNavigation-C4WPz06g.js} +1 -1
- package/frontend/dist/js/{appStore-0_qlwS8f.js → appStore-BeRY0hZe.js} +2 -2
- package/frontend/dist/js/appVersion-JNHbZTzT.js +1 -0
- package/frontend/dist/js/ar-D4ACicTy.js +2 -0
- package/frontend/dist/js/{authStore-COgKeTRv.js → authStore-Ccdoy8Vq.js} +3 -3
- package/frontend/dist/js/authStore-DTSwmAtW.js +1 -0
- package/frontend/dist/js/{bn-BDCaFQu-.js → bn-U-J9oKiN.js} +1 -1
- package/frontend/dist/js/{chatStore-CVTbkZyb.js → chatStore-BV17ffDe.js} +3 -3
- package/frontend/dist/js/{client-jaxZzn-I.js → client-CGDIO9t6.js} +2 -2
- package/frontend/dist/js/{config-Da1yh9sC.js → config-DYZVxv3t.js} +1 -1
- package/frontend/dist/js/cs-DqF3kKON.js +2 -0
- package/frontend/dist/js/da-BY_ue7IH.js +2 -0
- package/frontend/dist/js/de-ByqcjDDi.js +2 -0
- package/frontend/dist/js/es-PpY8rAbj.js +2 -0
- package/frontend/dist/js/{evaluationsApi-BwaxBVpl.js → evaluationsApi-VwEJ0x8J.js} +1 -1
- package/frontend/dist/js/fr-B8kAmhGd.js +2 -0
- package/frontend/dist/js/hi-pOpOSvWK.js +2 -0
- package/frontend/dist/js/id-bRK07dZm.js +2 -0
- package/frontend/dist/js/is-BObnLGvi.js +2 -0
- package/frontend/dist/js/it-Dgcq9Mkn.js +2 -0
- package/frontend/dist/js/ja-BhkyZZKR.js +2 -0
- package/frontend/dist/js/ko-D-xfOA2T.js +2 -0
- package/frontend/dist/js/logger-B4-E6SY8.js +1 -0
- package/frontend/dist/js/markdown-math-BtrScp6v.js +261 -0
- package/frontend/dist/js/markdownMath-DPjkFHpu.js +1 -0
- package/frontend/dist/js/{messageCodeStyles-D3cWF9XO.js → messageCodeStyles-CHTEQi80.js} +1 -1
- package/frontend/dist/js/ms-DLFQvNh-.js +2 -0
- package/frontend/dist/js/nl-BWFqTL4u.js +2 -0
- package/frontend/dist/js/pl-Cr0-8RBA.js +2 -0
- package/frontend/dist/js/pt-DpNh0tQT.js +2 -0
- package/frontend/dist/js/{router-vendor-DqMnEJWK.js → router-vendor-CKl1g8Qt.js} +1 -1
- package/frontend/dist/js/ru-VPEPKfbU.js +2 -0
- package/frontend/dist/js/{strandsApi-COxSPh_5.js → strandsApi-D6XECW3U.js} +1 -1
- package/frontend/dist/js/sv-Bb41KZL-.js +2 -0
- package/frontend/dist/js/{teamEventStream-RNJYm84u.js → teamEventStream-C5Zk1VDu.js} +1 -1
- package/frontend/dist/js/th-D8ahJkLy.js +2 -0
- package/frontend/dist/js/tr-LxdOSx7H.js +2 -0
- package/frontend/dist/js/{ui-CI0OdG9q.js → ui-CU8ko29F.js} +2 -2
- package/frontend/dist/js/{ui-vendor-6S05F84J.js → ui-vendor-Bk_S1tZa.js} +1 -1
- package/frontend/dist/js/uk-MWQC7_0z.js +2 -0
- package/frontend/dist/js/{useChat-BSkqxHnH.js → useChat-D02w6J_J.js} +1 -1
- package/frontend/dist/js/useDictation-mEvTPNBJ.js +1 -0
- package/frontend/dist/js/vi-DZIXswgY.js +2 -0
- package/frontend/dist/js/{work-C7MYlv5S.js → work-BP_ujNmK.js} +1 -1
- package/frontend/dist/js/workAnnouncements-C2Cd6YCk.js +1 -0
- package/frontend/dist/js/workApi-BL1yHp4v.js +5 -0
- package/frontend/dist/js/workApi-D5BcMUUb.js +1 -0
- package/frontend/dist/js/zh-Cpymo7dg.js +2 -0
- package/package.json +8 -4
- package/plugins/anthropic.json +1 -0
- package/plugins/bedrock.json +2 -1
- package/frontend/dist/assets/index-DLfU_qNT.js +0 -75
- package/frontend/dist/assets/markdown-math-DzFXvcrH.css +0 -1
- package/frontend/dist/js/ChatPage-CUfAlpdt.js +0 -14
- package/frontend/dist/js/PluginUsagePage-CZiMdmjI.js +0 -1
- package/frontend/dist/js/RichMessageContent-BXv5baJ_.js +0 -1
- package/frontend/dist/js/SettingsModal-C6aVzSI-.js +0 -19
- package/frontend/dist/js/SystemPage-C86ypXG4.js +0 -1
- package/frontend/dist/js/WorkPage-DEXBL5J7.js +0 -7
- package/frontend/dist/js/api-DRAKhdz7.js +0 -1
- package/frontend/dist/js/appVersion-D5lk_2zb.js +0 -1
- package/frontend/dist/js/ar-BZntyucf.js +0 -2
- package/frontend/dist/js/authStore-C4dzH1NY.js +0 -1
- package/frontend/dist/js/cs-BCmN--jQ.js +0 -2
- package/frontend/dist/js/da-B895dAyV.js +0 -2
- package/frontend/dist/js/de-B0ZhC0dm.js +0 -2
- package/frontend/dist/js/es-D7eaw4_W.js +0 -2
- package/frontend/dist/js/fr-DsB0gLW4.js +0 -2
- package/frontend/dist/js/hi-CLeU3ung.js +0 -2
- package/frontend/dist/js/id-Cdq6tOTi.js +0 -2
- package/frontend/dist/js/is-DJ1tHaAT.js +0 -2
- package/frontend/dist/js/it-9K1R4CeT.js +0 -2
- package/frontend/dist/js/ja-BYP_3M5M.js +0 -2
- package/frontend/dist/js/ko-CNtjlaDm.js +0 -2
- package/frontend/dist/js/logger-BR4forr_.js +0 -1
- package/frontend/dist/js/markdown-math-DxPfMKvO.js +0 -261
- package/frontend/dist/js/markdownMath-CsfRQAcz.js +0 -1
- package/frontend/dist/js/ms-A_IVO_qt.js +0 -2
- package/frontend/dist/js/nl-CrKWO3ea.js +0 -2
- package/frontend/dist/js/pl-BrpSuyDP.js +0 -2
- package/frontend/dist/js/pt-BHbpB5BM.js +0 -2
- package/frontend/dist/js/ru-DzLsS9zY.js +0 -2
- package/frontend/dist/js/sv-VU2CjzNj.js +0 -2
- package/frontend/dist/js/th-DV2hNXXc.js +0 -2
- package/frontend/dist/js/tr-DvVZ9jxF.js +0 -2
- package/frontend/dist/js/uk-MFFDRo2m.js +0 -2
- package/frontend/dist/js/useDictation-D9whH12W.js +0 -1
- package/frontend/dist/js/vi-CfZ-U8Cw.js +0 -2
- package/frontend/dist/js/workAnnouncements-CAsI8P7c.js +0 -1
- package/frontend/dist/js/workApi-BJfbaV6k.js +0 -1
- package/frontend/dist/js/workApi-Ck8nTlJn.js +0 -5
- package/frontend/dist/js/zh-CTl_raYa.js +0 -2
|
@@ -0,0 +1,982 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Libre WebUI
|
|
3
|
+
* Copyright (C) 2025 Kroonen AI, Inc.
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at:
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The logins agent CLIs in Work run under: the same ones Chat uses, read
|
|
19
|
+
* from where each CLI keeps its own sign-in for the server user.
|
|
20
|
+
*
|
|
21
|
+
* Chat runs a CLI on the host, so the CLI simply finds its login. Work runs
|
|
22
|
+
* the CLI inside the task's sandbox, so each login here is turned into the
|
|
23
|
+
* CLI's own login file (or variable) with placeholders where the tokens go.
|
|
24
|
+
* The egress proxy swaps the real token in on the login's own API hosts;
|
|
25
|
+
* the token itself never enters the sandbox.
|
|
26
|
+
*
|
|
27
|
+
* A sandboxed CLI cannot refresh its login (a refresh token travels in a
|
|
28
|
+
* request body, which the proxy never rewrites), so the sandbox copy claims
|
|
29
|
+
* not to expire and the host side keeps the real token fresh instead, the
|
|
30
|
+
* way the CLI itself would: before the run and periodically during it.
|
|
31
|
+
* Refreshed tokens are written back where the CLI keeps them, so the CLI on
|
|
32
|
+
* the host keeps working too.
|
|
33
|
+
*/
|
|
34
|
+
import { execFile } from 'node:child_process';
|
|
35
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
36
|
+
import fs from 'node:fs';
|
|
37
|
+
import os from 'node:os';
|
|
38
|
+
import path from 'node:path';
|
|
39
|
+
import { createLogger } from '../utils/logger.js';
|
|
40
|
+
import { providerRequest } from '../utils/providerFetch.js';
|
|
41
|
+
import { resolveBinary } from './agentCliService.js';
|
|
42
|
+
import { readKiroLoginRows, scrubbedKiroDatabase, } from './kiroLoginDatabase.js';
|
|
43
|
+
import codexOAuthService from './codexOAuthService.js';
|
|
44
|
+
import { createEgressPlaceholder, } from './workEgressProxy.js';
|
|
45
|
+
const logger = createLogger('services:work-agent-logins');
|
|
46
|
+
/** A token must stay valid at least this long when a run (re)checks it. */
|
|
47
|
+
export const LOGIN_REFRESH_MARGIN_MS = 10 * 60000;
|
|
48
|
+
/** How long the sandbox copy claims to stay valid. */
|
|
49
|
+
const SANDBOX_VALIDITY_MS = 365 * 24 * 60 * 60000;
|
|
50
|
+
const STATUS_CACHE_MS = 15000;
|
|
51
|
+
const HOST_COMMAND_TIMEOUT_MS = 30000;
|
|
52
|
+
/** A login that is missing, expired, or of a kind Work cannot carry. */
|
|
53
|
+
export class WorkAgentLoginError extends Error {
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.status = 409;
|
|
57
|
+
this.code = 'WORK_AGENT_NOT_SIGNED_IN';
|
|
58
|
+
this.name = 'WorkAgentLoginError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// --- Provider hosts ------------------------------------------------------
|
|
62
|
+
const ANTHROPIC_HOSTS = ['api.anthropic.com'];
|
|
63
|
+
const OPENAI_HOSTS = ['api.openai.com'];
|
|
64
|
+
const CHATGPT_HOSTS = ['chatgpt.com'];
|
|
65
|
+
const COPILOT_HOSTS = [
|
|
66
|
+
'api.githubcopilot.com',
|
|
67
|
+
'api.individual.githubcopilot.com',
|
|
68
|
+
'api.business.githubcopilot.com',
|
|
69
|
+
'api.enterprise.githubcopilot.com',
|
|
70
|
+
];
|
|
71
|
+
const KIRO_HOSTS = [
|
|
72
|
+
'management.*.kiro.dev',
|
|
73
|
+
'runtime.*.kiro.dev',
|
|
74
|
+
'q.*.amazonaws.com',
|
|
75
|
+
'codewhisperer.*.amazonaws.com',
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* Where each provider's login may be used, for providers OpenCode and Pi
|
|
79
|
+
* can sign in to. Exact API hosts only: the proxy puts a real token on
|
|
80
|
+
* nothing else. A provider missing here cannot run in Work, and says so.
|
|
81
|
+
*/
|
|
82
|
+
export const WORK_AGENT_PROVIDER_HOSTS = {
|
|
83
|
+
anthropic: ANTHROPIC_HOSTS,
|
|
84
|
+
openai: OPENAI_HOSTS,
|
|
85
|
+
'openai-codex': CHATGPT_HOSTS,
|
|
86
|
+
openrouter: ['openrouter.ai'],
|
|
87
|
+
google: ['generativelanguage.googleapis.com'],
|
|
88
|
+
'github-copilot': COPILOT_HOSTS,
|
|
89
|
+
groq: ['api.groq.com'],
|
|
90
|
+
mistral: ['api.mistral.ai'],
|
|
91
|
+
deepseek: ['api.deepseek.com'],
|
|
92
|
+
xai: ['api.x.ai'],
|
|
93
|
+
cerebras: ['api.cerebras.ai'],
|
|
94
|
+
togetherai: ['api.together.xyz'],
|
|
95
|
+
'fireworks-ai': ['api.fireworks.ai'],
|
|
96
|
+
moonshotai: ['api.moonshot.ai'],
|
|
97
|
+
zai: ['api.z.ai'],
|
|
98
|
+
'zai-coding-plan': ['api.z.ai'],
|
|
99
|
+
opencode: ['opencode.ai'],
|
|
100
|
+
huggingface: ['router.huggingface.co'],
|
|
101
|
+
};
|
|
102
|
+
/** The variable each provider's key is read from when no login is saved. */
|
|
103
|
+
const PROVIDER_KEY_VARIABLES = {
|
|
104
|
+
anthropic: ['ANTHROPIC_API_KEY'],
|
|
105
|
+
openai: ['OPENAI_API_KEY'],
|
|
106
|
+
openrouter: ['OPENROUTER_API_KEY'],
|
|
107
|
+
google: ['GEMINI_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY'],
|
|
108
|
+
groq: ['GROQ_API_KEY'],
|
|
109
|
+
mistral: ['MISTRAL_API_KEY'],
|
|
110
|
+
deepseek: ['DEEPSEEK_API_KEY'],
|
|
111
|
+
xai: ['XAI_API_KEY'],
|
|
112
|
+
cerebras: ['CEREBRAS_API_KEY'],
|
|
113
|
+
togetherai: ['TOGETHER_API_KEY'],
|
|
114
|
+
'fireworks-ai': ['FIREWORKS_API_KEY'],
|
|
115
|
+
moonshotai: ['MOONSHOT_API_KEY'],
|
|
116
|
+
huggingface: ['HF_TOKEN'],
|
|
117
|
+
};
|
|
118
|
+
// --- Shared helpers ------------------------------------------------------
|
|
119
|
+
function base64url(value) {
|
|
120
|
+
return Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
121
|
+
}
|
|
122
|
+
function jwtClaims(token) {
|
|
123
|
+
const parts = token.split('.');
|
|
124
|
+
if (parts.length !== 3)
|
|
125
|
+
return null;
|
|
126
|
+
try {
|
|
127
|
+
const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
128
|
+
return claims && typeof claims === 'object'
|
|
129
|
+
? claims
|
|
130
|
+
: null;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const OPENAI_AUTH_CLAIM = 'https://api.openai.com/auth';
|
|
137
|
+
/**
|
|
138
|
+
* A placeholder shaped like the token it replaces. CLIs that read their
|
|
139
|
+
* account from a ChatGPT access token still find it, along with an expiry
|
|
140
|
+
* far enough out that they never try to refresh; the signature segment is
|
|
141
|
+
* the placeholder itself, so the whole string is what the proxy replaces.
|
|
142
|
+
*/
|
|
143
|
+
export function placeholderFor(realToken) {
|
|
144
|
+
const placeholder = createEgressPlaceholder();
|
|
145
|
+
const claims = jwtClaims(realToken);
|
|
146
|
+
if (!claims)
|
|
147
|
+
return placeholder;
|
|
148
|
+
const kept = {
|
|
149
|
+
exp: Math.floor((Date.now() + SANDBOX_VALIDITY_MS) / 1000),
|
|
150
|
+
};
|
|
151
|
+
const auth = claims[OPENAI_AUTH_CLAIM];
|
|
152
|
+
if (auth && typeof auth === 'object') {
|
|
153
|
+
const { chatgpt_account_id, chatgpt_plan_type } = auth;
|
|
154
|
+
kept[OPENAI_AUTH_CLAIM] = { chatgpt_account_id, chatgpt_plan_type };
|
|
155
|
+
}
|
|
156
|
+
if (typeof claims.chatgpt_account_id === 'string') {
|
|
157
|
+
kept.chatgpt_account_id = claims.chatgpt_account_id;
|
|
158
|
+
}
|
|
159
|
+
return `${base64url({ alg: 'none', typ: 'JWT' })}.${base64url(kept)}.${placeholder}`;
|
|
160
|
+
}
|
|
161
|
+
/** A token the proxy reads on every request, replaced when refreshed. */
|
|
162
|
+
class LiveSecret {
|
|
163
|
+
constructor(value) {
|
|
164
|
+
this.value = value;
|
|
165
|
+
this.read = () => this.value;
|
|
166
|
+
}
|
|
167
|
+
set(value) {
|
|
168
|
+
this.value = value;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function credential(name, placeholder, secret, hosts) {
|
|
172
|
+
return {
|
|
173
|
+
name,
|
|
174
|
+
placeholder,
|
|
175
|
+
secret: typeof secret === 'string' ? secret : secret.read,
|
|
176
|
+
hosts,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function jsonFile(relativePath, value) {
|
|
180
|
+
return {
|
|
181
|
+
path: relativePath,
|
|
182
|
+
content: Buffer.from(`${JSON.stringify(value, null, 2)}\n`),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function readJson(file) {
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
188
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
189
|
+
? parsed
|
|
190
|
+
: null;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/** Write a login file back with the same restrictive mode the CLI uses. */
|
|
197
|
+
function writeJsonPrivate(file, value) {
|
|
198
|
+
const temporary = `${file}.libre-${randomBytes(4).toString('hex')}`;
|
|
199
|
+
fs.writeFileSync(temporary, JSON.stringify(value, null, 2), {
|
|
200
|
+
mode: 0o600,
|
|
201
|
+
});
|
|
202
|
+
fs.renameSync(temporary, file);
|
|
203
|
+
}
|
|
204
|
+
function environmentValue(name) {
|
|
205
|
+
const value = process.env[name]?.trim();
|
|
206
|
+
return value ? value : undefined;
|
|
207
|
+
}
|
|
208
|
+
function xdgDataHome() {
|
|
209
|
+
return (environmentValue('XDG_DATA_HOME') ??
|
|
210
|
+
path.join(os.homedir(), '.local', 'share'));
|
|
211
|
+
}
|
|
212
|
+
function runHost(command, args, options = {}) {
|
|
213
|
+
return new Promise(resolve => {
|
|
214
|
+
const child = execFile(command, [...args], {
|
|
215
|
+
timeout: HOST_COMMAND_TIMEOUT_MS,
|
|
216
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
217
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
218
|
+
}, (error, stdout) => {
|
|
219
|
+
const code = error && typeof error.code === 'number'
|
|
220
|
+
? error.code
|
|
221
|
+
: error
|
|
222
|
+
? 1
|
|
223
|
+
: 0;
|
|
224
|
+
resolve({ code, stdout: String(stdout) });
|
|
225
|
+
});
|
|
226
|
+
child.stdin?.end(options.input ?? '');
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
function signInHint(cli, command) {
|
|
230
|
+
return `${cli} is not signed in on this server. Run \`${command}\` as the server user (the account Libre WebUI runs as), then try again.`;
|
|
231
|
+
}
|
|
232
|
+
function expiredHint(cli, command) {
|
|
233
|
+
return `${cli}'s login on this server has expired and could not be refreshed. Run \`${command}\` as the server user, then try again.`;
|
|
234
|
+
}
|
|
235
|
+
/** Cache a cheap status for a few seconds; the picker asks often. */
|
|
236
|
+
function cachedStatus(read) {
|
|
237
|
+
let cached = null;
|
|
238
|
+
return () => {
|
|
239
|
+
if (!cached || Date.now() - cached.at > STATUS_CACHE_MS) {
|
|
240
|
+
cached = { at: Date.now(), value: read() };
|
|
241
|
+
}
|
|
242
|
+
return cached.value;
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
const ANTHROPIC_OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
|
|
246
|
+
const OPENAI_OAUTH_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
|
247
|
+
async function refreshAnthropic(refreshToken, signal) {
|
|
248
|
+
const response = await providerRequest({
|
|
249
|
+
url: process.env.WORK_AGENT_ANTHROPIC_OAUTH_URL ||
|
|
250
|
+
'https://console.anthropic.com/v1/oauth/token',
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: { 'Content-Type': 'application/json' },
|
|
253
|
+
body: JSON.stringify({
|
|
254
|
+
grant_type: 'refresh_token',
|
|
255
|
+
refresh_token: refreshToken,
|
|
256
|
+
client_id: ANTHROPIC_OAUTH_CLIENT_ID,
|
|
257
|
+
}),
|
|
258
|
+
timeoutMs: HOST_COMMAND_TIMEOUT_MS,
|
|
259
|
+
...(signal ? { signal } : {}),
|
|
260
|
+
});
|
|
261
|
+
const data = response.data;
|
|
262
|
+
if (!data.access_token) {
|
|
263
|
+
throw new Error('The Anthropic token refresh returned no access token.');
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
access: data.access_token,
|
|
267
|
+
...(data.refresh_token ? { refresh: data.refresh_token } : {}),
|
|
268
|
+
expiresAtMs: Date.now() + (data.expires_in ?? 3600) * 1000,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
async function refreshOpenAi(refreshToken, signal) {
|
|
272
|
+
const response = await providerRequest({
|
|
273
|
+
url: process.env.CODEX_OAUTH_TOKEN_URL ||
|
|
274
|
+
'https://auth.openai.com/oauth/token',
|
|
275
|
+
method: 'POST',
|
|
276
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
277
|
+
body: new URLSearchParams({
|
|
278
|
+
grant_type: 'refresh_token',
|
|
279
|
+
refresh_token: refreshToken,
|
|
280
|
+
client_id: OPENAI_OAUTH_CLIENT_ID,
|
|
281
|
+
}).toString(),
|
|
282
|
+
timeoutMs: HOST_COMMAND_TIMEOUT_MS,
|
|
283
|
+
...(signal ? { signal } : {}),
|
|
284
|
+
});
|
|
285
|
+
const data = response.data;
|
|
286
|
+
if (!data.access_token) {
|
|
287
|
+
throw new Error('The OpenAI token refresh returned no access token.');
|
|
288
|
+
}
|
|
289
|
+
const exp = jwtClaims(data.access_token)?.exp;
|
|
290
|
+
return {
|
|
291
|
+
access: data.access_token,
|
|
292
|
+
...(data.refresh_token ? { refresh: data.refresh_token } : {}),
|
|
293
|
+
expiresAtMs: typeof exp === 'number'
|
|
294
|
+
? exp * 1000
|
|
295
|
+
: Date.now() + (data.expires_in ?? 3600) * 1000,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/** A Copilot session token from the long-lived GitHub token. */
|
|
299
|
+
async function refreshCopilot(githubToken, signal) {
|
|
300
|
+
const response = await providerRequest({
|
|
301
|
+
url: 'https://api.github.com/copilot_internal/v2/token',
|
|
302
|
+
method: 'GET',
|
|
303
|
+
headers: {
|
|
304
|
+
Accept: 'application/json',
|
|
305
|
+
Authorization: `Bearer ${githubToken}`,
|
|
306
|
+
'User-Agent': 'GitHubCopilotChat/0.26.7',
|
|
307
|
+
'Editor-Version': 'vscode/1.99.3',
|
|
308
|
+
'Editor-Plugin-Version': 'copilot-chat/0.26.7',
|
|
309
|
+
},
|
|
310
|
+
timeoutMs: HOST_COMMAND_TIMEOUT_MS,
|
|
311
|
+
...(signal ? { signal } : {}),
|
|
312
|
+
});
|
|
313
|
+
const data = response.data;
|
|
314
|
+
if (!data.token) {
|
|
315
|
+
throw new Error('GitHub returned no Copilot token.');
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
access: data.token,
|
|
319
|
+
// The GitHub token is the refresh token; it does not rotate.
|
|
320
|
+
refresh: githubToken,
|
|
321
|
+
expiresAtMs: typeof data.expires_at === 'number'
|
|
322
|
+
? data.expires_at * 1000
|
|
323
|
+
: Date.now() + 25 * 60000,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
/** The refresh flow for an OpenCode or Pi provider's OAuth login. */
|
|
327
|
+
const PROVIDER_REFRESH = {
|
|
328
|
+
anthropic: refreshAnthropic,
|
|
329
|
+
openai: refreshOpenAi,
|
|
330
|
+
'openai-codex': refreshOpenAi,
|
|
331
|
+
'github-copilot': refreshCopilot,
|
|
332
|
+
};
|
|
333
|
+
const CLAUDE_KEYCHAIN_SERVICE = 'Claude Code-credentials';
|
|
334
|
+
/**
|
|
335
|
+
* Where Claude Code keeps its subscription login: the macOS login keychain,
|
|
336
|
+
* or `.credentials.json` in its config directory elsewhere. A custom
|
|
337
|
+
* CLAUDE_CONFIG_DIR gets its own keychain entry, suffixed like the CLI does.
|
|
338
|
+
*/
|
|
339
|
+
export class ClaudeCodeLoginStore {
|
|
340
|
+
constructor(platform = process.platform, configDir = environmentValue('CLAUDE_CONFIG_DIR')) {
|
|
341
|
+
this.platform = platform;
|
|
342
|
+
this.configDir = configDir;
|
|
343
|
+
}
|
|
344
|
+
get file() {
|
|
345
|
+
return path.join(this.configDir ?? path.join(os.homedir(), '.claude'), '.credentials.json');
|
|
346
|
+
}
|
|
347
|
+
get service() {
|
|
348
|
+
if (!this.configDir)
|
|
349
|
+
return CLAUDE_KEYCHAIN_SERVICE;
|
|
350
|
+
const suffix = createHash('sha256')
|
|
351
|
+
.update(this.configDir)
|
|
352
|
+
.digest('hex')
|
|
353
|
+
.slice(0, 8);
|
|
354
|
+
return `${CLAUDE_KEYCHAIN_SERVICE}-${suffix}`;
|
|
355
|
+
}
|
|
356
|
+
async read() {
|
|
357
|
+
if (this.platform !== 'darwin')
|
|
358
|
+
return readJson(this.file);
|
|
359
|
+
const result = await runHost('security', [
|
|
360
|
+
'find-generic-password',
|
|
361
|
+
'-a',
|
|
362
|
+
os.userInfo().username,
|
|
363
|
+
'-s',
|
|
364
|
+
this.service,
|
|
365
|
+
'-w',
|
|
366
|
+
]);
|
|
367
|
+
if (result.code !== 0)
|
|
368
|
+
return readJson(this.file);
|
|
369
|
+
try {
|
|
370
|
+
const parsed = JSON.parse(result.stdout.trim());
|
|
371
|
+
return parsed && typeof parsed === 'object'
|
|
372
|
+
? parsed
|
|
373
|
+
: null;
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async write(value) {
|
|
380
|
+
if (this.platform !== 'darwin') {
|
|
381
|
+
writeJsonPrivate(this.file, value);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// Through `security -i` so the token never appears in a process list.
|
|
385
|
+
const hex = Buffer.from(JSON.stringify(value)).toString('hex');
|
|
386
|
+
const quote = (text) => `"${text.replace(/["\\]/g, '\\$&')}"`;
|
|
387
|
+
const result = await runHost('security', ['-i'], {
|
|
388
|
+
input: `add-generic-password -U -a ${quote(os.userInfo().username)} -s ${quote(this.service)} -X ${hex}\n`,
|
|
389
|
+
});
|
|
390
|
+
if (result.code !== 0) {
|
|
391
|
+
throw new Error('Could not save the refreshed Claude Code login.');
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
export class ClaudeCodeHostLogin {
|
|
396
|
+
constructor(store = new ClaudeCodeLoginStore(), refresh = refreshAnthropic) {
|
|
397
|
+
this.store = store;
|
|
398
|
+
this.refresh = refresh;
|
|
399
|
+
this.refreshing = null;
|
|
400
|
+
this.status = cachedStatus(async () => {
|
|
401
|
+
const unsupported = this.unsupportedBackend();
|
|
402
|
+
if (unsupported)
|
|
403
|
+
return { ready: false, reason: unsupported };
|
|
404
|
+
if (environmentValue('ANTHROPIC_API_KEY') ||
|
|
405
|
+
environmentValue('CLAUDE_CODE_OAUTH_TOKEN')) {
|
|
406
|
+
return { ready: true };
|
|
407
|
+
}
|
|
408
|
+
const oauth = await this.readOauth();
|
|
409
|
+
return oauth?.accessToken
|
|
410
|
+
? { ready: true }
|
|
411
|
+
: { ready: false, reason: signInHint('Claude Code', 'claude') };
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
async prepare(_model, signal) {
|
|
415
|
+
const unsupported = this.unsupportedBackend();
|
|
416
|
+
if (unsupported)
|
|
417
|
+
throw new WorkAgentLoginError(unsupported);
|
|
418
|
+
// The same precedence Claude Code applies to the server's variables.
|
|
419
|
+
for (const name of ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN']) {
|
|
420
|
+
const value = environmentValue(name);
|
|
421
|
+
if (!value)
|
|
422
|
+
continue;
|
|
423
|
+
const placeholder = createEgressPlaceholder();
|
|
424
|
+
return {
|
|
425
|
+
credentials: [credential(name, placeholder, value, ANTHROPIC_HOSTS)],
|
|
426
|
+
env: { [name]: placeholder },
|
|
427
|
+
files: [],
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
const oauth = await this.fresh(signal);
|
|
431
|
+
const secret = new LiveSecret(oauth.accessToken);
|
|
432
|
+
const placeholder = createEgressPlaceholder();
|
|
433
|
+
return {
|
|
434
|
+
credentials: [
|
|
435
|
+
credential('CLAUDE_CODE_OAUTH_TOKEN', placeholder, secret, ANTHROPIC_HOSTS),
|
|
436
|
+
],
|
|
437
|
+
// The CLI's documented headless form of a subscription login.
|
|
438
|
+
env: { CLAUDE_CODE_OAUTH_TOKEN: placeholder },
|
|
439
|
+
files: [],
|
|
440
|
+
refresh: async (refreshSignal) => {
|
|
441
|
+
secret.set((await this.fresh(refreshSignal)).accessToken);
|
|
442
|
+
},
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
unsupportedBackend() {
|
|
446
|
+
for (const name of [
|
|
447
|
+
'CLAUDE_CODE_USE_BEDROCK',
|
|
448
|
+
'CLAUDE_CODE_USE_VERTEX',
|
|
449
|
+
'CLAUDE_CODE_USE_FOUNDRY',
|
|
450
|
+
]) {
|
|
451
|
+
const value = environmentValue(name);
|
|
452
|
+
if (value && value !== '0' && value.toLowerCase() !== 'false') {
|
|
453
|
+
return `Claude Code on this server is set to use a cloud provider (${name}), which Work cannot run inside a sandbox. Unset it to use the Claude login instead.`;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
async readOauth() {
|
|
459
|
+
const stored = await this.store.read();
|
|
460
|
+
const oauth = stored?.claudeAiOauth;
|
|
461
|
+
return oauth && typeof oauth === 'object' ? oauth : null;
|
|
462
|
+
}
|
|
463
|
+
/** The stored login, refreshed (single flight) when close to expiry. */
|
|
464
|
+
async fresh(signal) {
|
|
465
|
+
const oauth = await this.readOauth();
|
|
466
|
+
if (!oauth?.accessToken) {
|
|
467
|
+
throw new WorkAgentLoginError(signInHint('Claude Code', 'claude'));
|
|
468
|
+
}
|
|
469
|
+
const expiresAt = typeof oauth.expiresAt === 'number' ? oauth.expiresAt : 0;
|
|
470
|
+
if (!expiresAt || expiresAt - Date.now() > LOGIN_REFRESH_MARGIN_MS) {
|
|
471
|
+
return oauth;
|
|
472
|
+
}
|
|
473
|
+
this.refreshing ?? (this.refreshing = this.refreshStored(signal).finally(() => {
|
|
474
|
+
this.refreshing = null;
|
|
475
|
+
}));
|
|
476
|
+
return this.refreshing;
|
|
477
|
+
}
|
|
478
|
+
async refreshStored(signal) {
|
|
479
|
+
// Read again right before refreshing: the CLI may have just done it.
|
|
480
|
+
const stored = (await this.store.read()) ?? {};
|
|
481
|
+
const oauth = (stored.claudeAiOauth ?? {});
|
|
482
|
+
if (oauth.accessToken &&
|
|
483
|
+
typeof oauth.expiresAt === 'number' &&
|
|
484
|
+
oauth.expiresAt - Date.now() > LOGIN_REFRESH_MARGIN_MS) {
|
|
485
|
+
return oauth;
|
|
486
|
+
}
|
|
487
|
+
if (!oauth.refreshToken) {
|
|
488
|
+
throw new WorkAgentLoginError(expiredHint('Claude Code', 'claude'));
|
|
489
|
+
}
|
|
490
|
+
let tokens;
|
|
491
|
+
try {
|
|
492
|
+
tokens = await this.refresh(oauth.refreshToken, signal);
|
|
493
|
+
}
|
|
494
|
+
catch (error) {
|
|
495
|
+
logger.warn('Could not refresh the Claude Code login', error);
|
|
496
|
+
throw new WorkAgentLoginError(expiredHint('Claude Code', 'claude'));
|
|
497
|
+
}
|
|
498
|
+
const updated = {
|
|
499
|
+
...oauth,
|
|
500
|
+
accessToken: tokens.access,
|
|
501
|
+
refreshToken: tokens.refresh ?? oauth.refreshToken,
|
|
502
|
+
expiresAt: tokens.expiresAtMs,
|
|
503
|
+
};
|
|
504
|
+
await this.store.write({ ...stored, claudeAiOauth: updated });
|
|
505
|
+
logger.info('Refreshed the Claude Code login for a Work run.');
|
|
506
|
+
return updated;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
export class CodexHostLogin {
|
|
510
|
+
constructor(codexHome = () => environmentValue('CODEX_HOME') ?? path.join(os.homedir(), '.codex'), chatgpt = codexOAuthService) {
|
|
511
|
+
this.codexHome = codexHome;
|
|
512
|
+
this.chatgpt = chatgpt;
|
|
513
|
+
this.status = cachedStatus(async () => {
|
|
514
|
+
if (environmentValue('CODEX_API_KEY'))
|
|
515
|
+
return { ready: true };
|
|
516
|
+
const auth = this.authFile();
|
|
517
|
+
const tokens = auth?.tokens;
|
|
518
|
+
return typeof tokens?.refresh_token === 'string' ||
|
|
519
|
+
typeof auth?.OPENAI_API_KEY === 'string'
|
|
520
|
+
? { ready: true }
|
|
521
|
+
: { ready: false, reason: signInHint('Codex', 'codex login') };
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
authFile() {
|
|
525
|
+
return readJson(path.join(this.codexHome(), 'auth.json'));
|
|
526
|
+
}
|
|
527
|
+
async prepare(_model, signal) {
|
|
528
|
+
const model = this.configuredModel();
|
|
529
|
+
const withModel = model ? { model } : {};
|
|
530
|
+
const fromEnvironment = environmentValue('CODEX_API_KEY');
|
|
531
|
+
if (fromEnvironment) {
|
|
532
|
+
const placeholder = createEgressPlaceholder();
|
|
533
|
+
return {
|
|
534
|
+
credentials: [
|
|
535
|
+
credential('CODEX_API_KEY', placeholder, fromEnvironment, OPENAI_HOSTS),
|
|
536
|
+
],
|
|
537
|
+
env: { CODEX_API_KEY: placeholder },
|
|
538
|
+
files: [],
|
|
539
|
+
...withModel,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
const auth = this.authFile();
|
|
543
|
+
const tokens = auth?.tokens;
|
|
544
|
+
if (typeof tokens?.refresh_token !== 'string') {
|
|
545
|
+
const apiKey = auth?.OPENAI_API_KEY;
|
|
546
|
+
if (typeof apiKey !== 'string' || !apiKey) {
|
|
547
|
+
throw new WorkAgentLoginError(signInHint('Codex', 'codex login'));
|
|
548
|
+
}
|
|
549
|
+
const placeholder = createEgressPlaceholder();
|
|
550
|
+
return {
|
|
551
|
+
credentials: [
|
|
552
|
+
credential('OPENAI_API_KEY', placeholder, apiKey, OPENAI_HOSTS),
|
|
553
|
+
],
|
|
554
|
+
env: {},
|
|
555
|
+
files: [jsonFile('.codex/auth.json', { OPENAI_API_KEY: placeholder })],
|
|
556
|
+
...withModel,
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
let signIn;
|
|
560
|
+
try {
|
|
561
|
+
signIn = await this.chatgpt.signIn(LOGIN_REFRESH_MARGIN_MS, signal);
|
|
562
|
+
}
|
|
563
|
+
catch (error) {
|
|
564
|
+
signal?.throwIfAborted();
|
|
565
|
+
logger.warn('Could not refresh the Codex login', error);
|
|
566
|
+
throw new WorkAgentLoginError(expiredHint('Codex', 'codex login'));
|
|
567
|
+
}
|
|
568
|
+
const secret = new LiveSecret(signIn.accessToken);
|
|
569
|
+
const accessPlaceholder = placeholderFor(signIn.accessToken);
|
|
570
|
+
const accountId = signIn.accountId ??
|
|
571
|
+
(typeof tokens.account_id === 'string' ? tokens.account_id : undefined);
|
|
572
|
+
// Only what the CLI reads from its ID token: plan and account.
|
|
573
|
+
const idClaims = jwtClaims(String(tokens.id_token ?? ''));
|
|
574
|
+
const idAuth = (idClaims?.[OPENAI_AUTH_CLAIM] ?? {});
|
|
575
|
+
const idToken = `${base64url({ alg: 'none', typ: 'JWT' })}.${base64url({
|
|
576
|
+
exp: Math.floor((Date.now() + SANDBOX_VALIDITY_MS) / 1000),
|
|
577
|
+
[OPENAI_AUTH_CLAIM]: {
|
|
578
|
+
chatgpt_account_id: accountId,
|
|
579
|
+
chatgpt_plan_type: idAuth.chatgpt_plan_type,
|
|
580
|
+
},
|
|
581
|
+
})}.${createEgressPlaceholder()}`;
|
|
582
|
+
return {
|
|
583
|
+
credentials: [
|
|
584
|
+
credential('CODEX_ACCESS_TOKEN', accessPlaceholder, secret, CHATGPT_HOSTS),
|
|
585
|
+
],
|
|
586
|
+
env: {},
|
|
587
|
+
files: [
|
|
588
|
+
jsonFile('.codex/auth.json', {
|
|
589
|
+
...(typeof auth?.auth_mode === 'string'
|
|
590
|
+
? { auth_mode: auth.auth_mode }
|
|
591
|
+
: {}),
|
|
592
|
+
OPENAI_API_KEY: null,
|
|
593
|
+
tokens: {
|
|
594
|
+
id_token: idToken,
|
|
595
|
+
access_token: accessPlaceholder,
|
|
596
|
+
// Never sent anywhere the proxy rewrites: a refresh cannot work.
|
|
597
|
+
refresh_token: createEgressPlaceholder(),
|
|
598
|
+
...(accountId ? { account_id: accountId } : {}),
|
|
599
|
+
},
|
|
600
|
+
last_refresh: new Date().toISOString(),
|
|
601
|
+
}),
|
|
602
|
+
],
|
|
603
|
+
...withModel,
|
|
604
|
+
refresh: async (refreshSignal) => {
|
|
605
|
+
const next = await this.chatgpt.signIn(LOGIN_REFRESH_MARGIN_MS, refreshSignal);
|
|
606
|
+
secret.set(next.accessToken);
|
|
607
|
+
},
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/** The default model in the CLI's config, which Chat's runs pick up. */
|
|
611
|
+
configuredModel() {
|
|
612
|
+
try {
|
|
613
|
+
const config = fs.readFileSync(path.join(this.codexHome(), 'config.toml'), 'utf8');
|
|
614
|
+
// Top-level keys come before the first [table].
|
|
615
|
+
const topLevel = config.split(/^\s*\[/m)[0];
|
|
616
|
+
const match = /^\s*model\s*=\s*"([^"\n]{1,200})"\s*$/m.exec(topLevel);
|
|
617
|
+
return match?.[1];
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
return undefined;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const KIRO_SANDBOX_DB = '.local/share/kiro-cli/data.sqlite3';
|
|
625
|
+
/** state keys that never go into a sandbox copy. */
|
|
626
|
+
const KIRO_PRIVATE_STATE = /token|secret|password|credential|session|history|conversation/i;
|
|
627
|
+
function kiroExpiry(value) {
|
|
628
|
+
const raw = value.expires_at ?? value.expiresAt;
|
|
629
|
+
if (typeof raw === 'number')
|
|
630
|
+
return raw > 1e12 ? raw : raw * 1000;
|
|
631
|
+
if (typeof raw === 'string') {
|
|
632
|
+
const parsed = Date.parse(raw);
|
|
633
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
634
|
+
}
|
|
635
|
+
return 0;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Kiro keeps its login in a SQLite database. The sandbox gets a copy with
|
|
639
|
+
* the same schema, the login rows rewritten to placeholders, and nothing
|
|
640
|
+
* else of the user's: chat history, sessions, and the OAuth client
|
|
641
|
+
* registration are dropped and the file is vacuumed so no freed page
|
|
642
|
+
* carries them along.
|
|
643
|
+
*/
|
|
644
|
+
export class KiroHostLogin {
|
|
645
|
+
constructor(databasePath = () => process.platform === 'darwin'
|
|
646
|
+
? path.join(os.homedir(), 'Library', 'Application Support', 'kiro-cli', 'data.sqlite3')
|
|
647
|
+
: path.join(xdgDataHome(), 'kiro-cli', 'data.sqlite3'),
|
|
648
|
+
/** Lets Kiro refresh its own login on the host. */
|
|
649
|
+
refreshOnHost = async (signal) => {
|
|
650
|
+
const binary = resolveBinary('kiro-cli');
|
|
651
|
+
if (binary)
|
|
652
|
+
await runHost(binary, ['whoami'], { signal });
|
|
653
|
+
}) {
|
|
654
|
+
this.databasePath = databasePath;
|
|
655
|
+
this.refreshOnHost = refreshOnHost;
|
|
656
|
+
this.status = cachedStatus(async () => {
|
|
657
|
+
if (environmentValue('KIRO_API_KEY'))
|
|
658
|
+
return { ready: true };
|
|
659
|
+
return this.readTokens().length > 0
|
|
660
|
+
? { ready: true }
|
|
661
|
+
: { ready: false, reason: signInHint('Kiro', 'kiro-cli login') };
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
async prepare(_model, signal) {
|
|
665
|
+
const apiKey = environmentValue('KIRO_API_KEY');
|
|
666
|
+
if (apiKey) {
|
|
667
|
+
const placeholder = createEgressPlaceholder();
|
|
668
|
+
return {
|
|
669
|
+
credentials: [
|
|
670
|
+
credential('KIRO_API_KEY', placeholder, apiKey, KIRO_HOSTS),
|
|
671
|
+
],
|
|
672
|
+
env: { KIRO_API_KEY: placeholder },
|
|
673
|
+
files: [],
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
const tokens = await this.freshTokens(signal);
|
|
677
|
+
const secrets = new Map();
|
|
678
|
+
const placeholders = new Map();
|
|
679
|
+
for (const token of tokens) {
|
|
680
|
+
const access = String(token.value.access_token);
|
|
681
|
+
secrets.set(token.key, new LiveSecret(access));
|
|
682
|
+
placeholders.set(token.key, placeholderFor(access));
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
credentials: tokens.map(token => credential(`KIRO_LOGIN:${token.key}`, placeholders.get(token.key), secrets.get(token.key), KIRO_HOSTS)),
|
|
686
|
+
env: {},
|
|
687
|
+
files: [
|
|
688
|
+
{
|
|
689
|
+
path: KIRO_SANDBOX_DB,
|
|
690
|
+
content: await this.sandboxDatabase(placeholders),
|
|
691
|
+
},
|
|
692
|
+
],
|
|
693
|
+
refresh: async (refreshSignal) => {
|
|
694
|
+
for (const token of await this.freshTokens(refreshSignal)) {
|
|
695
|
+
secrets.get(token.key)?.set(String(token.value.access_token));
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
/** Login rows: auth_kv entries ending in `:token` with an access token. */
|
|
701
|
+
readTokens() {
|
|
702
|
+
try {
|
|
703
|
+
return readKiroLoginRows(this.databasePath()).flatMap(row => {
|
|
704
|
+
try {
|
|
705
|
+
const value = JSON.parse(row.value);
|
|
706
|
+
return typeof value.access_token === 'string' && value.access_token
|
|
707
|
+
? [{ key: row.key, value }]
|
|
708
|
+
: [];
|
|
709
|
+
}
|
|
710
|
+
catch {
|
|
711
|
+
return [];
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
catch (error) {
|
|
716
|
+
logger.warn('Could not read the Kiro login database', error);
|
|
717
|
+
return [];
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
async freshTokens(signal) {
|
|
721
|
+
const stale = (tokens) => tokens.some(token => {
|
|
722
|
+
const expiry = kiroExpiry(token.value);
|
|
723
|
+
return expiry > 0 && expiry - Date.now() < LOGIN_REFRESH_MARGIN_MS;
|
|
724
|
+
});
|
|
725
|
+
let tokens = this.readTokens();
|
|
726
|
+
if (tokens.length === 0) {
|
|
727
|
+
throw new WorkAgentLoginError(signInHint('Kiro', 'kiro-cli login'));
|
|
728
|
+
}
|
|
729
|
+
if (stale(tokens)) {
|
|
730
|
+
await this.refreshOnHost(signal);
|
|
731
|
+
signal?.throwIfAborted();
|
|
732
|
+
tokens = this.readTokens();
|
|
733
|
+
if (tokens.length === 0 || stale(tokens)) {
|
|
734
|
+
throw new WorkAgentLoginError(expiredHint('Kiro', 'kiro-cli login'));
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return tokens;
|
|
738
|
+
}
|
|
739
|
+
/** The login rows become placeholders; every other auth_kv row goes. */
|
|
740
|
+
sandboxDatabase(placeholders) {
|
|
741
|
+
return scrubbedKiroDatabase(this.databasePath(), (key, raw) => {
|
|
742
|
+
const placeholder = placeholders.get(key);
|
|
743
|
+
if (!placeholder)
|
|
744
|
+
return null;
|
|
745
|
+
const value = JSON.parse(raw);
|
|
746
|
+
const expiresAt = new Date(Date.now() + SANDBOX_VALIDITY_MS);
|
|
747
|
+
const rewritten = {
|
|
748
|
+
...value,
|
|
749
|
+
access_token: placeholder,
|
|
750
|
+
refresh_token: createEgressPlaceholder(),
|
|
751
|
+
};
|
|
752
|
+
delete rewritten.client_secret;
|
|
753
|
+
if ('expires_at' in value) {
|
|
754
|
+
rewritten.expires_at =
|
|
755
|
+
typeof value.expires_at === 'number'
|
|
756
|
+
? Math.floor(expiresAt.getTime() / 1000)
|
|
757
|
+
: expiresAt.toISOString();
|
|
758
|
+
}
|
|
759
|
+
return JSON.stringify(rewritten);
|
|
760
|
+
}, KIRO_PRIVATE_STATE);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* The shared shape of OpenCode's and Pi's logins: one auth file, one entry
|
|
765
|
+
* per provider, either a key or an OAuth login with `access`, `refresh`,
|
|
766
|
+
* and `expires`.
|
|
767
|
+
*/
|
|
768
|
+
class ProviderAuthFileLogin {
|
|
769
|
+
constructor(options, authPath, refreshers = PROVIDER_REFRESH) {
|
|
770
|
+
this.options = options;
|
|
771
|
+
this.authPath = authPath;
|
|
772
|
+
this.refreshers = refreshers;
|
|
773
|
+
this.refreshing = new Map();
|
|
774
|
+
}
|
|
775
|
+
authFile() {
|
|
776
|
+
return (readJson(this.authPath()) ?? {});
|
|
777
|
+
}
|
|
778
|
+
hasAnyLogin() {
|
|
779
|
+
if (Object.keys(this.authFile()).length > 0)
|
|
780
|
+
return true;
|
|
781
|
+
return Object.values(PROVIDER_KEY_VARIABLES).some(names => names.some(name => environmentValue(name)));
|
|
782
|
+
}
|
|
783
|
+
/** The sandbox login for one provider, with its auth file entry. */
|
|
784
|
+
async providerLogin(provider, signal) {
|
|
785
|
+
const { cli, loginCommand } = this.options;
|
|
786
|
+
const hosts = WORK_AGENT_PROVIDER_HOSTS[provider];
|
|
787
|
+
const entry = this.authFile()[provider];
|
|
788
|
+
if (!hosts) {
|
|
789
|
+
throw new WorkAgentLoginError(`${cli}'s "${provider}" provider cannot run in Work yet: Libre WebUI does not know which API hosts its login may be sent to.`);
|
|
790
|
+
}
|
|
791
|
+
if (!entry) {
|
|
792
|
+
for (const name of PROVIDER_KEY_VARIABLES[provider] ?? []) {
|
|
793
|
+
const value = environmentValue(name);
|
|
794
|
+
if (!value)
|
|
795
|
+
continue;
|
|
796
|
+
const placeholder = createEgressPlaceholder();
|
|
797
|
+
return {
|
|
798
|
+
credentials: [credential(name, placeholder, value, hosts)],
|
|
799
|
+
env: { [name]: placeholder },
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
throw new WorkAgentLoginError(`${cli} has no login for "${provider}" on this server. Run \`${loginCommand}\` as the server user, then try again.`);
|
|
803
|
+
}
|
|
804
|
+
if (entry.type === this.options.apiType && typeof entry.key === 'string') {
|
|
805
|
+
const placeholder = createEgressPlaceholder();
|
|
806
|
+
return {
|
|
807
|
+
credentials: [credential(provider, placeholder, entry.key, hosts)],
|
|
808
|
+
env: {},
|
|
809
|
+
entry: { type: entry.type, key: placeholder },
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
if (entry.type === 'oauth' && typeof entry.access === 'string') {
|
|
813
|
+
const fresh = await this.freshOauth(provider, signal);
|
|
814
|
+
const secret = new LiveSecret(String(fresh.access));
|
|
815
|
+
const placeholder = placeholderFor(String(fresh.access));
|
|
816
|
+
const sandboxEntry = { ...fresh };
|
|
817
|
+
sandboxEntry.access = placeholder;
|
|
818
|
+
sandboxEntry.refresh = createEgressPlaceholder();
|
|
819
|
+
sandboxEntry.expires = Date.now() + SANDBOX_VALIDITY_MS;
|
|
820
|
+
return {
|
|
821
|
+
credentials: [credential(provider, placeholder, secret, hosts)],
|
|
822
|
+
env: {},
|
|
823
|
+
entry: sandboxEntry,
|
|
824
|
+
refresh: async (refreshSignal) => {
|
|
825
|
+
const next = await this.freshOauth(provider, refreshSignal);
|
|
826
|
+
secret.set(String(next.access));
|
|
827
|
+
},
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
throw new WorkAgentLoginError(`${cli}'s "${provider}" login is a kind Work cannot carry into a sandbox yet.`);
|
|
831
|
+
}
|
|
832
|
+
freshOauth(provider, signal) {
|
|
833
|
+
const entry = this.authFile()[provider];
|
|
834
|
+
const expires = typeof entry?.expires === 'number' ? entry.expires : 0;
|
|
835
|
+
if (entry && expires - Date.now() > LOGIN_REFRESH_MARGIN_MS) {
|
|
836
|
+
return Promise.resolve(entry);
|
|
837
|
+
}
|
|
838
|
+
let flight = this.refreshing.get(provider);
|
|
839
|
+
if (!flight) {
|
|
840
|
+
flight = this.refreshEntry(provider, signal).finally(() => {
|
|
841
|
+
this.refreshing.delete(provider);
|
|
842
|
+
});
|
|
843
|
+
this.refreshing.set(provider, flight);
|
|
844
|
+
}
|
|
845
|
+
return flight;
|
|
846
|
+
}
|
|
847
|
+
async refreshEntry(provider, signal) {
|
|
848
|
+
const { cli, loginCommand } = this.options;
|
|
849
|
+
const expired = new WorkAgentLoginError(`${cli}'s "${provider}" login on this server has expired and could not be refreshed. Run \`${loginCommand}\` as the server user, then try again.`);
|
|
850
|
+
const refresh = this.refreshers[provider];
|
|
851
|
+
const entry = this.authFile()[provider];
|
|
852
|
+
if (!refresh || !entry || typeof entry.refresh !== 'string')
|
|
853
|
+
throw expired;
|
|
854
|
+
let tokens;
|
|
855
|
+
try {
|
|
856
|
+
tokens = await refresh(entry.refresh, signal);
|
|
857
|
+
}
|
|
858
|
+
catch (error) {
|
|
859
|
+
logger.warn(`Could not refresh ${cli}'s ${provider} login`, error);
|
|
860
|
+
throw expired;
|
|
861
|
+
}
|
|
862
|
+
const updated = {
|
|
863
|
+
...entry,
|
|
864
|
+
access: tokens.access,
|
|
865
|
+
refresh: tokens.refresh ?? entry.refresh,
|
|
866
|
+
expires: tokens.expiresAtMs,
|
|
867
|
+
};
|
|
868
|
+
// Re-read so a login the CLI changed meanwhile is not overwritten.
|
|
869
|
+
const latest = this.authFile();
|
|
870
|
+
writeJsonPrivate(this.authPath(), { ...latest, [provider]: updated });
|
|
871
|
+
logger.info(`Refreshed ${cli}'s ${provider} login for a Work run.`);
|
|
872
|
+
return updated;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
/** OpenCode: one auth file for every provider it is signed in to. */
|
|
876
|
+
export class OpenCodeHostLogin extends ProviderAuthFileLogin {
|
|
877
|
+
constructor(authPath = () => path.join(xdgDataHome(), 'opencode', 'auth.json'), refreshers) {
|
|
878
|
+
super({
|
|
879
|
+
cli: 'OpenCode',
|
|
880
|
+
loginCommand: 'opencode auth login',
|
|
881
|
+
sandboxAuthFile: '.local/share/opencode/auth.json',
|
|
882
|
+
apiType: 'api',
|
|
883
|
+
}, authPath, refreshers);
|
|
884
|
+
this.status = cachedStatus(async () => this.hasAnyLogin()
|
|
885
|
+
? { ready: true }
|
|
886
|
+
: {
|
|
887
|
+
ready: false,
|
|
888
|
+
reason: signInHint('OpenCode', 'opencode auth login'),
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
async prepare(model, signal) {
|
|
892
|
+
const provider = model?.split('/')[0];
|
|
893
|
+
if (!provider || !model?.includes('/')) {
|
|
894
|
+
throw new WorkAgentLoginError('OpenCode in Work needs a model chosen as provider/model.');
|
|
895
|
+
}
|
|
896
|
+
const login = await this.providerLogin(provider, signal);
|
|
897
|
+
return {
|
|
898
|
+
credentials: login.credentials,
|
|
899
|
+
env: login.env,
|
|
900
|
+
files: login.entry
|
|
901
|
+
? [jsonFile(this.options.sandboxAuthFile, { [provider]: login.entry })]
|
|
902
|
+
: [],
|
|
903
|
+
...(login.refresh ? { refresh: login.refresh } : {}),
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Pi: an auth file beside its settings. Chat runs Pi on its configured
|
|
909
|
+
* default model, and so does Work, unless a provider/model is chosen.
|
|
910
|
+
*/
|
|
911
|
+
export class PiHostLogin extends ProviderAuthFileLogin {
|
|
912
|
+
constructor(agentDir = () => environmentValue('PI_CODING_AGENT_DIR') ??
|
|
913
|
+
path.join(os.homedir(), '.pi', 'agent'), refreshers) {
|
|
914
|
+
super({
|
|
915
|
+
cli: 'Pi',
|
|
916
|
+
loginCommand: 'pi',
|
|
917
|
+
sandboxAuthFile: '.pi/agent/auth.json',
|
|
918
|
+
apiType: 'api_key',
|
|
919
|
+
}, () => path.join(agentDir(), 'auth.json'), refreshers);
|
|
920
|
+
this.agentDir = agentDir;
|
|
921
|
+
this.status = cachedStatus(async () => this.hasAnyLogin()
|
|
922
|
+
? { ready: true }
|
|
923
|
+
: { ready: false, reason: signInHint('Pi', 'pi') });
|
|
924
|
+
}
|
|
925
|
+
async prepare(model, signal) {
|
|
926
|
+
let provider;
|
|
927
|
+
let modelId;
|
|
928
|
+
if (model?.includes('/')) {
|
|
929
|
+
[provider] = model.split('/');
|
|
930
|
+
modelId = model.slice(provider.length + 1) || undefined;
|
|
931
|
+
}
|
|
932
|
+
else {
|
|
933
|
+
const settings = readJson(path.join(this.agentDir(), 'settings.json'));
|
|
934
|
+
if (typeof settings?.defaultProvider === 'string') {
|
|
935
|
+
provider = settings.defaultProvider;
|
|
936
|
+
modelId =
|
|
937
|
+
model ??
|
|
938
|
+
(typeof settings.defaultModel === 'string'
|
|
939
|
+
? settings.defaultModel
|
|
940
|
+
: undefined);
|
|
941
|
+
}
|
|
942
|
+
else {
|
|
943
|
+
// Pi picks a provider it has a login for; so does Work.
|
|
944
|
+
provider = Object.keys(this.authFile()).find(name => WORK_AGENT_PROVIDER_HOSTS[name]);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
if (!provider) {
|
|
948
|
+
throw new WorkAgentLoginError(signInHint('Pi', 'pi'));
|
|
949
|
+
}
|
|
950
|
+
const login = await this.providerLogin(provider, signal);
|
|
951
|
+
return {
|
|
952
|
+
credentials: login.credentials,
|
|
953
|
+
env: login.env,
|
|
954
|
+
files: [
|
|
955
|
+
...(login.entry
|
|
956
|
+
? [
|
|
957
|
+
jsonFile(this.options.sandboxAuthFile, {
|
|
958
|
+
[provider]: login.entry,
|
|
959
|
+
}),
|
|
960
|
+
]
|
|
961
|
+
: []),
|
|
962
|
+
jsonFile('.pi/agent/settings.json', {
|
|
963
|
+
defaultProvider: provider,
|
|
964
|
+
...(modelId ? { defaultModel: modelId } : {}),
|
|
965
|
+
}),
|
|
966
|
+
],
|
|
967
|
+
model: modelId ? `${provider}/${modelId}` : `${provider}/`,
|
|
968
|
+
...(login.refresh ? { refresh: login.refresh } : {}),
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
/** The host login behind each agent CLI Work can run. */
|
|
973
|
+
export function createWorkAgentHostLogins() {
|
|
974
|
+
return {
|
|
975
|
+
'claude-code': new ClaudeCodeHostLogin(),
|
|
976
|
+
codex: new CodexHostLogin(),
|
|
977
|
+
kiro: new KiroHostLogin(),
|
|
978
|
+
opencode: new OpenCodeHostLogin(),
|
|
979
|
+
pi: new PiHostLogin(),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
//# sourceMappingURL=workAgentHostLogins.js.map
|