grix-connector 3.17.1 → 3.19.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/README.md +28 -0
- package/dist/adapter/acp/acp-adapter.js +15 -14
- package/dist/adapter/claude/claude-adapter.js +21 -21
- package/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/codex/codex-bridge.js +8 -8
- package/dist/adapter/codex/codex-trust.js +4 -4
- package/dist/adapter/codex/config-overrides.js +1 -0
- package/dist/adapter/codex/raw-capture-hook.js +1 -0
- package/dist/adapter/opencode/opencode-adapter.js +3 -3
- package/dist/adapter/opencode/opencode-transport.js +4 -4
- package/dist/adapter/openhuman/openhuman-adapter.js +2 -2
- package/dist/adapter/pi/pi-adapter.js +1 -1
- package/dist/audit/adapters/codex/codex-audit-adapter.js +1 -1
- package/dist/audit/core/audit-options.js +1 -1
- package/dist/audit/core/audit-session-registry.js +3 -3
- package/dist/audit/core/replay-finalizer.js +1 -1
- package/dist/audit/integration/bridge-audit-controller.js +1 -1
- package/dist/audit/query/audit-local-actions.js +1 -1
- package/dist/audit/raw-capture/adapter-hook.js +0 -0
- package/dist/audit/raw-capture/attribution.js +2 -0
- package/dist/audit/raw-capture/body-source.js +1 -0
- package/dist/audit/raw-capture/capture-relay.js +13 -0
- package/dist/audit/raw-capture/redaction.js +1 -0
- package/dist/audit/raw-capture/types.js +1 -0
- package/dist/audit/storage/file-audit-replay-store.js +2 -2
- package/dist/audit/worker/audit-recorder-worker-entry.js +1 -1
- package/dist/bridge/bridge.js +9 -9
- package/dist/bridge/send-controller.js +3 -3
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/aibot/connection-handle.js +1 -1
- package/dist/core/files/file-serve.js +2 -2
- package/dist/core/log/packet-log.js +2 -2
- package/dist/core/mcp/tools.js +1 -1
- package/dist/core/persistence/session-binding-store.js +1 -1
- package/dist/core/persistence/stop-result-outbox.js +2 -0
- package/dist/core/persistence/terminal-commit-token-store.js +2 -0
- package/dist/core/persistence/terminal-outbox.js +2 -0
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/kiro.js +1 -1
- package/dist/core/provider-quota/openai-codex.js +2 -0
- package/dist/core/provider-quota/presentation.js +1 -1
- package/dist/core/provider-quota/providers.js +2 -2
- package/dist/core/proxy/relay-state-sync.js +1 -0
- package/dist/default-skills/grix-agent-dispatch/SKILL.md +17 -14
- package/dist/default-skills/grix-audit-data/SKILL.md +4 -2
- package/dist/default-skills/grix-chat-state/SKILL.md +11 -3
- package/dist/default-skills/grix-query/SKILL.md +4 -2
- package/dist/default-skills/index.js +1 -1
- package/dist/grix.js +7 -7
- package/dist/kimi-plugins/grix-layer/SKILL.md +68 -0
- package/dist/kimi-plugins/grix-layer/SYSTEM.md +16 -0
- package/dist/kimi-plugins/grix-layer/kimi.plugin.json +10 -0
- package/dist/kimi-plugins/grix-layer/references/gateway-architecture.md +153 -0
- package/dist/kimi-plugins/grix-layer/scripts/gateway.mjs +31 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/architecture-map.mjs +305 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/downstream-client.mjs +133 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/navigation-service.mjs +762 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/normalizers.mjs +202 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/policy.mjs +78 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/response-budget.mjs +83 -0
- package/dist/kimi-plugins/grix-layer/scripts/lib/tool-server.mjs +106 -0
- package/dist/kimi-plugins/index.js +3 -0
- package/dist/manager-share-config.js +1 -1
- package/dist/manager.js +2 -2
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/service/service-manager.js +3 -3
- package/openclaw-plugin/index.js +56 -36
- package/openclaw-plugin/skills/grix-query/SKILL.md +6 -2
- package/package.json +8 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as
|
|
1
|
+
import{readJSONFile as a,writeJSONFileAtomic as g}from"../util/json-file.js";import{log as l}from"../log/index.js";import{SESSION_MODE_IDS as s}from"../../adapter/claude/protocol-contract.js";const c=s.fullAuto;function n(r){const e=String(r??"").trim().toLowerCase();return e===s.approval||e===s.fullAuto?e:c}class x{bindings=new Map;filePath;writePromise=Promise.resolve();constructor(e){this.filePath=e??null}load(){if(!this.filePath)return;const e=a(this.filePath);if(Array.isArray(e)){this.bindings.clear();for(const d of e)d.aibotSessionId&&this.bindings.set(d.aibotSessionId,{...d,modeId:n(d.modeId)})}}set(e,d,t){const i=this.bindings.get(e),o=n(t?.modeId??i?.modeId);this.bindings.set(e,{aibotSessionId:e,cwd:d,acpSessionId:i?.acpSessionId,claudeSessionId:i?.claudeSessionId,codexThreadId:i?.codexThreadId,codexModelId:i?.codexModelId,codexModeId:i?.codexModeId,codewhaleThreadId:i?.codewhaleThreadId,agyConversationId:i?.agyConversationId,codexReasoningEffort:i?.codexReasoningEffort,codexServiceTier:i?.codexServiceTier,codexSandboxMode:i?.codexSandboxMode,piSessionPath:i?.piSessionPath,modeId:o,modelId:i?.modelId,cursorModeId:i?.cursorModeId,acpModelId:i?.acpModelId,acpModeId:i?.acpModeId,updatedAt:Date.now()}),this.scheduleWrite()}setAcpSessionId(e,d){this.updateBinding(e,{acpSessionId:d})}setClaudeSessionId(e,d){this.updateBinding(e,{claudeSessionId:d})}getClaudeSessionId(e){return this.bindings.get(e)?.claudeSessionId}setCodexThreadId(e,d){this.updateBinding(e,{codexThreadId:d})}getCodexThreadId(e){return this.bindings.get(e)?.codexThreadId}setAgyConversationId(e,d){this.updateBinding(e,{agyConversationId:d})}getAgyConversationId(e){return this.bindings.get(e)?.agyConversationId}setCodexContext(e,d){this.updateBinding(e,{codexModelId:d.modelId,codexModeId:d.modeId,codexReasoningEffort:d.reasoningEffort,codexServiceTier:d.serviceTier,codexSandboxMode:d.sandboxMode})}getCodexModelId(e){return this.bindings.get(e)?.codexModelId}setCodexModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim();!i||t.codexModelId===i||(this.bindings.set(e,{...t,codexModelId:i,updatedAt:Date.now()}),this.scheduleWrite())}setCodexModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim();!i||t.codexModeId===i||(this.bindings.set(e,{...t,codexModeId:i,updatedAt:Date.now()}),this.scheduleWrite())}setCodexServiceTier(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim();!i||t.codexServiceTier===i||(this.bindings.set(e,{...t,codexServiceTier:i,updatedAt:Date.now()}),this.scheduleWrite())}getCodexModeId(e){return this.bindings.get(e)?.codexModeId}getCodexReasoningEffort(e){return this.bindings.get(e)?.codexReasoningEffort}getCodexServiceTier(e){return this.bindings.get(e)?.codexServiceTier}getCodexSandboxMode(e){return this.bindings.get(e)?.codexSandboxMode}setPiSessionPath(e,d){this.updateBinding(e,{piSessionPath:d})}getPiSessionPath(e){return this.bindings.get(e)?.piSessionPath}setCodeWhaleThreadId(e,d){this.updateBinding(e,{codewhaleThreadId:d})}getCodeWhaleThreadId(e){return this.bindings.get(e)?.codewhaleThreadId}setModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=n(d);t.modeId!==i&&(this.bindings.set(e,{...t,modeId:i,updatedAt:Date.now()}),this.scheduleWrite())}ensureModeId(e,d=c){const t=this.bindings.get(e);t&&(t.modeId||(this.bindings.set(e,{...t,modeId:n(d),updatedAt:Date.now()}),this.scheduleWrite()))}getAcpSessionId(e){return this.bindings.get(e)?.acpSessionId}getModeId(e){const d=this.bindings.get(e)?.modeId;return d?n(d):void 0}setModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=d.trim();t.modelId!==i&&(this.bindings.set(e,{...t,modelId:i,updatedAt:Date.now()}),this.scheduleWrite())}getModelId(e){return this.bindings.get(e)?.modelId}setCursorModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim().toLowerCase(),o=i===""?void 0:i;t.cursorModeId!==o&&(this.bindings.set(e,{...t,cursorModeId:o,updatedAt:Date.now()}),this.scheduleWrite())}getCursorModeId(e){return this.bindings.get(e)?.cursorModeId}setAcpModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModelId!==o&&(this.bindings.set(e,{...t,acpModelId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModelId(e){return this.bindings.get(e)?.acpModelId}setAcpModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModeId!==o&&(this.bindings.set(e,{...t,acpModeId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModeId(e){return this.bindings.get(e)?.acpModeId}get(e){return this.bindings.get(e)}getMostRecentlyUpdatedSessionId(e){const d=e?.requireCwd!==!1;let t,i=-1;for(const o of this.bindings.values())d&&!String(o.cwd??"").trim()||o.updatedAt>i&&(i=o.updatedAt,t=o.aibotSessionId);return t}delete(e){this.bindings.delete(e),this.scheduleWrite()}entries(){return this.bindings.entries()}async flush(){await this.writePromise}scheduleWrite(){this.filePath&&(this.writePromise=this.writePromise.then(()=>this.write()).catch(e=>{l.error("session-binding-store",`Persist failed: ${e instanceof Error?e.message:e}`)}))}async write(){if(!this.filePath)return;const e=Array.from(this.bindings.values());await g(this.filePath,e)}updateBinding(e,d){const t=this.bindings.get(e),i={aibotSessionId:e,acpSessionId:Object.prototype.hasOwnProperty.call(d,"acpSessionId")?d.acpSessionId:t?.acpSessionId,claudeSessionId:Object.prototype.hasOwnProperty.call(d,"claudeSessionId")?d.claudeSessionId:t?.claudeSessionId,codexThreadId:Object.prototype.hasOwnProperty.call(d,"codexThreadId")?d.codexThreadId:t?.codexThreadId,codexModelId:Object.prototype.hasOwnProperty.call(d,"codexModelId")?d.codexModelId:t?.codexModelId,codexModeId:Object.prototype.hasOwnProperty.call(d,"codexModeId")?d.codexModeId:t?.codexModeId,codewhaleThreadId:Object.prototype.hasOwnProperty.call(d,"codewhaleThreadId")?d.codewhaleThreadId:t?.codewhaleThreadId,agyConversationId:Object.prototype.hasOwnProperty.call(d,"agyConversationId")?d.agyConversationId:t?.agyConversationId,codexReasoningEffort:Object.prototype.hasOwnProperty.call(d,"codexReasoningEffort")?d.codexReasoningEffort:t?.codexReasoningEffort,codexServiceTier:Object.prototype.hasOwnProperty.call(d,"codexServiceTier")?d.codexServiceTier:t?.codexServiceTier,codexSandboxMode:Object.prototype.hasOwnProperty.call(d,"codexSandboxMode")?d.codexSandboxMode:t?.codexSandboxMode,piSessionPath:Object.prototype.hasOwnProperty.call(d,"piSessionPath")?d.piSessionPath:t?.piSessionPath,cwd:t?.cwd,modeId:n(t?.modeId),modelId:t?.modelId,cursorModeId:t?.cursorModeId,acpModelId:t?.acpModelId,acpModeId:t?.acpModeId,updatedAt:Date.now()};this.bindings.set(e,i),this.scheduleWrite()}}export{x as SessionBindingStore};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{chmodSync as g,closeSync as d,existsSync as _,fsyncSync as c,mkdirSync as k,openSync as l,readFileSync as w,renameSync as A,unlinkSync as u,writeFileSync as b}from"node:fs";import{randomUUID as v}from"node:crypto";import{dirname as p}from"node:path";const h=1;function m(o){return`${o.event_id?.trim()??""}\0${o.stop_id.trim()}`}function a(o){return{...o,payload:{...o.payload}}}function f(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;const t=o;return!!(t.event_id?.trim()&&t.stop_id?.trim()&&t.terminal_commit_token?.trim()&&(t.status==="stopped"||t.status==="already_finished"))}class x{filePath;pending=new Map;constructor(t){this.filePath=t,this.load()}enqueue(t){if(!f(t))throw new Error("stop result outbox requires event_id, stop_id, terminal token, and valid status");const i={...t,event_id:t.event_id.trim(),stop_id:t.stop_id.trim(),terminal_commit_token:t.terminal_commit_token.trim()},n=m(i),r=this.pending.get(n);if(r){if(r.payload.status!==i.status||r.payload.terminal_commit_token!==i.terminal_commit_token)throw new Error(`stop result changed for event=${i.event_id} stop=${i.stop_id}`);return a(r)}const e=Date.now(),s={key:n,payload:i,generation:1,createdAt:e,updatedAt:e,attempts:0,nextAttemptAt:0};this.pending.set(n,s);try{this.persist()}catch(y){throw this.pending.delete(n),y}return a(s)}listPending(){return[...this.pending.values()].map(a)}isCurrent(t){const i=this.pending.get(t.key);return i?.generation===t.generation&&i.payload.status===t.payload.status&&i.payload.terminal_commit_token===t.payload.terminal_commit_token}acknowledge(t,i,n,r){if(i?.trim()!==t.payload.event_id||n?.trim()!==t.payload.terminal_commit_token||r!==!0||!this.isCurrent(t))return!1;const e=this.pending.get(t.key);this.pending.delete(t.key);try{this.persist()}catch(s){throw this.pending.set(t.key,e),s}return!0}recordRetry(t,i,n){const r=this.pending.get(t.key);if(!r||r.generation!==t.generation)return!1;const e=a(r);r.attempts+=1,r.updatedAt=Date.now(),r.nextAttemptAt=i,r.lastError=n;try{this.persist()}catch(s){throw this.pending.set(t.key,e),s}return!0}discard(t){const i=this.pending.get(t.key);if(!i||i.generation!==t.generation)return!1;this.pending.delete(t.key);try{this.persist()}catch(n){throw this.pending.set(t.key,i),n}return!0}load(){if(!this.filePath||!_(this.filePath))return;let t;try{t=JSON.parse(w(this.filePath,"utf8"))}catch(n){throw new Error(`stop result outbox load failed: ${n instanceof Error?n.message:n}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("stop result outbox load failed: invalid root");const i=t;if(i.version!==h||!i.pending||typeof i.pending!="object"||Array.isArray(i.pending))throw new Error("stop result outbox load failed: unsupported or invalid file");for(const[n,r]of Object.entries(i.pending)){if(!r||typeof r!="object")continue;const e=r;!f(e.payload)||n!==e.key||n!==m(e.payload)||this.pending.set(n,{key:n,payload:{...e.payload},generation:Number.isInteger(e.generation)&&e.generation>0?e.generation:1,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),updatedAt:Number.isFinite(e.updatedAt)?e.updatedAt:Date.now(),attempts:Number.isInteger(e.attempts)&&e.attempts>=0?e.attempts:0,nextAttemptAt:Number.isFinite(e.nextAttemptAt)?e.nextAttemptAt:0,...typeof e.lastError=="string"?{lastError:e.lastError}:{}})}}persist(){if(!this.filePath)return;if(this.pending.size===0){try{u(this.filePath);const r=l(p(this.filePath),"r");try{c(r)}finally{d(r)}}catch(r){if(r.code!=="ENOENT")throw r}return}const t=Object.create(null);for(const[r,e]of this.pending)t[r]=a(e);const i={version:h,pending:t};k(p(this.filePath),{recursive:!0,mode:448});const n=`${this.filePath}.${v()}.tmp`;try{b(n,`${JSON.stringify(i,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"});const r=l(n,"r");try{c(r)}finally{d(r)}A(n,this.filePath);const e=l(p(this.filePath),"r");try{c(e)}finally{d(e)}try{g(this.filePath,384)}catch{}}finally{try{u(n)}catch{}}}}export{x as StopResultOutbox};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{chmodSync as m,closeSync as n,existsSync as d,fsyncSync as s,mkdirSync as y,openSync as a,readFileSync as k,renameSync as p,unlinkSync as h,writeFileSync as u}from"node:fs";import{randomUUID as w}from"node:crypto";import{dirname as c}from"node:path";const l=1;class v{filePath;tokens=new Map;constructor(r){this.filePath=r,this.load()}get(r){return this.tokens.get(r)}register(r,i){const t=r.trim(),e=i.trim();if(!t||!e)throw new Error("terminal commit token requires non-empty event_id and token");const o=this.tokens.get(t);if(o!==e){if(o)throw new Error(`terminal commit token changed for event=${t}`);this.tokens.set(t,e);try{this.persist()}catch(f){throw this.tokens.delete(t),f}}}remove(r,i){const t=this.tokens.get(r);if(!t||t!==i)return!1;this.tokens.delete(r);try{this.persist()}catch(e){throw this.tokens.set(r,t),e}return!0}load(){if(!this.filePath||!d(this.filePath))return;let r;try{r=JSON.parse(k(this.filePath,"utf8"))}catch(t){throw new Error(`terminal commit token store load failed: ${t instanceof Error?t.message:t}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("terminal commit token store load failed: invalid root");const i=r;if(i.version!==l||!i.tokens||typeof i.tokens!="object"||Array.isArray(i.tokens))throw new Error("terminal commit token store load failed: unsupported or invalid file");for(const[t,e]of Object.entries(i.tokens))t.trim()&&typeof e=="string"&&e.trim()&&this.tokens.set(t,e)}persist(){if(!this.filePath)return;if(this.tokens.size===0){try{h(this.filePath);const e=a(c(this.filePath),"r");try{s(e)}finally{n(e)}}catch(e){if(e.code!=="ENOENT")throw e}return}const r=Object.create(null);for(const[e,o]of this.tokens)r[e]=o;const i={version:l,tokens:r};y(c(this.filePath),{recursive:!0,mode:448});const t=`${this.filePath}.${w()}.tmp`;try{u(t,`${JSON.stringify(i,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"});const e=a(t,"r");try{s(e)}finally{n(e)}p(t,this.filePath);const o=a(c(this.filePath),"r");try{s(o)}finally{n(o)}try{m(this.filePath,384)}catch{}}finally{try{h(t)}catch{}}}}export{v as TerminalCommitTokenStore};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{chmodSync as v,closeSync as c,existsSync as A,fsyncSync as u,mkdirSync as _,openSync as h,readFileSync as w,renameSync as S,unlinkSync as b,writeFileSync as L}from"node:fs";import{randomUUID as D}from"node:crypto";import{dirname as f}from"node:path";const y=1,g=1e3;function l(s){return{...s}}function o(s){return{...s,payload:l(s.payload)}}function p(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.event_id=="string"&&e.event_id.length>0&&(e.status==="responded"||e.status==="failed"||e.status==="canceled")}class F{filePath;pending=new Map;deadLetters=[];constructor(e){this.filePath=e,this.load()}enqueue(e){if(!p(e))throw new Error("terminal outbox requires a non-empty event_id and terminal status");const t=this.pending.get(e.event_id),r=Date.now(),i={payload:l(e),generation:(t?.generation??0)+1,createdAt:t?.createdAt??r,updatedAt:r,attempts:0,nextAttemptAt:0};this.pending.set(e.event_id,i);try{this.persist()}catch(n){throw t?this.pending.set(e.event_id,t):this.pending.delete(e.event_id),n}return o(i)}get(e){const t=this.pending.get(e);return t?o(t):void 0}listPending(){return[...this.pending.values()].map(o)}listDeadLetters(){return this.deadLetters.map(e=>({...e,payload:l(e.payload)}))}isCurrent(e){const t=this.pending.get(e.payload.event_id);return t?.generation===e.generation&&t.payload.status===e.payload.status}markDeliveryStarted(e){const t=this.pending.get(e.payload.event_id);if(!t||t.generation!==e.generation)return;if(t.deliveryStartedAt)return o(t);const r=o(t);t.deliveryStartedAt=Date.now(),t.updatedAt=t.deliveryStartedAt;try{this.persist()}catch(i){throw this.pending.set(e.payload.event_id,r),i}return o(t)}acknowledge(e,t,r,i,n){if(t!==e.payload.event_id||r!==e.payload.status)return!1;const a=e.payload.terminal_commit_token?.trim();if(a&&(i?.trim()!==a||n!==!0))return!1;const d=this.pending.get(e.payload.event_id);if(!d||d.generation!==e.generation||d.payload.status!==e.payload.status||d.payload.terminal_commit_token?.trim()!==a)return!1;this.pending.delete(e.payload.event_id);try{this.persist()}catch(m){throw this.pending.set(e.payload.event_id,d),m}return!0}recordRetry(e,t,r){const i=this.pending.get(e.payload.event_id);if(!i||i.generation!==e.generation)return!1;const n=o(i);i.attempts+=1,i.updatedAt=Date.now(),i.nextAttemptAt=t,i.lastError=r;try{this.persist()}catch(a){throw this.pending.set(e.payload.event_id,n),a}return!0}moveToDeadLetter(e,t){const r=this.pending.get(e.payload.event_id);if(!r||r.generation!==e.generation)return!1;const i={payload:l(r.payload),rejectedAt:Date.now(),responseCmd:t.responseCmd,code:t.code,message:t.message},n=this.deadLetters;this.pending.delete(e.payload.event_id),this.deadLetters=[...this.deadLetters,i].slice(-g);try{this.persist()}catch(a){throw this.pending.set(e.payload.event_id,r),this.deadLetters=n,a}return!0}load(){if(!this.filePath||!A(this.filePath))return;let e;try{e=JSON.parse(w(this.filePath,"utf8"))}catch(r){throw new Error(`terminal outbox load failed: ${r instanceof Error?r.message:r}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("terminal outbox load failed: invalid root");const t=e;if(t.version!==y||!t.pending||typeof t.pending!="object"||Array.isArray(t.pending))throw new Error("terminal outbox load failed: unsupported or invalid file");for(const[r,i]of Object.entries(t.pending)){if(!i||typeof i!="object")continue;const n=i;if(r!==n.payload?.event_id||!p(n.payload))continue;const a=Number.isFinite(n.deliveryStartedAt)&&n.deliveryStartedAt>0?n.deliveryStartedAt:void 0,d=n.payload.code==="agent_output_unconfirmed"?a??(Number.isFinite(n.updatedAt)?n.updatedAt:Date.now()):a;this.pending.set(r,{payload:l(n.payload),generation:Number.isInteger(n.generation)&&n.generation>0?n.generation:1,createdAt:Number.isFinite(n.createdAt)?n.createdAt:Date.now(),updatedAt:Number.isFinite(n.updatedAt)?n.updatedAt:Date.now(),attempts:Number.isInteger(n.attempts)&&n.attempts>=0?n.attempts:0,nextAttemptAt:Number.isFinite(n.nextAttemptAt)?n.nextAttemptAt:0,...d?{deliveryStartedAt:d}:{},...typeof n.lastError=="string"?{lastError:n.lastError}:{}})}Array.isArray(t.deadLetters)&&(this.deadLetters=t.deadLetters.filter(r=>!!r&&p(r.payload)&&(r.responseCmd==="send_nack"||r.responseCmd==="error")).slice(-g).map(r=>({...r,payload:l(r.payload)})))}persist(){if(!this.filePath)return;const e=Object.create(null);for(const[i,n]of this.pending)e[i]=o(n);const t={version:y,pending:e,deadLetters:this.listDeadLetters()};_(f(this.filePath),{recursive:!0,mode:448});const r=`${this.filePath}.${D()}.tmp`;try{L(r,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"});const i=h(r,"r");try{u(i)}finally{c(i)}S(r,this.filePath);const n=h(f(this.filePath),"r");try{u(n)}finally{c(n)}try{v(this.filePath,384)}catch{}}finally{try{b(r)}catch{}}}}export{F as TerminalOutbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProvider as o,detectProviderFromModel as i,normalizeProviderId as t,queryProviderQuota as d,readKimiProviderSettings as
|
|
1
|
+
import{detectProvider as o,detectProviderFromModel as i,normalizeProviderId as t,queryProviderQuota as d,readKimiProviderSettings as a,readPiProviderSettings as v,resolveKimiProviderSettings as s}from"./providers.js";import{isOpenaiCodexProviderName as m,parseOpenaiCodexUsage as P,queryOpenaiCodexQuota as n,resolveOpenaiCodexAccessToken as u,openaiCodexQuotaCacheKey as x}from"./openai-codex.js";import{ProviderQuotaService as c,sharedProviderQuotaService as C,resolveQuotaBaseUrl as l}from"./service.js";import{providerQuotaToRateLimits as f,providerQuotaToCodexRateLimits as g}from"./presentation.js";export{c as ProviderQuotaService,o as detectProvider,i as detectProviderFromModel,m as isOpenaiCodexProviderName,t as normalizeProviderId,x as openaiCodexQuotaCacheKey,P as parseOpenaiCodexUsage,g as providerQuotaToCodexRateLimits,f as providerQuotaToRateLimits,n as queryOpenaiCodexQuota,d as queryProviderQuota,a as readKimiProviderSettings,v as readPiProviderSettings,s as resolveKimiProviderSettings,u as resolveOpenaiCodexAccessToken,l as resolveQuotaBaseUrl,C as sharedProviderQuotaService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile as _}from"node:fs/promises";import{existsSync as m}from"node:fs";import{homedir as h}from"node:os";import{join as u}from"node:path";import{execFile as I}from"node:child_process";import{promisify as O}from"node:util";const f=O(I),N=[u(h(),".aws/sso/cache/kiro-auth-token-cli.json"),u(h(),".aws/sso/cache/kiro-auth-token.json")],R="https://codewhisperer.us-east-1.amazonaws.com",b="AmazonCodeWhispererService.GetUsageLimits",S=1e4,E="kirocli:odic:token",C="kirocli:odic:device-registration";async function x(t){try{const{stdout:r}=await f("security",["find-generic-password","-s",t,"-w"],{timeout:5e3});return r.trim()}catch{return null}}async function D(t,r){try{await f("security",["delete-generic-password","-s",t],{timeout:5e3}).catch(()=>{}),await f("security",["add-generic-password","-s",t,"-w",r,"-U"],{timeout:5e3})}catch{}}function L(t){return Date.now()>new Date(t).getTime()}const
|
|
1
|
+
import{readFile as _}from"node:fs/promises";import{existsSync as m}from"node:fs";import{homedir as h}from"node:os";import{join as u}from"node:path";import{execFile as I}from"node:child_process";import{promisify as O}from"node:util";const f=O(I),N=[u(h(),".aws/sso/cache/kiro-auth-token-cli.json"),u(h(),".aws/sso/cache/kiro-auth-token.json")],R="https://codewhisperer.us-east-1.amazonaws.com",b="AmazonCodeWhispererService.GetUsageLimits",S=1e4,E="kirocli:odic:token",C="kirocli:odic:device-registration";async function x(t){try{const{stdout:r}=await f("security",["find-generic-password","-s",t,"-w"],{timeout:5e3});return r.trim()}catch{return null}}async function D(t,r){try{await f("security",["delete-generic-password","-s",t],{timeout:5e3}).catch(()=>{}),await f("security",["add-generic-password","-s",t,"-w",r,"-U"],{timeout:5e3})}catch{}}function L(t){return Date.now()>new Date(t).getTime()}const d=u(h(),"Library/Application Support/kiro-cli/data.sqlite3");async function K(){if(!m(d))return null;try{const{stdout:t}=await f("sqlite3",[d,"SELECT value FROM auth_kv WHERE key='kirocli:odic:token';"],{timeout:5e3}),r=t.trim();if(!r)return null;const e=JSON.parse(r);if(e.access_token&&e.expires_at)return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_at,region:e.region??"us-east-1",keychainRaw:e}}catch{}return null}async function v(){const t=await K();if(t)return t;const r=await x(E);if(r)try{const e=JSON.parse(r);if(e.access_token&&e.expires_at)return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_at,region:e.region??"us-east-1",keychainRaw:e}}catch{}for(const e of N)if(m(e))try{const n=JSON.parse(await _(e,"utf-8"));if(n.accessToken&&n.expiresAt)return{accessToken:n.accessToken,refreshToken:n.refreshToken??"",expiresAt:n.expiresAt,region:n.region??"us-east-1",profileArn:n.profileArn}}catch{}throw new Error("\u627E\u4E0D\u5230 Kiro token\uFF08SQLite\u3001keychain \u548C\u6587\u4EF6\u5747\u4E0D\u53EF\u7528\uFF09")}async function j(t){if(!t.refreshToken)throw new Error("\u65E0 refreshToken \u53EF\u7528");let r,e,n=!1;if(!n&&m(d))try{const{stdout:i}=await f("sqlite3",[d,"SELECT value FROM auth_kv WHERE key='kirocli:odic:device-registration';"],{timeout:5e3}),c=i.trim();if(c){const l=JSON.parse(c);l.client_id&&l.client_secret&&(r=l.client_id,e=l.client_secret,n=!0)}}catch{}if(!n){const i=await x(C);if(i){const c=JSON.parse(i);r=c.client_id,e=c.client_secret,n=!0}}if(!n){const i=u(h(),".aws/sso/cache"),{readdir:c}=await import("node:fs/promises"),l=await c(i);let p=null;for(const w of l)if(!(w.startsWith("kiro-")||!w.endsWith(".json")))try{const k=JSON.parse(await _(u(i,w),"utf-8"));if(k.clientId&&k.clientSecret){p={clientId:k.clientId,clientSecret:k.clientSecret};break}}catch{}if(!p)throw new Error("\u627E\u4E0D\u5230 OIDC client \u6CE8\u518C\u4FE1\u606F");r=p.clientId,e=p.clientSecret}const o=new AbortController,a=setTimeout(()=>o.abort(),S);let s;try{const i=await fetch(`https://oidc.${t.region}.amazonaws.com/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:r,clientSecret:e,grantType:"refresh_token",refreshToken:t.refreshToken}),signal:o.signal});if(!i.ok)throw new Error(`OIDC refresh ${i.status}: ${await i.text()}`);s=await i.json()}finally{clearTimeout(a)}const T=s.accessToken,y=s.refreshToken??t.refreshToken,A=s.expiresIn??3600,g=new Date(Date.now()+A*1e3).toISOString();if(t.keychainRaw){const i={...t.keychainRaw,access_token:T,refresh_token:y,expires_at:g};await D(E,JSON.stringify(i))}return{...t,accessToken:T,refreshToken:y,expiresAt:g}}async function J(t,r){const e=new AbortController,n=setTimeout(()=>e.abort(),S);try{const o={};r&&(o.profileArn=r);const a=await fetch(R,{method:"POST",headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":b,Authorization:`Bearer ${t}`,Accept:"application/json"},body:JSON.stringify(o),signal:e.signal});if(!a.ok){const s=await a.text();throw new Error(`GetUsageLimits ${a.status}: ${s}`)}return await a.json()}finally{clearTimeout(n)}}async function M(){try{let t=await v();L(t.expiresAt)&&(t=await j(t));const r=await J(t.accessToken,t.profileArn),e=r.usageBreakdownList?.find(o=>o.resourceType==="CREDIT");let n=null;if(e){const o=e.currentUsageWithPrecision??e.currentUsage,a=e.usageLimitWithPrecision??e.usageLimit,s=e.nextDateReset<1e12?e.nextDateReset*1e3:e.nextDateReset;n={kind:"currency",remaining:Math.max(0,a-o),total:a,used:o,unit:e.unit||e.displayName||"Credits",resetsAt:Number.isFinite(s)&&s>0?new Date(s).toISOString():null}}return{provider:"kiro",providerLabel:"Kiro",planName:r.subscriptionInfo?.subscriptionTitle??null,tiers:[],balance:n,success:!0,error:null}}catch(t){const r=t instanceof Error?t.message:String(t);return{provider:"kiro",providerLabel:"Kiro",planName:null,tiers:[],balance:null,success:!1,error:r}}}export{M as queryKiroQuota};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readFileSync as w,writeFileSync as _,renameSync as x,mkdirSync as A}from"node:fs";import{createHash as S,randomBytes as g}from"node:crypto";import{homedir as b}from"node:os";import{dirname as I,join as l}from"node:path";const h=1e4,d=86400,N=6e4,P="app_EMoamEEZ73f0CkXaXp7hrann",C="https://auth.openai.com/oauth/token";function v(t){const e=t?.trim().toLowerCase()??"";return e==="openai-codex"||e==="openai_codex"}function k(){return(process.env.PI_CODING_AGENT_DIR??"").trim()||l(b(),".pi","agent")}function u(t){return{provider:"openai_codex",providerLabel:"ChatGPT Codex",planName:null,tiers:[],balance:null,success:!1,error:t}}function T(t){const e=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(!Number.isFinite(e)||e<=0)return null;try{return new Date(e*1e3).toISOString()}catch{return null}}function p(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const e=Number(t);return Number.isFinite(e)?e:null}return null}function O(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const e=t,r=p(e.limit_window_seconds??e.limitWindowSeconds);if(r==null||r<=0)return null;const n=p(e.used_percent??e.usedPercent);if(n==null)return null;const c=T(e.reset_at??e.resetAt)??(()=>{const o=p(e.reset_after_seconds??e.resetAfterSeconds);return o==null||o<=0?null:new Date(Date.now()+o*1e3).toISOString()})();return{usedPercent:n,windowSeconds:r,resetsAt:c}}function E(t){const e=t.rate_limit??t.rateLimit;if(!e||typeof e!="object")return u("Unexpected ChatGPT usage response schema");const r=[];for(const s of["primary_window","primaryWindow","secondary_window","secondaryWindow"]){const a=O(e[s]);a&&r.push(a)}const n=r.filter(s=>s.windowSeconds<d).sort((s,a)=>Math.abs(s.windowSeconds-5*3600)-Math.abs(a.windowSeconds-5*3600))[0],c=r.filter(s=>s.windowSeconds>=d).sort((s,a)=>Math.abs(s.windowSeconds-7*d)-Math.abs(a.windowSeconds-7*d))[0],o=[];return n&&o.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(n.usedPercent*100)/100,resetsAt:n.resetsAt}),c&&o.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(c.usedPercent*100)/100,resetsAt:c.resetsAt}),o.length===0?u("No usable ChatGPT rate-limit windows"):{provider:"openai_codex",providerLabel:"ChatGPT Codex",planName:typeof t.plan_type=="string"?t.plan_type:typeof t.planType=="string"?t.planType:null,tiers:o,balance:null,success:!0,error:null}}function f(t){try{return JSON.parse(w(l(t,"auth.json"),"utf8"))}catch{return null}}function m(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const e=t,r=typeof e.access=="string"?e.access.trim():"",n=typeof e.refresh=="string"?e.refresh.trim():"";if(!r&&!n)return null;const c=typeof e.expires=="number"&&Number.isFinite(e.expires)?e.expires:null,o=typeof e.accountId=="string"&&e.accountId.trim()?e.accountId.trim():null;return{access:r,refresh:n,expires:c,accountId:o}}function y(t){return t.access?t.expires==null?!0:Date.now()<t.expires-N:!1}function K(t,e){const r=l(t,"auth.json"),n=f(t)??{},c=n["openai-codex"]&&typeof n["openai-codex"]=="object"?n["openai-codex"]:{};n["openai-codex"]={...c,type:"oauth",access:e.access,refresh:e.refresh,...e.expires!=null?{expires:e.expires}:{},...e.accountId?{accountId:e.accountId}:{}},A(I(r),{recursive:!0});const o=l(t,`auth.json.tmp-${process.pid}-${g(4).toString("hex")}`);_(o,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,{mode:384}),x(o,r)}async function j(t){const e=await fetch(C,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:P}),signal:AbortSignal.timeout(h)});if(!e.ok)return null;const r=await e.json().catch(()=>({})),n=typeof r.access_token=="string"?r.access_token.trim():"",c=typeof r.refresh_token=="string"&&r.refresh_token.trim()?r.refresh_token.trim():t,o=Number(r.expires_in);return!n||!Number.isFinite(o)||o<=0?null:{access:n,refresh:c,expires:Date.now()+o*1e3,accountId:null}}async function F(t){const e=t||k(),r=f(e);if(!r)return null;let n=m(r["openai-codex"]);if(!n)return null;if(!y(n)){if(!n.refresh)return null;const o=await j(n.refresh);if(o){const i=n.accountId??o.accountId;n={...o,accountId:i};try{K(e,n)}catch{}}else{const i=m(f(e)?.["openai-codex"]);if(i&&y(i))n=i;else return null}}if(!n.access)return null;const c=n.accountId??S("sha256").update(n.access).digest("hex").slice(0,16);return{access:n.access,accountId:n.accountId,cacheAccountKey:c}}function G(t){return`openai_codex|${t||"default"}`}async function U(t){const e=await F(t);if(!e)return{quota:u("Pi openai-codex OAuth token missing or expired (refresh failed)"),accountKey:"default"};const r=new URL("https://chatgpt.com/backend-api/wham/usage");e.accountId&&r.searchParams.set("account_id",e.accountId);try{const n=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${e.access}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(n.status===401||n.status===403)return{quota:u(`Authentication failed (HTTP ${n.status})`),accountKey:e.cacheAccountKey};if(!n.ok){const o=await n.text().catch(()=>"");return{quota:u(`API error (HTTP ${n.status}): ${o.slice(0,200)}`),accountKey:e.cacheAccountKey}}const c=await n.json();return{quota:E(c),accountKey:e.cacheAccountKey}}catch(n){return{quota:u(`Network error: ${n instanceof Error?n.message:String(n)}`),accountKey:e.cacheAccountKey}}}export{v as isOpenaiCodexProviderName,G as openaiCodexQuotaCacheKey,E as parseOpenaiCodexUsage,U as queryOpenaiCodexQuota,F as resolveOpenaiCodexAccessToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(e){if(!e)return 0;const i=Date.parse(e);return Number.isFinite(i)?Math.floor(i/1e3):0}function d(e,i=Date.now()){const n=e.tiers.find(r=>r.name==="five_hour"),t=e.tiers.find(r=>r.name==="weekly_limit");return n||t?{...n?{fiveHour:{usedPercentage:n.usedPercent,resetsAt:a(n.resetsAt)}}:{},...t?{sevenDay:{usedPercentage:t.usedPercent,resetsAt:a(t.resetsAt)}}:{},sampledAt:i}:e.balance?{credit:{remaining:e.balance.remaining,total:e.balance.total,used:e.balance.used,unit:e.balance.unit,resetsAt:a(e.balance.resetsAt??null)},planName:e.planName,sampledAt:i}:null}function l(e,i=Date.now()){const n=e.tiers.find(s=>s.name==="five_hour"),t=e.tiers.find(s=>s.name==="weekly_limit");if(n||t){const s={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:i};return n&&(s.primary={usedPercent:n.usedPercent,windowMinutes:300,resetsAt:n.resetsAt}),t&&(s.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:t.resetsAt}),{rateLimits:s,primaryPercent:n?.usedPercent??0,secondaryPercent:t?.usedPercent??0,primaryWindowMin:n?300:0,secondaryWindowMin:t?10080:0}}if(!e.balance)return null;const r=e.balance,c=r.total&&r.total>0?Math.min(100,(r.used??r.total-r.remaining)/r.total*100):0;return{rateLimits:{primary:{usedPercent:c,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:r.remaining},sampledAt:i},primaryPercent:c,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}export{l as providerQuotaToCodexRateLimits,d as providerQuotaToRateLimits};
|
|
1
|
+
function a(e){if(!e)return 0;const i=Date.parse(e);return Number.isFinite(i)?Math.floor(i/1e3):0}function d(e,i=Date.now()){const n=e.tiers.find(r=>r.name==="five_hour"),t=e.tiers.find(r=>r.name==="weekly_limit");return n||t?{...n?{fiveHour:{usedPercentage:n.usedPercent,resetsAt:a(n.resetsAt)}}:{},...t?{sevenDay:{usedPercentage:t.usedPercent,resetsAt:a(t.resetsAt)}}:{},sampledAt:i}:e.balance?{credit:{remaining:e.balance.remaining,total:e.balance.total,used:e.balance.used,unit:e.balance.unit,resetsAt:a(e.balance.resetsAt??null),...e.balance.kind?{kind:e.balance.kind}:{}},planName:e.planName,sampledAt:i}:null}function l(e,i=Date.now()){const n=e.tiers.find(s=>s.name==="five_hour"),t=e.tiers.find(s=>s.name==="weekly_limit");if(n||t){const s={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:i};return n&&(s.primary={usedPercent:n.usedPercent,windowMinutes:300,resetsAt:n.resetsAt}),t&&(s.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:t.resetsAt}),{rateLimits:s,primaryPercent:n?.usedPercent??0,secondaryPercent:t?.usedPercent??0,primaryWindowMin:n?300:0,secondaryWindowMin:t?10080:0}}if(!e.balance)return null;const r=e.balance,c=r.total&&r.total>0?Math.min(100,(r.used??r.total-r.remaining)/r.total*100):0;return{rateLimits:{primary:{usedPercent:c,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:r.remaining},sampledAt:i},primaryPercent:c,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}export{l as providerQuotaToCodexRateLimits,d as providerQuotaToRateLimits};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHash as R}from"node:crypto";import{readFileSync as
|
|
2
|
-
[`,i+1),u=(l>=0?n.slice(i,l):n.slice(i)).match(/^\s*base_url\s*=\s*"([^"]+)"/m);u&&(e=u[1].trim())}}catch{}let a;try{const o=y(t,"credentials","kimi-code.json"),n=JSON.parse(w(o,"utf8")),i=typeof n.access_token=="string"?n.access_token.trim():"",l=typeof n.expires_at=="number"?n.expires_at:null;i&&(!l||Date.now()<l*1e3-s)&&(a=i)}catch{}return{baseUrl:e,apiKey:a}}const B="17e5f671-d194-4dfb-9706-5516cb48c098";function F(){return(process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||"https://auth.kimi.com").replace(/\/+$/,"")}const K=30*1e3;async function ce(r){const t=$(r);if(t.apiKey)return t;const s=await q(r);return{baseUrl:t.baseUrl,apiKey:s}}async function q(r){const t=r||j(),s=y(t,"credentials","kimi-code.json");let e;try{e=JSON.parse(w(s,"utf8"))}catch{return}const a=typeof e.refresh_token=="string"?e.refresh_token.trim():"";if(!a)return;const o=y(t,"credentials","kimi-code.lock.lock");if(Y(o))try{const n=$(r);if(n.apiKey)return n.apiKey;let i="";try{i=w(y(t,"device_id"),"utf8").trim()}catch{}const l=await fetch(`${F()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...i?{"X-Msh-Device-Id":i}:{}},body:new URLSearchParams({client_id:B,grant_type:"refresh_token",refresh_token:a}),signal:AbortSignal.timeout(8e3)}),c=await l.json().catch(()=>({})),u=typeof c.access_token=="string"?c.access_token:"";if(l.status!==200||!u)return $(r).apiKey;const d=Number(c.expires_in),f={access_token:u,refresh_token:typeof c.refresh_token=="string"&&c.refresh_token?c.refresh_token:a,expires_at:Math.floor(Date.now()/1e3)+(Number.isFinite(d)&&d>0?d:900),scope:typeof c.scope=="string"&&c.scope?c.scope:e.scope??"kimi-code",token_type:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expires_in:Number.isFinite(d)&&d>0?d:900};return H(s,JSON.stringify(f),{mode:384}),u}catch{return}finally{try{x(o)}catch{}}}function Y(r){try{return N(r),!0}catch{}try{const t=C(r);return Date.now()-t.mtimeMs<K?!1:(x(r),N(r),!0)}catch{return!1}}function V(){return(process.env.PI_CODING_AGENT_DIR||"").trim()||y(M(),".pi","agent")}function Z(r){if(typeof r!="string")return;const t=r.trim();if(!(!t||t.startsWith("!")))return(process.env[t]??"").trim()||t}function le(r,t){const s=t||V();let e;try{e=JSON.parse(w(y(s,"models.json"),"utf8"))}catch{return{baseUrl:void 0,apiKey:void 0}}const a=e.providers;if(!a||typeof a!="object"||Array.isArray(a))return{baseUrl:void 0,apiKey:void 0};const o=[];for(const[u,d]of Object.entries(a)){const f=d&&typeof d=="object"?d:{},b=typeof f.baseUrl=="string"&&f.baseUrl.trim()?f.baseUrl.trim():void 0,_=Z(f.apiKey),g=Array.isArray(f.models)?f.models.map(v=>typeof v?.id=="string"?v.id.trim().toLowerCase():"").filter(Boolean):[],A=P(u)??(b?E(b)?.id??null:null)??g.map(v=>L(v)?.id??null).find(v=>v!==null)??null;o.push({baseUrl:b,apiKey:_,modelIds:g,providerId:A})}const n=o.filter(u=>u.baseUrl&&u.apiKey),i=P(r?.providerId),l=r?.model?.trim().toLowerCase()||void 0;let c;if(i){const u=n.filter(d=>d.providerId===i);c=(l?u.find(d=>d.modelIds.includes(l)):void 0)??u[0]}return!c&&l&&(c=n.find(u=>u.modelIds.includes(l))??n.find(u=>u.providerId!==null&&u.providerId===L(l)?.id)),!c&&!i&&!l&&(c=n[0]),{baseUrl:c?.baseUrl,apiKey:c?.apiKey}}async function W(r){const t="zhipu",s="Zhipu GLM";try{const e=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",{method:"GET",headers:{Authorization:r,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const l=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${l.slice(0,200)}`)}const a=await e.json();if(a.success===!1)return m(t,s,`API error: ${a.msg??"Unknown error"}`);const o=a.data;if(!o)return m(t,s,"Missing data field");const n=typeof o.level=="string"?o.level:null,i=U(o);return{provider:t,providerLabel:s,planName:n,tiers:i,balance:null,success:!0,error:null}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}function U(r){const t=Array.isArray(r.limits)?r.limits:[],s=[];for(const a of t){if(String(a.type??"").toUpperCase()!=="TOKENS_LIMIT")continue;const n=p(a.percentage)??0,i=p(a.nextResetTime)??Number.MAX_SAFE_INTEGER,l=i===Number.MAX_SAFE_INTEGER?null:k(i);s.push({percentage:n,resetMs:i,resetIso:l})}s.sort((a,o)=>a.resetMs-o.resetMs);const e=[];if(s.length>0){const a=s[0];e.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}if(s.length>1){const a=s[s.length-1];a.resetMs!==s[0].resetMs&&e.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}return e}async function J(r){const t="kimi",s="Kimi";try{const e=await fetch("https://api.kimi.com/coding/v1/usages",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const l=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${l.slice(0,200)}`)}const a=await e.json();if(!Array.isArray(a.limits)&&!a.usage)return m(t,s,"Unexpected quota response schema");const o=[],n=Array.isArray(a.limits)?a.limits:[];for(const l of n){const c=l.detail;if(!c)continue;const u=p(c.limit)??1,d=p(c.remaining)??0,f=T(c.resetTime),b=Math.max(0,u-d);o.push({name:"five_hour",label:"5h limit",usedPercent:u>0?Math.round(b/u*1e4)/100:0,resetsAt:f})}const i=a.usage;if(i){const l=p(i.limit)??1,c=p(i.remaining)??0,u=T(i.resetTime),d=Math.max(0,l-c);o.push({name:"weekly_limit",label:"Weekly limit",usedPercent:l>0?Math.round(d/l*1e4)/100:0,resetsAt:u})}return{provider:t,providerLabel:s,planName:null,tiers:o,balance:null,success:!0,error:null}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function O(r,t){const s=t?"minimax_cn":"minimax_en",e="MiniMax",a=t?"api.minimaxi.com":"api.minimax.io";try{const o=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(h)});if(o.status===401||o.status===403)return m(s,e,`Authentication failed (HTTP ${o.status})`);if(!o.ok){const d=await o.text().catch(()=>"");return m(s,e,`API error (HTTP ${o.status}): ${d.slice(0,200)}`)}const n=await o.json(),i=n.base_resp;if(i&&typeof i.status_code=="number"&&i.status_code!==0)return m(s,e,`API error (code ${i.status_code}): ${i.status_msg??"Unknown"}`);const l=[],u=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(u){const d=p(u.current_interval_total_count)??0,f=p(u.current_interval_usage_count)??0,b=typeof u.end_time=="number"?u.end_time:null;d>0&&l.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(f/d*1e4)/100,resetsAt:b!==null?k(b):null});const _=p(u.current_weekly_total_count)??0,g=p(u.current_weekly_usage_count)??0,A=typeof u.weekly_end_time=="number"?u.weekly_end_time:null;_>0&&l.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(g/_*1e4)/100,resetsAt:A!==null?k(A):null})}return{provider:s,providerLabel:e,planName:null,tiers:l,balance:null,success:!0,error:null}}catch(o){return m(s,e,`Network error: ${o instanceof Error?o.message:String(o)}`)}}async function X(r){const t="deepseek",s="DeepSeek";try{const e=await fetch("https://api.deepseek.com/user/balance",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const u=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${u.slice(0,200)}`)}const a=await e.json(),o=a.is_available===!0,i=(Array.isArray(a.balance_infos)?a.balance_infos:[])[0];if(!i)return m(t,s,"No balance info returned");const l=String(i.currency??"CNY"),c=p(i.total_balance);return{provider:t,providerLabel:s,planName:null,tiers:[],balance:{remaining:c??0,total:null,used:null,unit:l},success:!0,error:o?null:"Insufficient balance"}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function Q(r){const t="stepfun",s="StepFun";try{const e=await fetch("https://api.stepfun.com/v1/accounts",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const n=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${n.slice(0,200)}`)}const a=await e.json(),o=p(a.balance)??0;return{provider:t,providerLabel:s,planName:null,tiers:[],balance:{remaining:o,total:null,used:null,unit:"CNY"},success:!0,error:null}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function z(r,t){const s=t?"siliconflow_cn":"siliconflow_en",e=t?"SiliconFlow":"SiliconFlow (EN)",a=t?"api.siliconflow.cn":"api.siliconflow.com",o=t?"CNY":"USD";try{const n=await fetch(`https://${a}/v1/user/info`,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(n.status===401||n.status===403)return m(s,e,`Authentication failed (HTTP ${n.status})`);if(!n.ok){const u=await n.text().catch(()=>"");return m(s,e,`API error (HTTP ${n.status}): ${u.slice(0,200)}`)}const l=(await n.json()).data;if(!l)return m(s,e,"Missing data field");const c=p(l.totalBalance)??0;return{provider:s,providerLabel:e,planName:null,tiers:[],balance:{remaining:c,total:null,used:null,unit:o},success:!0,error:null}}catch(n){return m(s,e,`Network error: ${n instanceof Error?n.message:String(n)}`)}}async function ee(r){const t="openrouter",s="OpenRouter";try{const e=await fetch("https://openrouter.ai/api/v1/credits",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const c=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${c.slice(0,200)}`)}const a=await e.json(),o=a.data??a,n=p(o.total_credits)??0,i=p(o.total_usage)??0,l=n-i;return{provider:t,providerLabel:s,planName:null,tiers:[],balance:{remaining:l,total:n,used:i,unit:"USD"},success:!0,error:null}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function te(r){const t="novita",s="Novita AI";try{const e=await fetch("https://api.novita.ai/v3/user/balance",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,s,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const n=await e.text().catch(()=>"");return m(t,s,`API error (HTTP ${e.status}): ${n.slice(0,200)}`)}const a=await e.json(),o=(p(a.availableBalance)??0)/1e4;return{provider:t,providerLabel:s,planName:null,tiers:[],balance:{remaining:o,total:null,used:null,unit:"USD"},success:!0,error:null}}catch(e){return m(t,s,`Network error: ${e instanceof Error?e.message:String(e)}`)}}const S=new Map,ne=300*1e3;async function re(r,t){const s=R("sha256").update(t).digest("hex").slice(0,16),e=`${r.trim().replace(/\/+$/,"").toLowerCase()}|${s}`,a=S.get(e);if(a&&Date.now()-a.timestamp<=ne){const i=await I(a.providerId,r,t);if(i)return i;S.delete(e)}else a&&S.delete(e);const o=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],n=await Promise.allSettled(o.map(i=>I(i,r,t)));for(let i=0;i<n.length;i++){const l=n[i];if(l.status==="fulfilled"&&l.value?.success)return S.set(e,{providerId:o[i],timestamp:Date.now()}),l.value}return null}async function I(r,t,s){const e=t.replace(/\/+$/,""),a={Authorization:`Bearer ${s}`,Accept:"application/json"};try{switch(r){case"zhipu":{const o=await fetch(`${e}/api/monitor/usage/quota/limit`,{method:"GET",headers:{...a,Authorization:s,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json();if(n.success===!1)return null;const i=n.data;if(!i)return null;const l=typeof i.level=="string"?i.level:null,c=U(i);return{provider:"zhipu",providerLabel:"Zhipu GLM",planName:l,tiers:c,balance:null,success:!0,error:null}}case"deepseek":{const o=await fetch(`${e}/user/balance`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json(),i=n.is_available===!0,c=(Array.isArray(n.balance_infos)?n.balance_infos:[])[0];if(!c)return null;const u=String(c.currency??"CNY"),d=p(c.total_balance);return{provider:"deepseek",providerLabel:"DeepSeek",planName:null,tiers:[],balance:{remaining:d??0,total:null,used:null,unit:u},success:!0,error:i?null:"Insufficient balance"}}case"kimi":{const o=await fetch(`${e}/coding/v1/usages`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json();if(!Array.isArray(n.limits)&&!n.usage)return null;const i=[],l=Array.isArray(n.limits)?n.limits:[];for(const u of l){const d=u.detail;if(!d)continue;const f=p(d.limit)??1,b=p(d.remaining)??0,_=T(d.resetTime),g=Math.max(0,f-b);i.push({name:"five_hour",label:"5h limit",usedPercent:f>0?Math.round(g/f*1e4)/100:0,resetsAt:_})}const c=n.usage;if(c){const u=p(c.limit)??1,d=p(c.remaining)??0,f=T(c.resetTime),b=Math.max(0,u-d);i.push({name:"weekly_limit",label:"Weekly limit",usedPercent:u>0?Math.round(b/u*1e4)/100:0,resetsAt:f})}return{provider:"kimi",providerLabel:"Kimi",planName:null,tiers:i,balance:null,success:!0,error:null}}case"openrouter":{const o=await fetch(`${e}/api/v1/credits`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json(),i=n.data??n;if(i.total_credits===void 0&&i.total_usage===void 0)return null;const l=p(i.total_credits)??0,c=p(i.total_usage)??0,u=l-c;return{provider:"openrouter",providerLabel:"OpenRouter",planName:null,tiers:[],balance:{remaining:u,total:l,used:c,unit:"USD"},success:!0,error:null}}case"stepfun":{const o=await fetch(`${e}/v1/accounts`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json();if(n.balance===void 0)return null;const i=p(n.balance)??0;return{provider:"stepfun",providerLabel:"StepFun",planName:null,tiers:[],balance:{remaining:i,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"minimax_cn":case"minimax_en":{const o=await fetch(`${e}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json(),i=n.base_resp;if(i&&typeof i.status_code=="number"&&i.status_code!==0)return null;const c=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(!c)return null;const u=[],d=p(c.current_interval_total_count)??0,f=p(c.current_interval_usage_count)??0;if(d>0){const b=typeof c.end_time=="number"?c.end_time:null;u.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(f/d*1e4)/100,resetsAt:b!==null?k(b):null})}return{provider:r,providerLabel:"MiniMax",planName:null,tiers:u,balance:null,success:!0,error:null}}case"siliconflow_cn":case"siliconflow_en":{const o=await fetch(`${e}/v1/user/info`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const i=(await o.json()).data;if(!i)return null;const l=p(i.totalBalance)??0;return{provider:r,providerLabel:"SiliconFlow",planName:null,tiers:[],balance:{remaining:l,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"novita":{const o=await fetch(`${e}/v3/user/balance`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!o.ok)return null;const n=await o.json();if(n.availableBalance===void 0)return null;const i=(p(n.availableBalance)??0)/1e4;return{provider:"novita",providerLabel:"Novita AI",planName:null,tiers:[],balance:{remaining:i,total:null,used:null,unit:"USD"},success:!0,error:null}}default:return null}}catch{return null}}async function ue(r,t,s){if(!t.trim())return{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:"API key is empty"};const e=P(s),a=E(r);if(a)switch(a.id){case"zhipu":return W(t);case"kimi":return J(t);case"minimax_cn":return O(t,!0);case"minimax_en":return O(t,!1);case"deepseek":return X(t);case"stepfun":return Q(t);case"siliconflow_cn":return z(t,!0);case"siliconflow_en":return z(t,!1);case"openrouter":return ee(t);case"novita":return te(t)}if(e){const n=await I(e,r,t);return n||m(e,e,`Quota API unavailable through base URL: ${r}`)}const o=await re(r,t);return o||{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:`Could not identify provider for base URL: ${r}`}}export{E as detectProvider,L as detectProviderFromModel,P as normalizeProviderId,ue as queryProviderQuota,$ as readKimiProviderSettings,le as readPiProviderSettings,ce as resolveKimiProviderSettings};
|
|
1
|
+
import{createHash as R}from"node:crypto";import{readFileSync as k,writeFileSync as C,mkdirSync as I,rmdirSync as N,statSync as H}from"node:fs";import{homedir as M}from"node:os";import{join as y}from"node:path";const G=new Set(["zhipu","kimi","minimax_cn","minimax_en","deepseek","stepfun","siliconflow_cn","siliconflow_en","openrouter","novita","openai_codex"]),D={zai:"zhipu","z.ai":"zhipu",glm:"zhipu",bigmodel:"zhipu",moonshot:"kimi",minimax:"minimax_cn",siliconflow:"siliconflow_cn","openai-codex":"openai_codex"};function P(r){const t=r?.trim().toLowerCase();if(!t)return null;const o=D[t]??t;return G.has(o)?o:null}function E(r){const t=r.toLowerCase();return t.includes("open.bigmodel.cn")||t.includes("bigmodel.cn")||t.includes("api.z.ai")?{id:"zhipu",label:"Zhipu GLM"}:t.includes("api.kimi.com")?{id:"kimi",label:"Kimi"}:t.includes("api.minimaxi.com")?{id:"minimax_cn",label:"MiniMax"}:t.includes("api.minimax.io")?{id:"minimax_en",label:"MiniMax"}:t.includes("api.deepseek.com")?{id:"deepseek",label:"DeepSeek"}:t.includes("api.stepfun.ai")||t.includes("api.stepfun.com")?{id:"stepfun",label:"StepFun"}:t.includes("api.siliconflow.cn")?{id:"siliconflow_cn",label:"SiliconFlow"}:t.includes("api.siliconflow.com")?{id:"siliconflow_en",label:"SiliconFlow"}:t.includes("openrouter.ai")?{id:"openrouter",label:"OpenRouter"}:t.includes("api.novita.ai")?{id:"novita",label:"Novita AI"}:null}function L(r){const t=r?.trim().toLowerCase()??"";return t?/(^|[\/:_-])(glm|zhipu|zai)([\/:_.-]|$)/.test(t)?{id:"zhipu",label:"Zhipu GLM"}:/(^|[\/:_-])(kimi|moonshot)([\/:_.-]|$)/.test(t)?{id:"kimi",label:"Kimi"}:/(^|[\/:_-])deepseek([\/:_.-]|$)/.test(t)?{id:"deepseek",label:"DeepSeek"}:null:null}const h=1e4;function m(r,t,o){return{provider:r,providerLabel:t,planName:null,tiers:[],balance:null,success:!1,error:o}}function p(r){if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);return Number.isFinite(t)?t:null}return null}function w(r){if(!Number.isFinite(r)||r<=0)return null;try{return new Date(r).toISOString()}catch{return null}}function T(r){if(typeof r=="string")return r;if(typeof r=="number"){const t=r<1e12?r*1e3:r;return w(t)}return null}function U(){return(process.env.KIMI_CODE_HOME||"").trim()||y(M(),".kimi-code")}function x(r){const t=r||U(),o=300*1e3;let e;try{const s=y(t,"config.toml"),n=k(s,"utf8"),i=n.indexOf('[providers."managed:kimi-code"]');if(i>=0){const l=n.indexOf(`
|
|
2
|
+
[`,i+1),u=(l>=0?n.slice(i,l):n.slice(i)).match(/^\s*base_url\s*=\s*"([^"]+)"/m);u&&(e=u[1].trim())}}catch{}let a;try{const s=y(t,"credentials","kimi-code.json"),n=JSON.parse(k(s,"utf8")),i=typeof n.access_token=="string"?n.access_token.trim():"",l=typeof n.expires_at=="number"?n.expires_at:null;i&&(!l||Date.now()<l*1e3-o)&&(a=i)}catch{}return{baseUrl:e,apiKey:a}}const B="17e5f671-d194-4dfb-9706-5516cb48c098";function F(){return(process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||"https://auth.kimi.com").replace(/\/+$/,"")}const K=30*1e3;async function ce(r){const t=x(r);if(t.apiKey)return t;const o=await q(r);return{baseUrl:t.baseUrl,apiKey:o}}async function q(r){const t=r||U(),o=y(t,"credentials","kimi-code.json");let e;try{e=JSON.parse(k(o,"utf8"))}catch{return}const a=typeof e.refresh_token=="string"?e.refresh_token.trim():"";if(!a)return;const s=y(t,"credentials","kimi-code.lock.lock");if(Y(s))try{const n=x(r);if(n.apiKey)return n.apiKey;let i="";try{i=k(y(t,"device_id"),"utf8").trim()}catch{}const l=await fetch(`${F()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...i?{"X-Msh-Device-Id":i}:{}},body:new URLSearchParams({client_id:B,grant_type:"refresh_token",refresh_token:a}),signal:AbortSignal.timeout(8e3)}),c=await l.json().catch(()=>({})),u=typeof c.access_token=="string"?c.access_token:"";if(l.status!==200||!u)return x(r).apiKey;const d=Number(c.expires_in),f={access_token:u,refresh_token:typeof c.refresh_token=="string"&&c.refresh_token?c.refresh_token:a,expires_at:Math.floor(Date.now()/1e3)+(Number.isFinite(d)&&d>0?d:900),scope:typeof c.scope=="string"&&c.scope?c.scope:e.scope??"kimi-code",token_type:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expires_in:Number.isFinite(d)&&d>0?d:900};return C(o,JSON.stringify(f),{mode:384}),u}catch{return}finally{try{N(s)}catch{}}}function Y(r){try{return I(r),!0}catch{}try{const t=H(r);return Date.now()-t.mtimeMs<K?!1:(N(r),I(r),!0)}catch{return!1}}function V(){return(process.env.PI_CODING_AGENT_DIR||"").trim()||y(M(),".pi","agent")}function Z(r){if(typeof r!="string")return;const t=r.trim();if(!(!t||t.startsWith("!")))return(process.env[t]??"").trim()||t}function le(r,t){const o=t||V();let e;try{e=JSON.parse(k(y(o,"models.json"),"utf8"))}catch{return{baseUrl:void 0,apiKey:void 0}}const a=e.providers;if(!a||typeof a!="object"||Array.isArray(a))return{baseUrl:void 0,apiKey:void 0};const s=[];for(const[u,d]of Object.entries(a)){const f=d&&typeof d=="object"?d:{},b=typeof f.baseUrl=="string"&&f.baseUrl.trim()?f.baseUrl.trim():void 0,_=Z(f.apiKey),g=Array.isArray(f.models)?f.models.map(v=>typeof v?.id=="string"?v.id.trim().toLowerCase():"").filter(Boolean):[],A=P(u)??(b?E(b)?.id??null:null)??g.map(v=>L(v)?.id??null).find(v=>v!==null)??null;s.push({baseUrl:b,apiKey:_,modelIds:g,providerId:A})}const n=s.filter(u=>u.baseUrl&&u.apiKey),i=P(r?.providerId),l=r?.model?.trim().toLowerCase()||void 0;let c;if(i){const u=n.filter(d=>d.providerId===i);c=(l?u.find(d=>d.modelIds.includes(l)):void 0)??u[0]}return!c&&l&&(c=n.find(u=>u.modelIds.includes(l))??n.find(u=>u.providerId!==null&&u.providerId===L(l)?.id)),!c&&!i&&!l&&(c=n[0]),{baseUrl:c?.baseUrl,apiKey:c?.apiKey}}async function W(r){const t="zhipu",o="Zhipu GLM";try{const e=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",{method:"GET",headers:{Authorization:r,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const l=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${l.slice(0,200)}`)}const a=await e.json();if(a.success===!1)return m(t,o,`API error: ${a.msg??"Unknown error"}`);const s=a.data;if(!s)return m(t,o,"Missing data field");const n=typeof s.level=="string"?s.level:null,i=j(s);return{provider:t,providerLabel:o,planName:n,tiers:i,balance:null,success:!0,error:null}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}function j(r){const t=Array.isArray(r.limits)?r.limits:[],o=[];for(const a of t){if(String(a.type??"").toUpperCase()!=="TOKENS_LIMIT")continue;const n=p(a.percentage)??0,i=p(a.nextResetTime)??Number.MAX_SAFE_INTEGER,l=i===Number.MAX_SAFE_INTEGER?null:w(i);o.push({percentage:n,resetMs:i,resetIso:l})}o.sort((a,s)=>a.resetMs-s.resetMs);const e=[];if(o.length>0){const a=o[0];e.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}if(o.length>1){const a=o[o.length-1];a.resetMs!==o[0].resetMs&&e.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(a.percentage*100)/100,resetsAt:a.resetIso})}return e}async function J(r){const t="kimi",o="Kimi";try{const e=await fetch("https://api.kimi.com/coding/v1/usages",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const l=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${l.slice(0,200)}`)}const a=await e.json();if(!Array.isArray(a.limits)&&!a.usage)return m(t,o,"Unexpected quota response schema");const s=[],n=Array.isArray(a.limits)?a.limits:[];for(const l of n){const c=l.detail;if(!c)continue;const u=p(c.limit)??1,d=p(c.remaining)??0,f=T(c.resetTime),b=Math.max(0,u-d);s.push({name:"five_hour",label:"5h limit",usedPercent:u>0?Math.round(b/u*1e4)/100:0,resetsAt:f})}const i=a.usage;if(i){const l=p(i.limit)??1,c=p(i.remaining)??0,u=T(i.resetTime),d=Math.max(0,l-c);s.push({name:"weekly_limit",label:"Weekly limit",usedPercent:l>0?Math.round(d/l*1e4)/100:0,resetsAt:u})}return{provider:t,providerLabel:o,planName:null,tiers:s,balance:null,success:!0,error:null}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function O(r,t){const o=t?"minimax_cn":"minimax_en",e="MiniMax",a=t?"api.minimaxi.com":"api.minimax.io";try{const s=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(h)});if(s.status===401||s.status===403)return m(o,e,`Authentication failed (HTTP ${s.status})`);if(!s.ok){const d=await s.text().catch(()=>"");return m(o,e,`API error (HTTP ${s.status}): ${d.slice(0,200)}`)}const n=await s.json(),i=n.base_resp;if(i&&typeof i.status_code=="number"&&i.status_code!==0)return m(o,e,`API error (code ${i.status_code}): ${i.status_msg??"Unknown"}`);const l=[],u=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(u){const d=p(u.current_interval_total_count)??0,f=p(u.current_interval_usage_count)??0,b=typeof u.end_time=="number"?u.end_time:null;d>0&&l.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(f/d*1e4)/100,resetsAt:b!==null?w(b):null});const _=p(u.current_weekly_total_count)??0,g=p(u.current_weekly_usage_count)??0,A=typeof u.weekly_end_time=="number"?u.weekly_end_time:null;_>0&&l.push({name:"weekly_limit",label:"Weekly limit",usedPercent:Math.round(g/_*1e4)/100,resetsAt:A!==null?w(A):null})}return{provider:o,providerLabel:e,planName:null,tiers:l,balance:null,success:!0,error:null}}catch(s){return m(o,e,`Network error: ${s instanceof Error?s.message:String(s)}`)}}async function X(r){const t="deepseek",o="DeepSeek";try{const e=await fetch("https://api.deepseek.com/user/balance",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const u=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${u.slice(0,200)}`)}const a=await e.json(),s=a.is_available===!0,i=(Array.isArray(a.balance_infos)?a.balance_infos:[])[0];if(!i)return m(t,o,"No balance info returned");const l=String(i.currency??"CNY"),c=p(i.total_balance);return{provider:t,providerLabel:o,planName:null,tiers:[],balance:{kind:"currency",remaining:c??0,total:null,used:null,unit:l},success:!0,error:s?null:"Insufficient balance"}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function Q(r){const t="stepfun",o="StepFun";try{const e=await fetch("https://api.stepfun.com/v1/accounts",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const n=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${n.slice(0,200)}`)}const a=await e.json(),s=p(a.balance)??0;return{provider:t,providerLabel:o,planName:null,tiers:[],balance:{kind:"currency",remaining:s,total:null,used:null,unit:"CNY"},success:!0,error:null}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function z(r,t){const o=t?"siliconflow_cn":"siliconflow_en",e=t?"SiliconFlow":"SiliconFlow (EN)",a=t?"api.siliconflow.cn":"api.siliconflow.com",s=t?"CNY":"USD";try{const n=await fetch(`https://${a}/v1/user/info`,{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(n.status===401||n.status===403)return m(o,e,`Authentication failed (HTTP ${n.status})`);if(!n.ok){const u=await n.text().catch(()=>"");return m(o,e,`API error (HTTP ${n.status}): ${u.slice(0,200)}`)}const l=(await n.json()).data;if(!l)return m(o,e,"Missing data field");const c=p(l.totalBalance)??0;return{provider:o,providerLabel:e,planName:null,tiers:[],balance:{kind:"currency",remaining:c,total:null,used:null,unit:s},success:!0,error:null}}catch(n){return m(o,e,`Network error: ${n instanceof Error?n.message:String(n)}`)}}async function ee(r){const t="openrouter",o="OpenRouter";try{const e=await fetch("https://openrouter.ai/api/v1/credits",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const c=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${c.slice(0,200)}`)}const a=await e.json(),s=a.data??a,n=p(s.total_credits)??0,i=p(s.total_usage)??0,l=n-i;return{provider:t,providerLabel:o,planName:null,tiers:[],balance:{kind:"currency",remaining:l,total:n,used:i,unit:"USD"},success:!0,error:null}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}async function te(r){const t="novita",o="Novita AI";try{const e=await fetch("https://api.novita.ai/v3/user/balance",{method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},signal:AbortSignal.timeout(h)});if(e.status===401||e.status===403)return m(t,o,`Authentication failed (HTTP ${e.status})`);if(!e.ok){const n=await e.text().catch(()=>"");return m(t,o,`API error (HTTP ${e.status}): ${n.slice(0,200)}`)}const a=await e.json(),s=(p(a.availableBalance)??0)/1e4;return{provider:t,providerLabel:o,planName:null,tiers:[],balance:{kind:"currency",remaining:s,total:null,used:null,unit:"USD"},success:!0,error:null}}catch(e){return m(t,o,`Network error: ${e instanceof Error?e.message:String(e)}`)}}const S=new Map,ne=300*1e3;async function re(r,t){const o=R("sha256").update(t).digest("hex").slice(0,16),e=`${r.trim().replace(/\/+$/,"").toLowerCase()}|${o}`,a=S.get(e);if(a&&Date.now()-a.timestamp<=ne){const i=await $(a.providerId,r,t);if(i)return i;S.delete(e)}else a&&S.delete(e);const s=["zhipu","deepseek","kimi","openrouter","stepfun","minimax_cn","siliconflow_cn","novita"],n=await Promise.allSettled(s.map(i=>$(i,r,t)));for(let i=0;i<n.length;i++){const l=n[i];if(l.status==="fulfilled"&&l.value?.success)return S.set(e,{providerId:s[i],timestamp:Date.now()}),l.value}return null}async function $(r,t,o){const e=t.replace(/\/+$/,""),a={Authorization:`Bearer ${o}`,Accept:"application/json"};try{switch(r){case"zhipu":{const s=await fetch(`${e}/api/monitor/usage/quota/limit`,{method:"GET",headers:{...a,Authorization:o,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json();if(n.success===!1)return null;const i=n.data;if(!i)return null;const l=typeof i.level=="string"?i.level:null,c=j(i);return{provider:"zhipu",providerLabel:"Zhipu GLM",planName:l,tiers:c,balance:null,success:!0,error:null}}case"deepseek":{const s=await fetch(`${e}/user/balance`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json(),i=n.is_available===!0,c=(Array.isArray(n.balance_infos)?n.balance_infos:[])[0];if(!c)return null;const u=String(c.currency??"CNY"),d=p(c.total_balance);return{provider:"deepseek",providerLabel:"DeepSeek",planName:null,tiers:[],balance:{kind:"currency",remaining:d??0,total:null,used:null,unit:u},success:!0,error:i?null:"Insufficient balance"}}case"kimi":{const s=await fetch(`${e}/coding/v1/usages`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json();if(!Array.isArray(n.limits)&&!n.usage)return null;const i=[],l=Array.isArray(n.limits)?n.limits:[];for(const u of l){const d=u.detail;if(!d)continue;const f=p(d.limit)??1,b=p(d.remaining)??0,_=T(d.resetTime),g=Math.max(0,f-b);i.push({name:"five_hour",label:"5h limit",usedPercent:f>0?Math.round(g/f*1e4)/100:0,resetsAt:_})}const c=n.usage;if(c){const u=p(c.limit)??1,d=p(c.remaining)??0,f=T(c.resetTime),b=Math.max(0,u-d);i.push({name:"weekly_limit",label:"Weekly limit",usedPercent:u>0?Math.round(b/u*1e4)/100:0,resetsAt:f})}return{provider:"kimi",providerLabel:"Kimi",planName:null,tiers:i,balance:null,success:!0,error:null}}case"openrouter":{const s=await fetch(`${e}/api/v1/credits`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json(),i=n.data??n;if(i.total_credits===void 0&&i.total_usage===void 0)return null;const l=p(i.total_credits)??0,c=p(i.total_usage)??0,u=l-c;return{provider:"openrouter",providerLabel:"OpenRouter",planName:null,tiers:[],balance:{kind:"currency",remaining:u,total:l,used:c,unit:"USD"},success:!0,error:null}}case"stepfun":{const s=await fetch(`${e}/v1/accounts`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json();if(n.balance===void 0)return null;const i=p(n.balance)??0;return{provider:"stepfun",providerLabel:"StepFun",planName:null,tiers:[],balance:{kind:"currency",remaining:i,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"minimax_cn":case"minimax_en":{const s=await fetch(`${e}/v1/api/openplatform/coding_plan/remains`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json(),i=n.base_resp;if(i&&typeof i.status_code=="number"&&i.status_code!==0)return null;const c=(Array.isArray(n.model_remains)?n.model_remains:[])[0];if(!c)return null;const u=[],d=p(c.current_interval_total_count)??0,f=p(c.current_interval_usage_count)??0;if(d>0){const b=typeof c.end_time=="number"?c.end_time:null;u.push({name:"five_hour",label:"5h limit",usedPercent:Math.round(f/d*1e4)/100,resetsAt:b!==null?w(b):null})}return{provider:r,providerLabel:"MiniMax",planName:null,tiers:u,balance:null,success:!0,error:null}}case"siliconflow_cn":case"siliconflow_en":{const s=await fetch(`${e}/v1/user/info`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const i=(await s.json()).data;if(!i)return null;const l=p(i.totalBalance)??0;return{provider:r,providerLabel:"SiliconFlow",planName:null,tiers:[],balance:{kind:"currency",remaining:l,total:null,used:null,unit:"CNY"},success:!0,error:null}}case"novita":{const s=await fetch(`${e}/v3/user/balance`,{method:"GET",headers:a,signal:AbortSignal.timeout(h)});if(!s.ok)return null;const n=await s.json();if(n.availableBalance===void 0)return null;const i=(p(n.availableBalance)??0)/1e4;return{provider:"novita",providerLabel:"Novita AI",planName:null,tiers:[],balance:{kind:"currency",remaining:i,total:null,used:null,unit:"USD"},success:!0,error:null}}default:return null}}catch{return null}}async function ue(r,t,o){if(!t.trim())return{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:"API key is empty"};const e=P(o),a=E(r);if(a)switch(a.id){case"zhipu":return W(t);case"kimi":return J(t);case"minimax_cn":return O(t,!0);case"minimax_en":return O(t,!1);case"deepseek":return X(t);case"stepfun":return Q(t);case"siliconflow_cn":return z(t,!0);case"siliconflow_en":return z(t,!1);case"openrouter":return ee(t);case"novita":return te(t)}if(e){if(e==="openai_codex")return m("openai_codex","ChatGPT Codex","openai_codex requires Pi OAuth (queryOpenaiCodexQuota), not base URL probing");const n=await $(e,r,t);return n||m(e,e,`Quota API unavailable through base URL: ${r}`)}const s=await re(r,t);return s||{provider:"unknown",providerLabel:"Unknown",planName:null,tiers:[],balance:null,success:!1,error:`Could not identify provider for base URL: ${r}`}}export{E as detectProvider,L as detectProviderFromModel,P as normalizeProviderId,ue as queryProviderQuota,x as readKimiProviderSettings,le as readPiProviderSettings,ce as resolveKimiProviderSettings};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fetchRelayCredentialWithRetry as l,RelayFetchError as c}from"./relay-credential-fetch.js";const p=15e3;function a(n){return n instanceof Error?n.message:String(n)}function o(n){if(n instanceof c)return n.bizCode?.trim()||n.code;const e=n?.code;return typeof e=="string"&&e.trim()?e.trim():"INTERNAL"}class u{ports;lastRevision=null;applyingFromServer=0;chain=Promise.resolve();constructor(e){this.ports=e}get knownRevision(){return this.lastRevision}syncOnConnect(){return this.enqueue(()=>this.doSync())}applyFromLocalAction(e){return this.enqueue(()=>this.doApply(e))}reportLocalChange(){if(this.applyingFromServer>0)return;const e=this.lastRevision;e!=null&&this.safeReport({applied:this.currentApplied(),revision:e})}enqueue(e){const t=this.chain.catch(()=>{}).then(e);return this.chain=t.then(()=>{},()=>{}),t}async doSync(){const e=this.ports.getLocalState();let t;try{t=await this.ports.sendSyncRequest({local_enabled:e.enabled,...e.model?{local_model:e.model}:{}},p)}catch(i){this.ports.log.warn(`relay_state_sync_request not answered: ${a(i)}`);return}if(t.cmd==="error"){const i=t.payload??{};this.ports.log.warn(`relay_state_sync_request rejected by server: code=${i.code??"?"} msg=${i.msg??""}`);return}const r=t.payload??{};if(r.status!=="ok"){this.ports.log.warn(`relay_state_sync_result failed: ${r.error_code??""} ${r.error_msg??""}`.trim());return}const s=Number(r.revision);if(!Number.isFinite(s)){this.ports.log.warn("relay_state_sync_result missing/invalid revision; ignored");return}this.lastRevision=s;try{r.enabled?await this.ensureEnabled(r.model?.trim()||void 0,r.credential):await this.guarded(()=>this.ports.applyDisable())}catch(i){this.ports.log.warn(`relay state apply after sync failed: ${a(i)}`),this.safeReport({applied:this.currentApplied(),revision:s,error_code:o(i)});return}this.safeReport({applied:this.currentApplied(),revision:s})}async doApply(e){const t=e.revision;this.lastRevision=t;const r=e.model?.trim()||void 0;try{return e.enabled?await this.ensureEnabled(r,void 0):await this.guarded(()=>this.ports.applyDisable()),{ok:!0,revision:t}}catch(s){return this.ports.log.warn(`apply_relay_state failed: ${a(s)}`),{ok:!1,error_code:o(s),error_msg:a(s),revision:t}}}async ensureEnabled(e,t){const r=t?.api_key?.trim();if(r){await this.guarded(()=>this.ports.applyEnable({apiKey:r,anthropicBaseUrl:t?.anthropic_base_url?.trim()||void 0,openaiBaseUrl:t?.openai_base_url?.trim()||void 0,model:e},e));return}const s=this.ports.getLocalState();if(s.enabled&&(!e||!s.model||s.model===e))return;const i=await l(this.ports.sendCredentialRequest,e?{model:e}:{});await this.guarded(()=>this.ports.applyEnable(i,e??i.model))}async guarded(e){this.applyingFromServer++;try{await e()}finally{this.applyingFromServer--}}currentApplied(){try{return this.ports.getLocalState().enabled}catch{return!1}}safeReport(e){try{this.ports.sendReport(e)}catch(t){this.ports.log.warn(`relay_state_report not sent: ${a(t)}`)}}}export{u as RelayStateSyncer};
|
|
@@ -42,19 +42,21 @@ terminal state, then report the actual result back to the user.
|
|
|
42
42
|
calm cadence — wait ~15–30s between polls, never spin in a tight loop. Each
|
|
43
43
|
entry has one mutually-exclusive `state`; act on it:
|
|
44
44
|
- `running` — still working. Keep polling.
|
|
45
|
-
- `completed` — done.
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
- `completed` — done. The same state entry includes `final_result`; go to
|
|
46
|
+
step 3.
|
|
47
|
+
- `failed` — errored. Report its `stop_reason`; do not query message history.
|
|
48
48
|
- `waiting_approval` / `waiting_question` — the agent is blocked on the owner
|
|
49
49
|
(approve/deny, or answer a question) and will **not** progress on its own.
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
- `idle` — no active task / stopped.
|
|
53
|
-
|
|
50
|
+
Surface the waiting state and session id, then stop polling — the user has
|
|
51
|
+
to act in that session. Do not query message history.
|
|
52
|
+
- `idle` — no active task / stopped. Report the state and `stop_reason` when
|
|
53
|
+
present; do not query message history.
|
|
54
54
|
|
|
55
|
-
3. **Read the answer
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
3. **Read the answer from state.** For `completed`, read the single
|
|
56
|
+
`final_result` returned by that exact-session `grix_chat_state_query` call and
|
|
57
|
+
summarize it. If `final_result.found` is false, say that the task completed
|
|
58
|
+
without a persisted plain-text final reply. Never call `message_history`
|
|
59
|
+
while monitoring a dispatched task.
|
|
58
60
|
|
|
59
61
|
4. **Reply the result.** Send the conclusion back to the user: what the
|
|
60
62
|
dispatched agent did and how it turned out.
|
|
@@ -93,7 +95,8 @@ local connector config (`agents.json` entry names stay as-is).
|
|
|
93
95
|
first-person voice and tone — never as a third-person relay and never in your
|
|
94
96
|
own narrating voice.
|
|
95
97
|
5. Dispatch is **not** fire-and-forget. After dispatching, monitor the session
|
|
96
|
-
state
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
98
|
+
state with exact-session `grix_chat_state_query`, consume its `final_result`
|
|
99
|
+
only after `completed`, and report the result. Never query message history
|
|
100
|
+
before completion or as a fallback. Never promise a future notification you
|
|
101
|
+
cannot send — if you must stop while it's still running, say so plainly and
|
|
102
|
+
give the user a way to re-check.
|
|
@@ -13,9 +13,11 @@ Use `grix_audit_data` only for read-only conversation audit replay. The owner mu
|
|
|
13
13
|
1. Start from an `auditId` supplied by the user or by audited-turn metadata.
|
|
14
14
|
2. Call `grix_audit_data` with `action: "get_manifest"` and `auditId`.
|
|
15
15
|
3. Read the returned `result`:
|
|
16
|
-
- `content_refs` tells you which text bodies can be fetched.
|
|
16
|
+
- `content_refs` tells you which text bodies can be fetched. Each item includes byte/char counts, capture level, and an estimated token count.
|
|
17
17
|
- `has_spans` tells you whether a span/timeline page is available.
|
|
18
18
|
- `revision` should be reused in later calls when present.
|
|
19
|
+
- `quality.raw_requests_status` distinguishes `not_requested`, `unavailable`, `partial`, and `complete` raw provider body capture. Prefer it over treating the legacy boolean `raw_requests_complete` as proof that raw model requests were stored.
|
|
20
|
+
- `statistics.input_token_attribution` compares provider-reported input tokens with captured input content refs. A large `unattributed_provider_input_tokens` value usually means runtime context such as system/developer instructions, tool schemas, or adapter-added context was included in the model request but was not captured as replay content.
|
|
19
21
|
4. Only fetch what is needed:
|
|
20
22
|
- For timeline/structure details, call `action: "list_spans"` with the same `auditId`, optional `revision`, and pagination `cursor`.
|
|
21
23
|
- For a specific text body, call `action: "get_content_chunk"` with `auditId`, `contentId`, optional `revision`, and pagination `cursor` until `eof` is true.
|
|
@@ -30,7 +32,7 @@ Required:
|
|
|
30
32
|
Optional:
|
|
31
33
|
- `revision`
|
|
32
34
|
|
|
33
|
-
Returns the audit overview/manifest: metadata, stats, `content_refs`, `has_spans`, and related structure. It does not return full text bodies or span pages.
|
|
35
|
+
Returns the audit overview/manifest: metadata, stats, `content_refs`, raw request capture availability, input token attribution, `has_spans`, and related structure. It does not return full text bodies or span pages.
|
|
34
36
|
|
|
35
37
|
Example:
|
|
36
38
|
|
|
@@ -27,7 +27,15 @@ Returns one entry per session with a single mutually-exclusive state:
|
|
|
27
27
|
- `completed` / `failed` — finished
|
|
28
28
|
- `idle` — no task / stopped
|
|
29
29
|
|
|
30
|
-
Also returns `task_title` for easy identification of each chat.
|
|
30
|
+
Also returns `task_title` for easy identification of each chat. When
|
|
31
|
+
`session_id` targets exactly one completed session, that entry additionally
|
|
32
|
+
contains one `final_result` object:
|
|
33
|
+
|
|
34
|
+
- `found` — whether a persisted plain-text final reply exists
|
|
35
|
+
- `msg_id`, `content`, `created_at` — present when `found` is true
|
|
36
|
+
|
|
37
|
+
Non-completed exact-session queries and list queries never include message
|
|
38
|
+
content.
|
|
31
39
|
|
|
32
40
|
Use it to see at a glance which chats are done, still running, or waiting on the
|
|
33
41
|
owner.
|
|
@@ -52,5 +60,5 @@ Parameters:
|
|
|
52
60
|
|
|
53
61
|
1. `grix_chat_state_query` is read-only — safe to call any time to orient yourself.
|
|
54
62
|
2. `grix_chat_state_update` only updates existing records; it will error if the session has no prior state entry.
|
|
55
|
-
3.
|
|
56
|
-
|
|
63
|
+
3. For a completed exact-session query, use its `final_result` directly. Do not
|
|
64
|
+
query message history merely to recover a dispatched task's result.
|
|
@@ -22,8 +22,10 @@ Always call the `grix_query` tool with one `action`:
|
|
|
22
22
|
regardless of type.**
|
|
23
23
|
- `search_favorite_sessions` — list the owner's favorited sessions; optional
|
|
24
24
|
`keyword` filter.
|
|
25
|
-
- `message_history` — read recent messages in a session. Requires
|
|
26
|
-
|
|
25
|
+
- `message_history` — read recent clean messages in a session. Requires
|
|
26
|
+
`sessionId`; defaults to the newest one message and pages backwards with
|
|
27
|
+
`beforeId`. Agent history contains plain text and approval-family cards, not
|
|
28
|
+
tool/status/binding process cards.
|
|
27
29
|
- `message_search` — keyword search inside a session. Requires `sessionId` and
|
|
28
30
|
`keyword`; page backwards with `beforeId`.
|
|
29
31
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as p,readdirSync as c,existsSync as a,mkdirSync as k,cpSync as y,writeFileSync as h,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as m}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as F,MANAGED_MARKER as f}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as w}from"../core/config/index.js";import{log as u}from"../core/log/index.js";const l=S(D(import.meta.url));function d(){const e=[];let i;try{i=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of i){if(!r.isDirectory())continue;const n=t(l,r.name,"SKILL.md");try{const s=p(n,"utf-8"),o=v(s);o?.name&&e.push({name:o.name,description:o.description,trigger:o.trigger,source:"connector",managed:!0})}catch{}}return e}function T(e){let i=[];try{i=x(e)}catch{i=[]}return F([...i,...d()])}function j(e){const i=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return i}for(const n of r){if(!n.isDirectory())continue;const s=t(l,n.name);if(a(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,n.name);y(s,o,{recursive:!0}),h(t(o,f),"","utf8"),i.push(n.name)}catch{}}return i}function C(){return(
|
|
1
|
+
import{readFileSync as p,readdirSync as c,existsSync as a,mkdirSync as k,cpSync as y,writeFileSync as h,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as m}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as F,MANAGED_MARKER as f}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as w}from"../core/config/index.js";import{log as u}from"../core/log/index.js";const l=S(D(import.meta.url));function d(){const e=[];let i;try{i=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of i){if(!r.isDirectory())continue;const n=t(l,r.name,"SKILL.md");try{const s=p(n,"utf-8"),o=v(s);o?.name&&e.push({name:o.name,description:o.description,trigger:o.trigger,source:"connector",managed:!0})}catch{}}return e}function T(e){let i=[];try{i=x(e)}catch{i=[]}return F([...i,...d()])}function j(e){const i=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return i}for(const n of r){if(!n.isDirectory())continue;const s=t(l,n.name);if(a(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,n.name);y(s,o,{recursive:!0}),h(t(o,f),"","utf8"),i.push(n.name)}catch{}}return i}function C(e=process.env){return(e.KIMI_CODE_HOME||"").trim()||t(m(),".kimi-code")}function L(){const e=m(),i=process.env.XDG_CONFIG_HOME||t(e,".config");return[t(w().dataDir,"claude-plugin","skills"),t(e,".codex","skills"),t(e,".gemini","skills"),t(e,".qwen","skills"),t(e,".pi","agent","skills"),t(e,".codewhale","skills"),t(i,"opencode","skills"),t(e,".cursor","skills"),t(e,".openhuman","skills"),t(e,".kiro","skills"),t(e,".reasonix","skills"),t(C(),"skills")]}function O(){const e=[];for(const i of L()){let r;try{r=c(i,{withFileTypes:!0,encoding:"utf8"})}catch{continue}for(const n of r){if(!n.isDirectory())continue;const s=t(i,n.name);if(a(t(s,f)))try{g(s,{recursive:!0,force:!0}),e.push(s)}catch{}}}return e.length>0&&u.info("default-skills",`Cleaned ${e.length} projected skill dir(s)`),e}function b(){const e=d();if(e.length===0){u.warn("default-skills","No connector system skills found \u2014 dist/default-skills/ may be missing SKILL.md files");return}u.info("default-skills",`Connector system skills available: [${e.map(i=>i.name).join(", ")}]`)}export{T as buildReportedSkills,O as cleanupProjectedSkills,b as logDefaultSkillsCheck,C as resolveKimiCodeHome,d as scanDefaultSkills,j as syncDefaultSkillsToDir};
|
package/dist/grix.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import k from"node:path";import{writeFileSync as
|
|
3
|
-
Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),
|
|
2
|
+
import k from"node:path";import{writeFileSync as Y}from"node:fs";import{Manager as me}from"./manager.js";import{ensureGrixDirs as he,initLogger as ye,log as s,installProcessLogRotation as we,setConsoleOutput as q}from"./core/log/index.js";import{HealthServer as Se,bindPortOrFail as z}from"./core/runtime/index.js";import{writePidFile as Re,removePidFile as C,readDaemonPid as Ae}from"./core/runtime/index.js";import{resolveRuntimePaths as H}from"./core/config/index.js";import{supportsNonMitmRelayConfig as B}from"./core/config/provider-env.js";import{ServiceManager as xe}from"./service/service-manager.js";import{killProcessesByCommandLine as Ee,isWindowsElevated as ve}from"./service/process-control.js";import{buildServiceID as be}from"./service/service-paths.js";import{acquireDaemonLock as De,isLockHolderSameProcess as Pe,readDaemonLock as M,releaseDaemonLock as T}from"./runtime/daemon-lock.js";import{writeDaemonStatus as _,removeDaemonStatus as Ie}from"./runtime/service-state.js";import{AdminServer as ke,generateToken as Ce,writeTokenFile as Te}from"./core/admin/index.js";import{initSentry as Ue,closeSentry as G,reportFatal as N}from"./core/observability/sentry.js";import{initProxyManager as $e,getProxyManager as m,relayHostsForClientType as Q}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as _e,disableAllRelayAndRestart as Fe,setOneAgentRelayAndRestart as Z}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as ee,RelayCredentialError as te}from"./core/proxy/relay-credential.js";import{RelayFetchError as re,RelayToggleCoordinator as Le}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as Oe,clearHermesProfileRelay as He,discoverHermesProfiles as Be}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as Me,enableRelayCredential as Ge,RelayRouteError as oe}from"./core/proxy/relay-credential-router.js";import{resolveClientVersion as Ne}from"./core/util/client-version.js";import{parseCliArgs as je}from"./core/util/cli-args.js";const{command:x,flags:S,unknownFlags:j}=je(process.argv.slice(2));if(j.length>0&&(console.error(`Unknown option${j.length>1?"s":""}: ${j.map(o=>`--${o}`).join(", ")}
|
|
3
|
+
Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),S.version&&(console.log(Ne()),process.exit(0)),S.help&&(console.log(`grix-connector \u2014 Unified AI Agent Bridge
|
|
4
4
|
|
|
5
5
|
Usage: grix-connector <command> [options]
|
|
6
6
|
|
|
@@ -34,9 +34,9 @@ Examples:
|
|
|
34
34
|
grix-connector start # Start as system service
|
|
35
35
|
grix-connector status # Check service status
|
|
36
36
|
grix-connector restart # Restart the service
|
|
37
|
-
`),process.exit(0)),
|
|
37
|
+
`),process.exit(0)),x==="reload"){const o=Ae();o||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(o,0)}catch{console.error(`reload failed: daemon process ${o} is not running (stale pid file)`),process.exit(1)}{const c=M(H().daemonLockFile);c&&c.pid===o&&!Pe(c)&&(console.error(`reload failed: pid ${o} has been reused by another process (stale pid file)`),process.exit(1))}try{process.kill(o,"SIGHUP"),console.log(JSON.stringify({ok:!0,signaled:o},null,2)),process.exit(0)}catch(c){console.error(`reload failed: ${c instanceof Error?c.message:c}`),process.exit(1)}}const ne=["start","stop","restart","status"];if(x&&ne.includes(x)){process.platform==="win32"&&["start","stop","restart"].includes(x)&&!ve()&&console.warn(`Warning: Not running as administrator. Task Scheduler registration is skipped;
|
|
38
38
|
using Startup folder auto-start instead. For full Task Scheduler integration,
|
|
39
|
-
right-click the terminal and select "Run as administrator".`);const
|
|
40
|
-
Valid commands: ${
|
|
41
|
-
`),
|
|
42
|
-
`)}catch{}
|
|
39
|
+
right-click the terminal and select "Run as administrator".`);const o=H(),c=S["config-dir"]??(S.profile?k.join(o.configDir,S.profile):void 0),h=k.resolve(process.argv[1]||`${o.rootDir}/dist/grix.js`),p=new xe({cliPath:h,nodePath:process.execPath});try{let u;switch(x){case"start":(await p.status({rootDir:o.rootDir})).installed?u=await p.start({rootDir:o.rootDir}):u=await p.install({rootDir:o.rootDir,configDir:c});break;case"stop":u=await p.stop({rootDir:o.rootDir});break;case"restart":(await p.status({rootDir:o.rootDir})).installed?u=await p.restart({rootDir:o.rootDir}):u=await p.install({rootDir:o.rootDir,configDir:c});break;case"status":u=await p.status({rootDir:o.rootDir});break}console.log(JSON.stringify(u,null,2)),process.exit(0)}catch(u){console.error(`${x} failed: ${u instanceof Error?u.message:u}`),process.exit(1)}}else x&&(console.error(`Unknown command: ${x}
|
|
40
|
+
Valid commands: ${ne.join(", ")}`),process.exit(1));const l=H(),Ke=S["config-dir"]??(S.profile?`${l.configDir}/${S.profile}`:void 0),r=new me,F=new Se,ae=Ce(),E=new ke(ae);let K=!1,D;async function se(o){process.stderr.write(o.message+`
|
|
41
|
+
`),s.error("main",o.message.replace(/\n/g," \u2014 "));const c=M(l.daemonLockFile);c?.pid===process.pid&&c.instance_id===D&&await _(l.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:D,updated_at:Date.now(),reason:`port_bind_${o.kind}:${o.label}:${o.port}`}).catch(()=>{}),await G(),T(l.daemonLockFile).catch(()=>{}),C(),process.exit(1)}async function L(o){if(K)return;K=!0,s.info("main",`Received ${o}, shutting down...`),F.markShuttingDown();const c=setTimeout(()=>{s.error("main","Shutdown timed out, forcing exit"),T(l.daemonLockFile).catch(()=>{}),C(),process.exit(2)},1e4);try{await r.stop(),await m()?.stop().catch(()=>{}),await E.stop(),await F.stop(),await G(),await T(l.daemonLockFile),await Ie(l.daemonStatusFile).catch(()=>{}),clearTimeout(c),C(),s.info("main","Shutdown complete"),process.exit(0)}catch(h){s.error("main",`Shutdown error: ${h}`),T(l.daemonLockFile).catch(()=>{}),C(),process.exit(2)}}async function Ve(){if(he(),ye(),we(l.stdoutLogFile,l.stderrLogFile),q(!1),await Ue(),process.platform==="win32"){const e=be(l.rootDir,"win32");await Ee(e,{platform:"win32"})}try{D=(await De(l.daemonLockFile,l.rootDir)).instance_id}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}Re(),s.info("main",`grix-connector starting (PID ${process.pid})`),await _(l.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:D,updated_at:Date.now()});const o=parseInt(S["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await z({label:"health",port:o,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:n=>F.start(n)});e&&await se(e)}const c=k.join(l.dataDir,"health-port");Y(c,String(o),"utf-8"),process.on("SIGINT",()=>L("SIGINT")),process.on("SIGTERM",()=>L("SIGTERM")),process.on("SIGHUP",()=>{K||(s.info("main","Received SIGHUP, reloading config..."),r.reload().then(e=>s.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>s.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let h="",p=0,u;process.on("uncaughtException",e=>{const n=e instanceof Error?e.stack??e.message:String(e);n===h?(p++,(p<=3||p%100===0)&&s.error("main",`Uncaught exception (x${p}): ${n}`)):(p>3&&s.error("main",`Previous exception repeated ${p} times total`),h=n,p=1,s.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),u||(u=setTimeout(()=>{p>3&&s.error("main",`Previous exception repeated ${p} times total`),h="",p=0,u=void 0},1e4).unref())),!ie(e)&&(N(e,"uncaughtException"),L("uncaughtException"))}),process.on("unhandledRejection",e=>{s.error("main",`Unhandled rejection: ${e}`),!ie(e)&&(N(e,"unhandledRejection"),L("unhandledRejection"))});const b=$e(l.dataDir);await b.clearRuntimeState();const P=b.getRelayAgents();if(P.length>0)try{await b.startIfAnyRelayAgent(),s.info("main",`mitm proxy started for relay agents: ${P.join(", ")} (per-agent; others stay direct)`)}catch(e){s.error("main",`mitm proxy FAILED to start (relay agents: ${P.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else s.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');if(F.setStatusProvider(()=>r.getAgentsStatus()),await r.start(Ke),P.length>0){const e=r.getAgentsStatus();for(const n of P){const d=e.find(t=>t.name===n);if(!d)continue;const R=Q(d.clientType);R.length!==0&&await b.setAgentRelayEnabled(n,!0,{relayHosts:R}).catch(t=>{s.warn("main",`failed to reconcile relay hosts for "${n}": ${t}`)})}}const V=parseInt(S["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);E.setAgentHandler({list:()=>r.getAgentsStatus(),add:e=>r.addAgent(e),remove:e=>r.removeAgent(e),restart:e=>r.restartAgent(e),reload:()=>r.reload()}),E.setUpgradeHandler({check:()=>r.checkUpgrade(),trigger:()=>r.triggerUpgrade()}),E.setProbeHandler({probeAll:e=>r.probeAll(e),probeOne:(e,n)=>r.probeOne(e,n)}),E.setInstallHandler({listInstallable:()=>r.listInstallable(),installAgent:e=>r.installAgent(e),getInstallProgress:e=>r.getInstallProgress(e)});let I=null;if(m()){const e=async()=>{const t=m();t&&await _e(t,r)&&s.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};r.setRelayEnvSettledHandler(()=>{e().catch(t=>{s.warn("main",`failed to stop idle mitm proxy: ${t}`)})});const n=()=>{const t=m(),a=t.getRelayAgents(),i=t.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:r.getAgentsWithStaleRelayEnv(),degradedRelayAgents:i,runtime:t.getRuntimeInfo(),config:t.getConfigSnapshot()}},d=new Le,R={status:()=>n(),setAgentRelay:async(t,a,i)=>{const f=m(),w={info:y=>s.info("main",y),warn:y=>s.warn("main",y)},A=y=>r.getAgentsStatus().find(v=>v.name===y),g=A(t);if(!a){d.cancel(t);const y=await d.runExclusive(t,async()=>{if(g&&B(g.clientType))return await r.setAgentProvider(t,void 0),{...n(),restarted:!0,busy:!1};const{restarted:v,busy:O}=await Z(f,r,w,{agentName:t,enabled:!1});return{...n(),restarted:v,busy:O}});return r.reportRelayStateLocalChange(t),y}if(!g)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});if(!B(g.clientType)&&Q(g.clientType).length===0)throw Object.assign(new Error(`client type "${g.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const de=await d.runExclusive(t,async()=>{const y=d.epoch(t),v=A(t);if(!v)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});const O=B(v.clientType),X=String(v.agentId??"").trim();if(!X)throw new te(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const J=d.waitCancelled(t,y);let $;try{$=await Promise.race([r.fetchRelayCredential(t,{model:i}),J.promise.then(()=>{throw new re("relay enable cancelled by a later disable","CANCELLED")})])}finally{J.dispose()}d.assertCurrent(t,y);const{restarted:pe,busy:ge}=await ee(f,r,A,w,{localName:t,agentId:X,virtualKey:$.apiKey,anthropicBaseUrl:$.anthropicBaseUrl,openaiBaseUrl:$.openaiBaseUrl,model:i},(ue,fe)=>r.setAgentProvider(ue,fe));if(d.epoch(t)!==y)throw O?await r.setAgentProvider(t,void 0):await Z(f,r,w,{agentName:t,enabled:!1}),new re("relay enable cancelled by a later disable","CANCELLED");return{...n(),restarted:pe,busy:ge}});return r.reportRelayStateLocalChange(t),de},setAgentRelayCredential:async(t,a)=>{const i=m(),f=r.getAgentsStatus(),{restarted:w,busy:A}=await ee(i,r,g=>f.find(U=>U.name===g),{info:g=>s.info("main",g),warn:g=>s.warn("main",g)},{localName:t,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model},(g,U)=>r.setAgentProvider(g,U));return r.reportRelayStateLocalChange(t),{...n(),restarted:w,busy:A}},disableAll:async()=>{const t=m();for(const i of r.getAgentsStatus())d.cancel(i.name);await Fe(t,r,{info:i=>s.info("main",i),warn:i=>s.warn("main",i)});const a=await r.clearDirectProviderConfigs();return a.length>0&&s.info("main",`relay disable-all cleared native provider config for: ${a.join(", ")}`),n()},setRoute:async(t,a)=>{const i=a,f=m();return f.setRoute({routeKey:t,targetBaseUrl:i.targetBaseUrl,...i.headers?{headers:i.headers}:{},...i.model?{model:i.model}:{},...i.modelMap?{modelMap:i.modelMap}:{},...i.passthrough?{passthrough:!0}:{},...i.relayOnly?{relayOnly:!0}:{},...i.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await f.persistConfig(),n()},deleteRoute:async t=>{const a=m();a.deleteRoute(t),await a.persistConfig()},setDefaultRoute:async t=>{const a=m();return a.setDefaultRouteKey(t),await a.persistConfig(),n()},setInterceptHosts:async t=>{const a=m();return a.setInterceptHosts(t),await a.persistConfig(),n()}};I=R,E.setProxyHandler(R),r.setRelayStateApplier({getLocalState:t=>{const a=m();if(a.getRelayAgents().includes(t)){const f=r.getAgentsStatus().find(g=>g.name===t),w=`grix-gateway-${String(f?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(g=>g.routeKey===w)?.model?.trim()||void 0}}const i=r.getAgentProvider(t);return i?.api_key?.trim()?{enabled:!0,model:i.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(t,a,i)=>{const f=r.getAgentsStatus().find(A=>A.name===t),w=String(f?.agentId??"").trim();if(!w)throw new te(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");await R.setAgentRelayCredential(t,{agentId:w,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:i??a.model})},applyDisable:async t=>{await R.setAgentRelay(t,!1)}})}const W={listAgents:()=>r.getAgentsStatus(),enableManaged:(e,n,d)=>{if(!I)throw new oe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return I.setAgentRelayCredential(e,{agentId:n,virtualKey:d.virtualKey,anthropicBaseUrl:d.anthropicBaseUrl,openaiBaseUrl:d.openaiBaseUrl,model:d.model})},disableManaged:e=>{if(!I)throw new oe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return I.setAgentRelay(e,!1)},enableHermesProfile:(e,n)=>Oe({agentId:e,baseUrl:n.openaiBaseUrl??"",virtualKey:n.virtualKey,model:n.model??""}),disableHermesProfile:e=>He(e)};E.setRelayCredentialHandler({listHermesProfiles:()=>Be(),enable:async(e,n)=>{const{target:d,result:R}=await Ge(W,e,n);return{target:d,...R}},disable:async e=>{const{target:n,result:d}=await Me(W,e);return{target:n,...d}}});{const e=await z({label:"admin",port:V,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:n=>E.start(n)});e&&await se(e)}const le=k.join(l.dataDir,"admin-token"),ce=k.join(l.dataDir,"admin-port");Te(le,ae),Y(ce,String(V),"utf-8"),await _(l.daemonStatusFile,{state:"running",pid:process.pid,instance_id:D,updated_at:Date.now()}),process.send&&process.send("ready"),s.info("main","grix-connector ready")}Ve().catch(async o=>{const c=`Fatal: ${o instanceof Error?o.stack??o.message:String(o)}`;try{process.stderr.write(`${c}
|
|
42
|
+
`)}catch{}q(!1),s.error("main",c),N(o,"startup");const h=M(l.daemonLockFile);h?.pid===process.pid&&h.instance_id===D&&await _(l.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:h.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await G(),T(l.daemonLockFile).catch(()=>{}),C(),process.exit(1)});const We=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function ie(o){return o instanceof Error&&"code"in o?We.has(o.code):!1}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: locate-code-by-layer
|
|
3
|
+
description: "Token-bounded, architecture-first code location through a private codebase-memory Gateway. Use whenever an Agent must understand or change implementation code: diagnose bugs, add features, refactor, review code, locate routes/controllers/services/models/views, find symbol definitions, or trace call paths and dependencies. It selects a layer and module before symbol lookup, returns compact metadata and file/line ranges instead of source, and replaces direct use of raw codebase-memory MCP tools. Do not use it for a pure documentation/configuration lookup when an exact literal and narrow path are already known."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Locate Code By Layer
|
|
7
|
+
|
|
8
|
+
Use the `codebase-navigator` MCP as the only routine code-discovery interface. It privately calls codebase-memory, enforces layer-first navigation, and returns a compact location packet.
|
|
9
|
+
|
|
10
|
+
## Agent decision
|
|
11
|
+
|
|
12
|
+
Before reading implementation files, ask whether the task requires finding where behavior is defined or connected. If yes, invoke this skill and start with `locate_code`. Do not attempt a repository-wide search first.
|
|
13
|
+
|
|
14
|
+
Provide the whole problem in one request. Include the observed behavior, expected behavior, exact error text, known symbol, route, or path hint when available. More discriminating input produces a smaller result.
|
|
15
|
+
|
|
16
|
+
## Required workflow
|
|
17
|
+
|
|
18
|
+
1. Call `locate_code` once with the complete problem. Include an exact error, known symbol, or path hint when available.
|
|
19
|
+
2. Follow the returned status:
|
|
20
|
+
- `located`: read only `recommended_reads`, beginning with the first range.
|
|
21
|
+
- `ambiguous`: call `refine_location` with one returned layer or candidate. Do not restart a global search.
|
|
22
|
+
- `architecture_uncertain`: follow `next_action`. If it is `refine_location`, reuse the returned `locator_id` with one exact symbol/path clue. Otherwise call `get_project_outline`, choose a layer, then call `locate_code` with that layer.
|
|
23
|
+
- `insufficient_coverage`: use `refine_location` with one discriminating hint. If still unresolved, report the indexed scope gap.
|
|
24
|
+
- `dependency_missing`: stop discovery, explain that Codebase is required, and ask whether the user wants it installed. Never install it without explicit approval.
|
|
25
|
+
- `dependency_misconfigured`, `dependency_not_executable`, or `dependency_unhealthy`: stop discovery, report the exact dependency repair action, and ask before changing system configuration or permissions. Do not misdiagnose these states as a narrower-problem issue.
|
|
26
|
+
- `not_indexed`: stop discovery, explain that the resolved project has no usable Codebase index, and ask whether the user wants it indexed with the official Codebase tooling.
|
|
27
|
+
- `stale_index`: stop discovery and ask whether the user wants the project index refreshed.
|
|
28
|
+
3. After reading at most the recommended ranges, form a concrete hypothesis. Read one directly related symbol only if the first range is insufficient.
|
|
29
|
+
4. Modify code and run the narrowest relevant test only after the target is established.
|
|
30
|
+
|
|
31
|
+
Installation, dependency repair, first-time indexing, and index refresh are external mutations and require explicit user confirmation. The read-only Gateway only detects these states and returns a consent-aware `next_action`; it never installs Codebase, changes system configuration or permissions, or changes an index itself.
|
|
32
|
+
|
|
33
|
+
For a location-only question, the first direct definition, assignment, or registration matching the requested construct is terminal evidence. Stop immediately and report that file/range; do not inspect callers, callees, adjacent implementations, or alternative files unless the user asked for behavior analysis.
|
|
34
|
+
|
|
35
|
+
## Tool rules
|
|
36
|
+
|
|
37
|
+
- Treat `locate_code` as the default entry point.
|
|
38
|
+
- When a path or symbol is known, pass it as `fileHint` or `knownSymbol`; the Gateway uses one compact, source-free exact search before falling back to architecture routing.
|
|
39
|
+
- Use `get_project_outline` only when architecture is uncertain or the user explicitly asks for an architecture view.
|
|
40
|
+
- Refine a locator at most twice. If two refinements fail, ask for a symbol, error text, or path clue.
|
|
41
|
+
- Never request pagination or expand all matches.
|
|
42
|
+
- Never ask the Gateway for source; open the returned repository-relative line ranges using the local filesystem.
|
|
43
|
+
- Do not call raw `search_graph`, `trace_path`, `get_code_snippet`, `query_graph`, or `get_architecture` from the hidden downstream MCP.
|
|
44
|
+
- Do not automatically install Codebase, create an index, or refresh an index. Ask the user first, then use only the official Codebase installation and indexing workflow after approval.
|
|
45
|
+
|
|
46
|
+
## Narrow fallback
|
|
47
|
+
|
|
48
|
+
Use shell search only for an exact error string, configuration key, generated file, Markdown, shell script, or a path explicitly reported as uncovered. Limit it to the selected module. Never run repository-wide broad search or read whole source files as a substitute for the Gateway.
|
|
49
|
+
|
|
50
|
+
After the Gateway exhausts its refinements, the entire shell fallback budget is one exact-literal search inside the selected layer/module and at most two exact line-range reads. Do not issue a second `rg`, widen the path, scan directories, or read a whole source file. If that budget does not establish the target, report the unresolved index/scope gap. For a location-only task, stop after the first matching definition, assignment, or registration.
|
|
51
|
+
|
|
52
|
+
## Result contract
|
|
53
|
+
|
|
54
|
+
The Gateway returns a location packet, never source code. The Agent receives:
|
|
55
|
+
|
|
56
|
+
- `status` and `next_action`, telling the Agent whether to read, refine, inspect the outline, or refresh the index;
|
|
57
|
+
- dependency failures use `offer_install`, `repair_dependency_config`, `repair_dependency_permissions`, or `repair_dependency`;
|
|
58
|
+
- missing and stale indexes use `offer_index` or `offer_index_refresh`;
|
|
59
|
+
- `selected_layer` and bounded module scopes, explaining which architectural area was chosen;
|
|
60
|
+
- at most three ranked symbol candidates with stable candidate IDs and confidence evidence;
|
|
61
|
+
- `recommended_reads`, containing at most two repository-relative files and exact line ranges;
|
|
62
|
+
- at most five one-hop callers, callees, or dependencies needed to validate the target;
|
|
63
|
+
- `locator_id` for at most two bounded refinements;
|
|
64
|
+
- an index fingerprint and response-budget record for freshness and token auditing.
|
|
65
|
+
|
|
66
|
+
After receiving `located`, read only the first recommended range. The packet is a navigation decision, not an instruction to load every candidate.
|
|
67
|
+
|
|
68
|
+
For installation, architecture, policy limits, configuration, and status meanings, read [references/gateway-architecture.md](references/gateway-architecture.md).
|