@tocca-systems/twp-cli 0.17.0 → 0.18.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 +46 -3
- package/command-model/company.json +19 -0
- package/command-model/department.json +10 -0
- package/command-model/equipment.json +5 -0
- package/command-model/index.json +20 -20
- package/command-model/invoice.json +24 -2
- package/command-model/meeting.json +29 -9
- package/command-model/my-task.json +1 -0
- package/command-model/note.json +34 -8
- package/command-model/notification.json +35 -0
- package/command-model/private-task.json +46 -1
- package/command-model/project-member.json +2 -1
- package/command-model/project-task-comment.json +1 -1
- package/command-model/project-task.json +153 -4
- package/command-model/project.json +49 -2
- package/command-model/prospect.json +24 -1
- package/command-model/report.json +62 -18
- package/command-model/survey.json +38 -29
- package/command-model/user.json +2 -1
- package/command-model/wiki.json +29 -5
- package/command-model/workflow-instance.json +8 -3
- package/dist/{ai-dispatch-NTBNFFCS.js → ai-dispatch-27EZS2S3.js} +1 -1
- package/dist/{api-command-UIL4WGMG.js → api-command-BH6ILQNX.js} +1 -1
- package/dist/{app-LLSZV6SM.js → app-4LRDLLTV.js} +22 -21
- package/dist/{chunk-KXFT226N.js → chunk-77CQG7O7.js} +16 -14
- package/dist/chunk-BOBSH3QN.js +9 -0
- package/dist/{chunk-3WJHTPOZ.js → chunk-H3JTPDCJ.js} +7 -4
- package/dist/{chunk-EZCMF4I3.js → chunk-SQSVA6AT.js} +3 -2
- package/dist/{chunk-Y5RTTQ4Y.js → chunk-U4QQNRXF.js} +90 -43
- package/dist/cli.js +41 -27
- package/dist/{commands-UGGBVOYU.js → commands-XYKBLMXT.js} +17 -14
- package/dist/{oneshot-HQJEXZHJ.js → oneshot-5EM5NFTK.js} +8 -7
- package/dist/{run-DWQEHR6I.js → run-XALXQIC3.js} +1 -1
- package/dist/{setup-I4PA2TQW.js → setup-AJ56N6XO.js} +1 -1
- package/dist/{task-7K54BO5U.js → task-VVBXZLPU.js} +38 -7
- package/package.json +1 -1
- package/dist/chunk-S646CPM4.js +0 -9
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{RESIDENT_TOKEN_CAP,activateModeFiles,buildResidentSet,buildSystemPrompt,createAuditLogger,currentBranch,describeAuditLog,displayCwd,runTurn}from"./chunk-
|
|
4
|
-
checkPermission,describePermissionMode,getMode,isModeId,modeSource,nextMode}from"./chunk-
|
|
5
|
-
__toESM}from"./chunk-VSJBJXZO.js";var require_react_production=__commonJS({"node_modules/react/cjs/react.production.js"(exports){"use strict";var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element");var REACT_PORTAL_TYPE=Symbol.for("react.portal");var REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");var REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode");var REACT_PROFILER_TYPE=Symbol.for("react.profiler");var REACT_CONSUMER_TYPE=Symbol.for("react.consumer");var REACT_CONTEXT_TYPE=Symbol.for("react.context");var REACT_FORWARD_REF_TYPE=Symbol.
|
|
3
|
+
import{RESIDENT_TOKEN_CAP,activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,currentBranch,describeAuditLog,displayCwd,runTurn}from"./chunk-U4QQNRXF.js";import{RelayError,builtinCatalog,createRuntime,loadCachedCatalog,modelLabel,pickModel,toModelInfos}from"./chunk-RQFG3OUL.js";import{checkMinSupportedVersion,isBelowMinSupported,minSupportedBlockMessage}from"./chunk-DXXFUNYN.js";import"./chunk-N2UVRM3Z.js";import"./chunk-PMOUHEJQ.js";
|
|
4
|
+
import{applyPermissionMode,checkPermission,describePermissionMode,getMode,isModeId,modeSource,nextMode}from"./chunk-BOBSH3QN.js";import{require_fuzzysort}from"./chunk-DIMZRTLE.js";import{isFullWidth,isWide,stringWidth,stripAnsi}from"./chunk-WVS4W5FY.js";import"./chunk-63LDNYGW.js";import"./chunk-NERYSBA4.js";import"./chunk-RZVI6PMW.js";import{proxyDiagnostics}from"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{__commonJS,
|
|
5
|
+
__export,__require,__toESM}from"./chunk-VSJBJXZO.js";var require_react_production=__commonJS({"node_modules/react/cjs/react.production.js"(exports){"use strict";var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element");var REACT_PORTAL_TYPE=Symbol.for("react.portal");var REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");var REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode");var REACT_PROFILER_TYPE=Symbol.for("react.profiler");var REACT_CONSUMER_TYPE=Symbol.for("react.consumer");var REACT_CONTEXT_TYPE=Symbol.for("react.context");var REACT_FORWARD_REF_TYPE=Symbol.
|
|
6
6
|
for("react.forward_ref");var REACT_SUSPENSE_TYPE=Symbol.for("react.suspense");var REACT_MEMO_TYPE=Symbol.for("react.memo");var REACT_LAZY_TYPE=Symbol.for("react.lazy");var REACT_ACTIVITY_TYPE=Symbol.for("react.activity");var REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition");var MAYBE_ITERATOR_SYMBOL=Symbol.iterator;function getIteratorFn(maybeIterable){if(null===maybeIterable||"object"!==typeof maybeIterable)return null;maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||
|
|
7
7
|
maybeIterable["@@iterator"];return"function"===typeof maybeIterable?maybeIterable:null}var ReactNoopUpdateQueue={isMounted:function(){return false},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}};var assign=Object.assign;var emptyObject={};function Component(props,context,updater){this.props=props;this.context=context;this.refs=emptyObject;this.updater=updater||ReactNoopUpdateQueue}Component.prototype.isReactComponent={};Component.prototype.setState=
|
|
8
8
|
function(partialState,callback){if("object"!==typeof partialState&&"function"!==typeof partialState&&null!=partialState)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,partialState,callback,"setState")};Component.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,"forceUpdate")};function ComponentDummy(){}ComponentDummy.prototype=Component.prototype;function PureComponent2(props,context,updater){
|
|
@@ -1260,8 +1260,8 @@ Text,{children:[(0,import_jsx_runtime8.jsx)(Text,{color:"cyan",children:ev.name.
|
|
|
1260
1260
|
shiftTab2.raw)}\uFF08${hexRaw(shiftTab2.raw)}\uFF09`:"\u672A\u691C\u51FA \u2014 Shift+Tab \u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044"}),!shiftTab2&&tab2?(0,import_jsx_runtime8.jsx)(Text,{color:"yellow",children:"Tab \u306E\u307F\u691C\u51FA\u3002\u3053\u306E\u7AEF\u672B\u306F Shift+Tab \u3092\u7D20\u306E TAB \u3068\u3057\u3066\u9001\u3063\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\uFF08Alt+M / /mode \u3092\u4F7F\u3063\u3066\u304F\u3060\u3055\u3044\uFF09"}):null]}),(0,import_jsx_runtime8.jsxs)(
|
|
1261
1261
|
Box_default,{flexDirection:"column",marginTop:1,children:[(0,import_jsx_runtime8.jsx)(Text,{bold:true,children:"\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\uFF08\u30D7\u30ED\u30AD\u30B7 / CA\uFF09"}),diagnostics.map(line=>(0,import_jsx_runtime8.jsxs)(Text,{children:[(0,import_jsx_runtime8.jsx)(Text,{color:"cyan",children:padDisplay(line.label,22)}),(0,import_jsx_runtime8.jsx)(Text,{color:line.warn===true?"yellow":void 0,children:line.value})]},line.label)),caWarn?(0,import_jsx_runtime8.jsx)(Text,{color:"\
|
|
1262
1262
|
yellow",children:"\u26A0 TLS \u508D\u53D7\u30D7\u30ED\u30AD\u30B7\u914D\u4E0B\u3067\u306F NODE_EXTRA_CA_CERTS \u306B\u30D7\u30ED\u30AD\u30B7\u306E CA \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08Node \u8D77\u52D5\u6642\u306B\u3057\u304B\u8AAD\u307E\u308C\u306A\u3044\u305F\u3081\u3001\u8A2D\u5B9A\u5F8C\u306B twp \u3092\u518D\u8D77\u52D5\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF09"}):null]}),(0,import_jsx_runtime8.jsx)(Text,{dimColor:true,children:"Esc \u3067\u623B\u308B"})]})}var import_react37=__toESM(require_react(),1);function useTerminalSize(){const read=()=>({rows:process.stdout.rows||24,columns:process.stdout.columns||80});const[size,setSize]=(0,import_react37.useState)(read);(0,import_react37.useEffect)(()=>{const onResize=()=>setSize(read());process.stdout.on("resize",onResize);return()=>{process.stdout.off("resize",onResize)}},[]);return size}var import_jsx_runtime9=__toESM(require_jsx_runtime(),1);function paletteFor(text,mode){return text.startsWith("/")&&!text.includes(" ")?filterCommands(text,mode):[]}function insert(b,value){return{text:b.text.slice(0,b.cursor)+value+b.text.slice(b.cursor),cursor:b.cursor+value.length}}var seq=0;var nextId=()=>`i${++seq}`;function fullInputFor(request){const command=request.input["command"];if(typeof command==="string"&&command!=="")return command;return request.preview}function catalogTitleSuffix(source){
|
|
1263
|
-
if(source==="server")return"";return source==="cache"?" \u2014 \u30AD\u30E3\u30C3\u30B7\u30E5":" \u2014 \u7D44\u307F\u8FBC\u307F\u4E00\u89A7\uFF08\u672A\u53D6\u5F97\uFF09"}function App2({initialMode,initialModel,initialCatalog,initialModelWarning,runtime,version,startInDoctor,permissionMode,audit}){const{exit}=use_app_default();const size=useTerminalSize();const stream=useTokenStream();const[items,setItems]=(0,import_react38.useState)(()=>[{id:nextId(),kind:"banner",banner:buildBanner(
|
|
1264
|
-
width:process.stdout.columns||80,branch:currentBranch()})}]);const bufferRef=(0,import_react38.useRef)({text:"",cursor:0});const[buffer,setBufferState]=(0,import_react38.useState)(bufferRef.current);const[mode,setMode]=(0,import_react38.useState)(initialMode);const[model,setModel]=(0,import_react38.useState)(initialModel);const[catalog,setCatalog]=(0,import_react38.useState)(initialCatalog);const[busy,setBusy]=(0,import_react38.useState)(false);const[context,setContext]=(0,import_react38.useState)(
|
|
1263
|
+
if(source==="server")return"";return source==="cache"?" \u2014 \u30AD\u30E3\u30C3\u30B7\u30E5":" \u2014 \u7D44\u307F\u8FBC\u307F\u4E00\u89A7\uFF08\u672A\u53D6\u5F97\uFF09"}function App2({initialMode,initialModel,initialCatalog,initialModelWarning,runtime,version,startInDoctor,permissionMode,permissionLayers,audit}){const{exit}=use_app_default();const size=useTerminalSize();const stream=useTokenStream();const[items,setItems]=(0,import_react38.useState)(()=>[{id:nextId(),kind:"banner",banner:buildBanner(
|
|
1264
|
+
{version,model:initialModel,width:process.stdout.columns||80,branch:currentBranch()})}]);const bufferRef=(0,import_react38.useRef)({text:"",cursor:0});const[buffer,setBufferState]=(0,import_react38.useState)(bufferRef.current);const[mode,setMode]=(0,import_react38.useState)(initialMode);const[model,setModel]=(0,import_react38.useState)(initialModel);const[catalog,setCatalog]=(0,import_react38.useState)(initialCatalog);const[busy,setBusy]=(0,import_react38.useState)(false);const[context,setContext]=(0,import_react38.useState)(
|
|
1265
1265
|
()=>runtime.context.snapshot());const[runningTool,setRunningTool]=(0,import_react38.useState)(null);const[overlay,setOverlay]=(0,import_react38.useState)(startInDoctor?"doctor":"none");const[pendingPermission,setPendingPermission]=(0,import_react38.useState)(null);const[keyLog,setKeyLog]=(0,import_react38.useState)([]);const[ctrlCArmed,setCtrlCArmed]=(0,import_react38.useState)(false);const[pasting,setPasting]=(0,import_react38.useState)(false);const setBuffer=(0,import_react38.useCallback)(fn=>{
|
|
1266
1266
|
bufferRef.current=fn(bufferRef.current);setBufferState(bufferRef.current)},[]);const clearBuffer=(0,import_react38.useCallback)(()=>setBuffer(()=>({text:"",cursor:0})),[setBuffer]);const selectedRef=(0,import_react38.useRef)(0);const[selectedState,setSelectedState]=(0,import_react38.useState)(0);const setSelected=(0,import_react38.useCallback)(next=>{selectedRef.current=typeof next==="function"?next(selectedRef.current):next;setSelectedState(selectedRef.current)},[]);const modeRef=(0,import_react38.useRef)(
|
|
1267
1267
|
mode);modeRef.current=mode;const modelRef=(0,import_react38.useRef)(model);modelRef.current=model;const busyRef=(0,import_react38.useRef)(false);const abortRef=(0,import_react38.useRef)(false);const streamAbortRef=(0,import_react38.useRef)(null);const sleepRef=(0,import_react38.useRef)(null);const permissionResolver=(0,import_react38.useRef)(null);const sessionAllow=(0,import_react38.useRef)(new Set);const demoSessionAllow=(0,import_react38.useRef)(new Set);const lastToolRef=(0,import_react38.useRef)(
|
|
@@ -1271,22 +1271,22 @@ floor=>{const text=minSupportedBlockMessage(version,floor??"");commit({kind:"not
|
|
|
1271
1271
|
return}if(initialModelWarning!==null){commit({kind:"notice",tone:"warn",text:initialModelWarning})}let cancelled=false;const pending=runtime.loadCatalog();catalogFetchRef.current=pending;void pending.then(fetched=>{if(cancelled)return;if(isBelowMinSupported(version,fetched.minSupportedVersion)){blockOnMinSupported(fetched.minSupportedVersion);return}setCatalog(fetched);const picked=pickModel(fetched,modelRef.current);if(picked.model!==modelRef.current){setModel(picked.model);if(picked.warning!==
|
|
1272
1272
|
void 0)commit({kind:"notice",tone:"warn",text:picked.warning})}});return()=>{cancelled=true}},[blockOnMinSupported,commit,initialModelWarning,runtime,version]);const sleep=ms=>new Promise(resolve=>{const timer=setTimeout(()=>{sleepRef.current=null;resolve()},ms);sleepRef.current={timer,resolve}});const abortSleep=()=>{const s=sleepRef.current;if(!s)return;clearTimeout(s.timer);sleepRef.current=null;s.resolve()};const askPermission=spec=>new Promise(resolve=>{setPendingPermission(spec);setSelected(
|
|
1273
1273
|
0);setOverlay("permission");permissionResolver.current=choice=>{setOverlay("none");setPendingPermission(null);permissionResolver.current=null;resolve(choice)}});const runTurn2=(0,import_react38.useCallback)(async text=>{if(busyRef.current){commit({kind:"notice",tone:"warn",text:"\u5B9F\u884C\u4E2D\u3067\u3059\u3002Ctrl+C \u3067\u4E2D\u65AD\u3057\u3066\u304B\u3089\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"});return}busyRef.current=true;abortRef.current=false;setBusy(true);commit({kind:"user",
|
|
1274
|
-
text});const startupCatalog=await catalogFetchRef.current;if(startupCatalog&&isBelowMinSupported(version,startupCatalog.minSupportedVersion)){blockOnMinSupported(startupCatalog.minSupportedVersion);return}const controller=new AbortController;streamAbortRef.current=controller;stream.begin();try{const turnMode=getMode(modeRef.current);const resident=buildResidentSet(turnMode,{...permissionMode!==void 0?{permissionMode}:{}});const result=await runTurn(runtime.client,runtime.context,
|
|
1275
|
-
current,system:buildSystemPrompt({cwd:cwd2,branch,modeLabel:turnMode.label,cliVersion:version,toolNames:resident.tools.map(t=>t.name),...turnMode.prompt!==void 0?{modePrompt:turnMode.prompt}:{}}),signal:controller.signal,onTextDelta:delta=>stream.push(stripTerminalControls(delta)),tools:resident.tools,execute:{mode:turnMode,ctx:{cwd:process.cwd()},sessionAllow:sessionAllow.current,...permissionMode!==void 0?{permissionMode}:{},audit,askPermission:request=>askPermission(
|
|
1276
|
-
request),...request.diff?{diff:request.diff}:{},noAlwaysReason:request.noAlwaysReason}),onStart:(tool,preview)=>{const safe=stripTerminalControls(preview);setRunningTool({name:stripTerminalControls(tool.name),summary:safe,input:safe,output:"",status:"running"})}},onToolUse:()=>{const partial=stream.end();stream.clear();if(partial.trim()!=="")commit({kind:"assistant",text:partial})},onToolResult:(call,toolResult)=>{setRunningTool(
|
|
1277
|
-
const run={name:stripTerminalControls(call.name),summary:label,input:label,output:stripTerminalControls(toolResult.content),status:toolResult.denied===true?"denied":toolResult.isError===true?"error":"done",...toolResult.diff?{diff:toolResult.diff}:{}};lastToolRef.current=run;commit({kind:"tool",run});stream.begin()}});const full=stream.end();stream.clear();if(full.trim()!=="")commit({kind:"assistant",text:full});if(result.maxStepsReached){
|
|
1278
|
-
\u6253\u3061\u5207\u308A\u307E\u3057\u305F\u3002\u7D9A\u304D\u306F\u540C\u3058\u4F1A\u8A71\u3067\u6307\u793A\u3057\u3066\u304F\u3060\u3055\u3044"})}if(result.droppedMessages>0){commit({kind:"notice",tone:"warn",text:`\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4E0A\u9650\u306B\u8FD1\u3065\u3044\u305F\u305F\u3081\u3001\u53E4\u3044\u3084\u308A\u53D6\u308A ${result.
|
|
1279
|
-
if(result.upstreamError!==null){commit({kind:"notice",tone:"error",text:`\u30E2\u30C7\u30EB\u306E\u5FDC\u7B54\u304C\u9014\u4E2D\u3067\u7D42\u308F\u308A\u307E\u3057\u305F: ${result.upstreamError}`})}if(result.aborted){commit({kind:"notice",tone:"warn",text:"\u4E2D\u65AD\u3057\u307E\u3057\u305F\uFF08Ctrl+C\uFF09\u2014 \u3053\u3053\u307E\u3067\u306E\u6D88\u8CBB\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u306B\u8A08\u4E0A\u3055\u308C\u307E\u3059"})}else if(result.
|
|
1280
|
-
commit({kind:"notice",tone:"warn",text:"\u30E2\u30C7\u30EB\u304B\u3089\u30C6\u30AD\u30B9\u30C8\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F"})}}catch(err){const partial=stream.end();stream.clear();if(partial.trim()!=="")commit({kind:"assistant",text:partial});commit({kind:"notice",tone:"error",text:err instanceof RelayError?err.message:`\u30E2\u30C7\u30EB\u53D6\u6B21\u3067\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F: ${err.message}`})}finally{streamAbortRef.
|
|
1281
|
-
null;setRunningTool(null);setContext(runtime.context.snapshot());busyRef.current=false;setBusy(false)}},[audit,blockOnMinSupported,branch,commit,cwd2,permissionMode,runtime,stream,version]);const runDemo=(0,import_react38.useCallback)(async text=>{if(busyRef.current){commit({kind:"notice",tone:"warn",text:"\u5B9F\u884C\u4E2D\u3067\u3059\u3002Ctrl+C \u3067\u4E2D\u65AD\u3057\u3066\u304B\u3089\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"});return}busyRef.current=true;abortRef.
|
|
1282
|
-
true);commit({kind:"user",text});for(const step of buildScenario(text)){if(abortRef.current)break;if(step.type==="text"){await stream.start(step.text);stream.clear();if(!abortRef.current)commit({kind:"assistant",text:step.text});continue}const spec=step.spec;const policy=applyPermissionMode(checkPermission(spec.name,getMode(modeRef.current)),spec.risk??"exec",permissionMode).decision;const decision=policy!=="deny"&&demoSessionAllow.current.has(spec.name)?"allow":policy;if(decision===
|
|
1283
|
-
name:spec.name,summary:spec.summary,input:spec.input,output:`permission denied: ${getMode(modeRef.current).label}\u30E2\u30FC\u30C9\u3067\u306F ${spec.name} \u306F deny \u3067\u3059`,status:"denied"};commit({kind:"tool",run});commit({kind:"notice",tone:"warn",text:"deny-and-continue: \u62D2\u5426\u3092 tool result \u3068\u3057\u3066\u30E2\u30C7\u30EB\u3078\u8FD4\u3057\u3001\u30EB\u30FC\u30D7\u306F\u7D9A\u884C\u3057\u307E\u3059\uFF08\u7121\u8A00\u306E allow \u306B\u306F\u3057\u306A\u3044\uFF09"});
|
|
1274
|
+
text});const startupCatalog=await catalogFetchRef.current;if(startupCatalog&&isBelowMinSupported(version,startupCatalog.minSupportedVersion)){blockOnMinSupported(startupCatalog.minSupportedVersion);return}const controller=new AbortController;streamAbortRef.current=controller;stream.begin();try{const turnMode=getMode(modeRef.current);const resident=buildResidentSet(turnMode,{...permissionMode!==void 0?{permissionMode}:{},permissionLayers});const result=await runTurn(runtime.client,runtime.context,
|
|
1275
|
+
{input:text,model:modelRef.current,system:buildSystemPrompt({cwd:cwd2,branch,modeLabel:turnMode.label,cliVersion:version,toolNames:resident.tools.map(t=>t.name),...turnMode.prompt!==void 0?{modePrompt:turnMode.prompt}:{}}),signal:controller.signal,onTextDelta:delta=>stream.push(stripTerminalControls(delta)),tools:resident.tools,execute:{mode:turnMode,ctx:{cwd:process.cwd()},sessionAllow:sessionAllow.current,permissionLayers,...permissionMode!==void 0?{permissionMode}:{},audit,askPermission:request=>askPermission(
|
|
1276
|
+
{name:(request.target?.tool??request.tool).name,input:fullInputFor(request),...request.diff?{diff:request.diff}:{},noAlwaysReason:request.noAlwaysReason}),onStart:(tool,preview)=>{const safe=stripTerminalControls(preview);setRunningTool({name:stripTerminalControls(tool.name),summary:safe,input:safe,output:"",status:"running"})}},onToolUse:()=>{const partial=stream.end();stream.clear();if(partial.trim()!=="")commit({kind:"assistant",text:partial})},onToolResult:(call,toolResult)=>{setRunningTool(
|
|
1277
|
+
null);const label=stripTerminalControls(toolResult.summary??call.name);const run={name:stripTerminalControls(call.name),summary:label,input:label,output:stripTerminalControls(toolResult.content),status:toolResult.denied===true?"denied":toolResult.isError===true?"error":"done",...toolResult.diff?{diff:toolResult.diff}:{}};lastToolRef.current=run;commit({kind:"tool",run});stream.begin()}});const full=stream.end();stream.clear();if(full.trim()!=="")commit({kind:"assistant",text:full});if(result.maxStepsReached){
|
|
1278
|
+
commit({kind:"notice",tone:"warn",text:"\u30C4\u30FC\u30EB\u5B9F\u884C\u306E\u5F80\u5FA9\u304C\u4E0A\u9650\u306B\u9054\u3057\u305F\u305F\u3081\u6253\u3061\u5207\u308A\u307E\u3057\u305F\u3002\u7D9A\u304D\u306F\u540C\u3058\u4F1A\u8A71\u3067\u6307\u793A\u3057\u3066\u304F\u3060\u3055\u3044"})}if(result.droppedMessages>0){commit({kind:"notice",tone:"warn",text:`\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4E0A\u9650\u306B\u8FD1\u3065\u3044\u305F\u305F\u3081\u3001\u53E4\u3044\u3084\u308A\u53D6\u308A ${result.
|
|
1279
|
+
droppedMessages} \u4EF6\u3092\u5C65\u6B74\u304B\u3089\u843D\u3068\u3057\u307E\u3057\u305F\uFF08/clear \u3067\u660E\u793A\u7684\u306B\u6D88\u305B\u307E\u3059\uFF09`})}if(result.upstreamError!==null){commit({kind:"notice",tone:"error",text:`\u30E2\u30C7\u30EB\u306E\u5FDC\u7B54\u304C\u9014\u4E2D\u3067\u7D42\u308F\u308A\u307E\u3057\u305F: ${result.upstreamError}`})}if(result.aborted){commit({kind:"notice",tone:"warn",text:"\u4E2D\u65AD\u3057\u307E\u3057\u305F\uFF08Ctrl+C\uFF09\u2014 \u3053\u3053\u307E\u3067\u306E\u6D88\u8CBB\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u306B\u8A08\u4E0A\u3055\u308C\u307E\u3059"})}else if(result.
|
|
1280
|
+
emptyResponse){commit({kind:"notice",tone:"warn",text:"\u30E2\u30C7\u30EB\u304B\u3089\u30C6\u30AD\u30B9\u30C8\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F"})}}catch(err){const partial=stream.end();stream.clear();if(partial.trim()!=="")commit({kind:"assistant",text:partial});commit({kind:"notice",tone:"error",text:err instanceof RelayError?err.message:`\u30E2\u30C7\u30EB\u53D6\u6B21\u3067\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F: ${err.message}`})}finally{streamAbortRef.
|
|
1281
|
+
current=null;setRunningTool(null);setContext(runtime.context.snapshot());busyRef.current=false;setBusy(false)}},[audit,blockOnMinSupported,branch,commit,cwd2,permissionLayers,permissionMode,runtime,stream,version]);const runDemo=(0,import_react38.useCallback)(async text=>{if(busyRef.current){commit({kind:"notice",tone:"warn",text:"\u5B9F\u884C\u4E2D\u3067\u3059\u3002Ctrl+C \u3067\u4E2D\u65AD\u3057\u3066\u304B\u3089\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"});return}busyRef.current=true;abortRef.
|
|
1282
|
+
current=false;setBusy(true);commit({kind:"user",text});for(const step of buildScenario(text)){if(abortRef.current)break;if(step.type==="text"){await stream.start(step.text);stream.clear();if(!abortRef.current)commit({kind:"assistant",text:step.text});continue}const spec=step.spec;const policy=applyPermissionMode(checkPermission(spec.name,getMode(modeRef.current)),spec.risk??"exec",permissionMode).decision;const decision=policy!=="deny"&&demoSessionAllow.current.has(spec.name)?"allow":policy;if(decision===
|
|
1283
|
+
"deny"){const run={name:spec.name,summary:spec.summary,input:spec.input,output:`permission denied: ${getMode(modeRef.current).label}\u30E2\u30FC\u30C9\u3067\u306F ${spec.name} \u306F deny \u3067\u3059`,status:"denied"};commit({kind:"tool",run});commit({kind:"notice",tone:"warn",text:"deny-and-continue: \u62D2\u5426\u3092 tool result \u3068\u3057\u3066\u30E2\u30C7\u30EB\u3078\u8FD4\u3057\u3001\u30EB\u30FC\u30D7\u306F\u7D9A\u884C\u3057\u307E\u3059\uFF08\u7121\u8A00\u306E allow \u306B\u306F\u3057\u306A\u3044\uFF09"});
|
|
1284
1284
|
continue}if(decision==="ask"){const choice=await askPermission(spec);if(choice==="no"){commit({kind:"tool",run:{name:spec.name,summary:spec.summary,input:spec.input,output:"\u30E6\u30FC\u30B6\u30FC\u304C\u62D2\u5426\u3057\u307E\u3057\u305F",status:"denied"}});commit({kind:"notice",tone:"info",text:"\u300C\u4EE3\u308F\u308A\u306B\u3053\u3046\u3057\u3066\u300D\u306E\u5165\u529B\u6B04\u306F\u3053\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306B\u306F\u3042\u308A\u307E\u305B\u3093\uFF08\u3053\u3053\u3067\u6253\u3061\u5207\u308A\u307E\u3059\uFF09"});
|
|
1285
1285
|
break}if(choice==="always")demoSessionAllow.current.add(spec.name)}setRunningTool({name:spec.name,summary:spec.summary,input:spec.input,output:"",status:"running"});await sleep(spec.durationMs);setRunningTool(null);if(abortRef.current)break;const done={name:spec.name,summary:spec.summary,input:spec.input,output:spec.output,status:"done",durationMs:spec.durationMs};lastToolRef.current=done;commit({kind:"tool",run:done})}stream.clear();busyRef.current=false;setBusy(false)},[commit,stream]);const runCommand=(0,import_react38.useCallback)(
|
|
1286
1286
|
line=>{const parsed=parseCommandLine(line);if(!parsed)return;const{args}=parsed;const name=resolveCommandName(parsed.name);switch(name){case"/exit":exit();return;case"/clear":setItems([]);runtime.context.clear();setContext(runtime.context.snapshot());return;case"/doctor":setOverlay("doctor");return;case"/model":setSelected(Math.max(0,catalog.ids.indexOf(model)));setOverlay("model");return;case"/mode":{const target=args[0];if(target!==void 0&&!isModeId(target)){commit({kind:"notice",tone:"warn",text:`\
|
|
1287
1287
|
\u4E0D\u660E\u306A\u30E2\u30FC\u30C9: ${target}\uFF08dev | biz | plan\uFF09`});return}const to=target??nextMode(modeRef.current);setMode(to);commit({kind:"notice",tone:"info",text:`\u30E2\u30FC\u30C9\u3092 ${getMode(to).label}\uFF08${to}\uFF09\u306B\u5207\u308A\u66FF\u3048\u307E\u3057\u305F \u2014 ${getMode(to).description}`});return}case"/help":commit({kind:"notice",tone:"info",text:["\u4F1A\u8A71\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u3067\u5B9F\u969B\u306B\u30E2\u30C7\u30EB\u3078\u9001\u3089\u308C\u307E\u3059",
|
|
1288
1288
|
`\u4F7F\u3048\u308B\u30B3\u30DE\u30F3\u30C9: ${commandsForMode(modeRef.current).map(c=>c.name).join(" ")}\uFF08/exit \u306F /quit \u3082\u53EF\uFF09`,...PENDING_COMMANDS.length>0?[`\u672A\u5B9F\u88C5\u306E\u305F\u3081\u767B\u9332\u3057\u3066\u3044\u306A\u3044\u30B3\u30DE\u30F3\u30C9: ${PENDING_COMMANDS.map(c=>c.name).join(" ")}`]:[],"\u30AD\u30FC: Shift+Tab \u307E\u305F\u306F Alt+M \u3067\u30E2\u30FC\u30C9\u5DE1\u56DE \xB7 Ctrl+R \u3067\u76F4\u524D\u306E\u30C4\u30FC\u30EB\u51FA\u529B\u3092\u5C55\u958B",
|
|
1289
|
-
"\u6539\u884C: Shift+Enter\uFF08kitty \u5BFE\u5FDC\u7AEF\u672B\uFF09\xB7 Ctrl+J\uFF08\u5168\u7AEF\u672B\uFF09\xB7 \\ \u3092\u6253\u3063\u3066\u304B\u3089 Enter \u3067\u3082\u53EF"].join("\n")});return;case"/context":{const snapshot=runtime.context.snapshot();const t=snapshot.totals;const resident=buildResidentSet(getMode(modeRef.current),{...permissionMode!==void 0?{permissionMode}:{}});commit({kind:"notice",tone:"info",text:[`\u30E2\u30C7\u30EB: ${modelLabel(model)}\uFF08\u30E2\u30FC\u30C9\u3068\u306F\u72EC\u7ACB\uFF09`,
|
|
1289
|
+
"\u6539\u884C: Shift+Enter\uFF08kitty \u5BFE\u5FDC\u7AEF\u672B\uFF09\xB7 Ctrl+J\uFF08\u5168\u7AEF\u672B\uFF09\xB7 \\ \u3092\u6253\u3063\u3066\u304B\u3089 Enter \u3067\u3082\u53EF"].join("\n")});return;case"/context":{const snapshot=runtime.context.snapshot();const t=snapshot.totals;const resident=buildResidentSet(getMode(modeRef.current),{...permissionMode!==void 0?{permissionMode}:{},permissionLayers});commit({kind:"notice",tone:"info",text:[`\u30E2\u30C7\u30EB: ${modelLabel(model)}\uFF08\u30E2\u30FC\u30C9\u3068\u306F\u72EC\u7ACB\uFF09`,
|
|
1290
1290
|
`\u30E2\u30FC\u30C9: ${getMode(modeRef.current).label} \u2014 \u6709\u52B9\u30C4\u30FC\u30EB glob: ${getMode(modeRef.current).tools.join(" ")}`,`\u30E2\u30FC\u30C9\u5B9A\u7FA9: ${modeSource(modeRef.current)??"\u7D44\u307F\u8FBC\u307F\uFF08\u5B9A\u7FA9\u30D5\u30A1\u30A4\u30EB\u306A\u3057\uFF09"}`,`\u63A5\u7D9A\u5148: ${runtime.relayUrl}\uFF08\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB: ${runtime.profileName}\uFF09`,`\u30BF\u30FC\u30F3\u6570: ${snapshot.turns} \xB7 \u76F4\u8FD1\u306E\u30D7\u30ED\u30F3\u30D7\u30C8\u9577: ${snapshot.
|
|
1291
1291
|
lastPromptTokens} tok`,`\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u6B8B\u91CF: ${snapshot.remainingPercent}%\uFF08\u7A93 200,000 tok \u306E\u6982\u7B97\uFF09`,`\u5B9F\u6E2C\u30C8\u30FC\u30AF\u30F3\u5408\u8A08: input ${t.inputTokens} / cache_read ${t.cacheReadTokens} / cache_write ${t.cacheWriteTokens} / output ${t.outputTokens}`,...snapshot.droppedMessages>0?[`\u4E0A\u9650\u306E\u305F\u3081\u843D\u3068\u3057\u305F\u3084\u308A\u53D6\u308A: ${snapshot.droppedMessages} \u4EF6`]:[],`permission-mode: ${describePermissionMode(
|
|
1292
1292
|
permissionMode)}`,`\u76E3\u67FB\u30ED\u30B0: ${describeAuditLog(audit)}`,`\u5E38\u99D0\u30C4\u30FC\u30EB: ${resident.tools.length} \u672C / \u30B9\u30AD\u30FC\u30DE\u6982\u7B97 ${resident.tokens} tok\uFF08\u4E0A\u9650 ${RESIDENT_TOKEN_CAP} tok\uFF09`,` ${resident.tools.map(t2=>t2.name).join(" ")||"\uFF08\u306A\u3057\uFF09"}`,...resident.dropped.length>0?[` \u4E0A\u9650\u8D85\u904E\u3067\u5916\u3057\u305F\u30C4\u30FC\u30EB: ${resident.dropped.join(" ")}`]:[],"TWP API \u306E\u30C4\u30FC\u30EB\uFF08\u30E1\u30BF\u30C4\u30FC\u30EB\u30FB\u30AB\u30BF\u30ED\u30B0\u914D\u4FE1\uFF09\u306F\u5225\u30BF\u30B9\u30AF\u3067\u8F09\u308A\u307E\
|
|
@@ -1304,13 +1304,14 @@ body-11-doctorNetworkRows(networkDiagnostics));return(0,import_jsx_runtime9.jsxs
|
|
|
1304
1304
|
truncate",children:line===""?" ":line},i))}):null,runningTool?(0,import_jsx_runtime9.jsx)(ToolCard,{run:runningTool,expanded:false,maxLines:budget.body}):null,overlay==="permission"&&pendingPermission?(0,import_jsx_runtime9.jsx)(PermissionDialog,{spec:pendingPermission,selected:selectedState,maxDiffLines:diffBudget}):null,overlay==="model"?(0,import_jsx_runtime9.jsx)(SelectList,{title:`\u30E2\u30C7\u30EB\u3092\u9078\u629E\uFF08\u30E2\u30FC\u30C9\u3068\u306F\u72EC\u7ACB\uFF09${catalogTitleSuffix(
|
|
1305
1305
|
catalog.source)}`,items:toModelInfos(catalog.ids).map(m=>({key:m.id,label:m.label,hint:m.note})),selected:selectedState,maxRows:Math.min(catalog.ids.length,listBudget),footer:"\u2191\u2193 \u3067\u9078\u629E \xB7 Enter \u3067\u6C7A\u5B9A \xB7 Esc \u3067\u53D6\u6D88"}):null,overlay==="doctor"?(0,import_jsx_runtime9.jsx)(Doctor,{events:keyLog,maxRows:doctorBudget,network:networkDiagnostics}):null,overlay==="none"&&!busy&&paletteItems.length>0?(0,import_jsx_runtime9.jsx)(SelectList,{title:"\u30B9\u30E9\u30C3\u30B7\u30E5\u30B3\u30DE\u30F3\
|
|
1306
1306
|
\u30C9",items:paletteItems.map(c=>({key:c.name,label:`${c.name}${c.argumentHint?` ${c.argumentHint}`:""}`,hint:c.description})),selected:selectedState,maxRows:Math.min(8,listBudget),footer:"\u2191\u2193 \u9078\u629E \xB7 Tab \u88DC\u5B8C \xB7 Enter \u5B9F\u884C \xB7 Esc \u53D6\u6D88"}):null,(0,import_jsx_runtime9.jsx)(InputBox,{value:buffer.text,window:inputWindow,busy,pasting,width:size.columns}),(0,import_jsx_runtime9.jsx)(StatusLine,{mode:modeDef,model,cwd:cwd2,branch,contextRemaining:context.
|
|
1307
|
-
remainingPercent,width:size.columns}),(0,import_jsx_runtime9.jsx)(HintLine,{width:size.columns})]})]})}var import_jsx_runtime10=__toESM(require_jsx_runtime(),1);async function startTui(opts){activateModeFiles(text=>void process.stderr.write(stripTerminalControls(text)));const
|
|
1308
|
-
void 0);if(opts.noTui){printPlain(mode,picked.model,runtime.relayUrl,opts.version,opts.permissionMode);return}if(!opts.doctor){const blocked=await checkMinSupportedVersion({current:opts.version,
|
|
1309
|
-
model,cwd:process.cwd(),cliVersion:opts.version,interactive:true});const instance=render_default((0,import_jsx_runtime10.jsx)(App2,{initialMode:mode,initialModel:picked.model,initialCatalog,
|
|
1310
|
-
stdout.write(stripTerminalControls(text))};out.write(`twp ${version} \u2014 \u3053\u306E\u74B0\u5883\u3067\u306F\u5BFE\u8A71 TUI \u3092\u8D77\u52D5\u3067\u304D\u307E\u305B\u3093\uFF08--no-tui / \u975ETTY\uFF09
|
|
1307
|
+
remainingPercent,width:size.columns}),(0,import_jsx_runtime9.jsx)(HintLine,{width:size.columns})]})]})}var import_jsx_runtime10=__toESM(require_jsx_runtime(),1);async function startTui(opts){activateModeFiles(text=>void process.stderr.write(stripTerminalControls(text)));const permissionLayers=activatePermissionSettings(text=>void process.stderr.write(stripTerminalControls(text)),{...opts.allowedTools?{allowedTools:opts.allowedTools}:{},...opts.disallowedTools?{disallowedTools:opts.disallowedTools}:{}});const mode=opts.mode??"dev";const runtime=createRuntime({...opts.profile!==void 0?{profile:opts.
|
|
1308
|
+
profile}:{},...opts.model!==void 0?{model:opts.model}:{},cliVersion:opts.version});const initialCatalog=loadCachedCatalog(runtime.profileName,runtime.relayUrl)??builtinCatalog();const picked=pickModel(initialCatalog,runtime.configuredModel??void 0);if(opts.noTui){printPlain(mode,picked.model,runtime.relayUrl,opts.version,opts.permissionMode,(opts.allowedTools?.length??0)+(opts.disallowedTools?.length??0)>0);return}if(!opts.doctor){const blocked=await checkMinSupportedVersion({current:opts.version,
|
|
1309
|
+
cachedFloor:runtime.loadCachedFloor().minSupportedVersion,refresh:async()=>(await runtime.loadCatalog()).minSupportedVersion,write:text=>void process.stderr.write(stripTerminalControls(text))});if(blocked){process.exitCode=1;return}}const audit=createAuditLogger({mode,permissionMode:opts.permissionMode,model:picked.model,cwd:process.cwd(),cliVersion:opts.version,interactive:true});const instance=render_default((0,import_jsx_runtime10.jsx)(App2,{initialMode:mode,initialModel:picked.model,initialCatalog,
|
|
1310
|
+
initialModelWarning:picked.warning??null,runtime,version:opts.version,startInDoctor:opts.doctor,audit,permissionLayers,...opts.permissionMode!==void 0?{permissionMode:opts.permissionMode}:{}}),{exitOnCtrlC:false});await instance.waitUntilExit()}function printPlain(mode,model,relayUrl,version,permissionMode,hasRuleFlags=false){const out={write:text=>void process.stdout.write(stripTerminalControls(text))};out.write(`twp ${version} \u2014 \u3053\u306E\u74B0\u5883\u3067\u306F\u5BFE\u8A71 TUI \u3092\u8D77\u52D5\u3067\u304D\u307E\u305B\u3093\uFF08--no-tui / \u975ETTY\uFF09
|
|
1311
1311
|
`);out.write(`mode=${mode} model=${model} relay=${relayUrl}
|
|
1312
1312
|
`);if(permissionMode!==void 0){out.write(`permission-mode=${permissionMode}\uFF08\u3053\u306E\u7D4C\u8DEF\u3067\u306F\u30C4\u30FC\u30EB\u3092\u5B9F\u884C\u3057\u306A\u3044\u305F\u3081\u52B9\u304D\u307E\u305B\u3093\uFF09
|
|
1313
|
-
`)}out.write('1 \u5F80\u5FA9\u3060\u3051\u5B9F\u884C\u3059\u308B: twp -p "\u8CEA\u554F" \uFF08\u6A19\u6E96\u5165\u529B\u304B\u3089\u306F twp -p -\uFF09\n');const network=proxyDiagnostics();out.write("\n\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\uFF08\u30D7\u30ED\u30AD\u30B7 / CA\uFF09:\n");
|
|
1313
|
+
`)}if(hasRuleFlags){out.write("--allowed-tools / --disallowed-tools\uFF08\u3053\u306E\u7D4C\u8DEF\u3067\u306F\u30C4\u30FC\u30EB\u3092\u5B9F\u884C\u3057\u306A\u3044\u305F\u3081\u52B9\u304D\u307E\u305B\u3093\uFF09\n")}out.write('1 \u5F80\u5FA9\u3060\u3051\u5B9F\u884C\u3059\u308B: twp -p "\u8CEA\u554F" \uFF08\u6A19\u6E96\u5165\u529B\u304B\u3089\u306F twp -p -\uFF09\n');const network=proxyDiagnostics();out.write("\n\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\uFF08\u30D7\u30ED\u30AD\u30B7 / CA\uFF09:\n");
|
|
1314
|
+
for(const line of network){out.write(` ${line.warn===true?"\u26A0 ":""}${line.label}: ${line.value}
|
|
1314
1315
|
`)}}export{startTui};
|
|
1315
1316
|
/*! Bundled license information:
|
|
1316
1317
|
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
3
|
import{stringWidth}from"./chunk-WVS4W5FY.js";import{AuthSession,NotLoggedInError,SessionExpiredError,loadCredentials}from"./chunk-63LDNYGW.js";import{GLOBAL_OPTIONS_HELP,HELP_TOKEN}from"./chunk-FKIZ5ZJU.js";import{parseOperationArgs}from"./chunk-O52CUEDO.js";import{Resolver,requireDefaultProject}from"./chunk-7WEYBZSK.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-JKSXUBND.js";import{effectiveApiUrl,loadUserConfig,resolveConfiguredOutput,resolveProfile}from"./chunk-NERYSBA4.js";
|
|
4
|
-
import{httpFetch}from"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-2VISRLWS.js";import{ApiResponseError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,NetworkError,UsageError}from"./chunk-M3GWY6NT.js";import{ResolveError}from"./chunk-5QCAIKFE.js";import fs from"fs";import path from"path";var SENSITIVE_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-vercel-protection-bypass"]);var REDACTED="***\uFF08\u4F0F\u5B57\uFF09";var SECRET_KEY_PATTERN="[A-Za-z0-9_-]*(?:token|secret|password|passwd|api[_-]?key|credential)[A-Za-z0-9_-]*";var NOT_SECRET_FLAGS="(?:starting-token)";function redactSecrets(text){return text.replace(/\bBearer\s+[^\s"'`,;)\]}]+/gi,`Bearer ${REDACTED}`).replace(new RegExp(`("${SECRET_KEY_PATTERN}"
|
|
5
|
-
|
|
6
|
-
const out={};for(const[key,item]of Object.entries(value)){out[key]=SECRET_KEY_NAME.test(key)?REDACTED:redactSecretValues(item)}return out}return value}function formatHeaders(headers){if(!headers)return[];const entries=headers instanceof Headers?[...headers.entries()]:Array.isArray(headers)?headers:Object.entries(headers);return entries.map(([name,value])=>{const shown=SENSITIVE_HEADERS.has(name.toLowerCase())?REDACTED:redactSecrets(String(value));return` ${name.toLowerCase()}: ${shown}`})}
|
|
7
|
-
function formatBody(raw){const safe=redactSecrets(stripTerminalControls(raw));return safe.length>BODY_LIMIT?`${safe.slice(0,BODY_LIMIT)}
|
|
4
|
+
import{httpFetch}from"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-2VISRLWS.js";import{ApiResponseError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,NetworkError,UsageError}from"./chunk-M3GWY6NT.js";import{ResolveError}from"./chunk-5QCAIKFE.js";import fs from"fs";import path from"path";var SENSITIVE_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-vercel-protection-bypass"]);var REDACTED="***\uFF08\u4F0F\u5B57\uFF09";var SECRET_KEY_PATTERN="[A-Za-z0-9_-]*(?:token|secret|password|passwd|api[_-]?key|credential|signature)[A-Za-z0-9_-]*";var NOT_SECRET_FLAGS="(?:starting-token)";function redactSecrets(text){return text.replace(/\bBearer\s+[^\s"'`,;)\]}]+/gi,`Bearer ${REDACTED}`).replace(new RegExp(`("${SECRET_KEY_PATTERN}"\\\
|
|
5
|
+
s*:\\s*)"(?:[^"\\\\]|\\\\.)*"`,"gi"),`$1"${REDACTED}"`).replace(new RegExp(`([?&]${SECRET_KEY_PATTERN}=)[^&\\s"'\`,;)\\]}]+`,"gi"),`$1${REDACTED}`).replace(new RegExp(`(--(?!${NOT_SECRET_FLAGS}(?:=|\\s))${SECRET_KEY_PATTERN}(?:=|\\s+))('[^']*'|"[^"]*"|[A-Za-z0-9_.~+/=|:%-]+)`,"gi"),`$1${REDACTED}`)}var SECRET_KEY_NAME=new RegExp(`^${SECRET_KEY_PATTERN}$`,"i");function redactSecretValues(value){if(Array.isArray(value))return value.map(item=>redactSecretValues(item));if(value!==null&&typeof value===
|
|
6
|
+
"object"){const out={};for(const[key,item]of Object.entries(value)){out[key]=SECRET_KEY_NAME.test(key)?REDACTED:redactSecretValues(item)}return out}return value}function formatHeaders(headers){if(!headers)return[];const entries=headers instanceof Headers?[...headers.entries()]:Array.isArray(headers)?headers:Object.entries(headers);return entries.map(([name,value])=>{const shown=SENSITIVE_HEADERS.has(name.toLowerCase())?REDACTED:redactSecrets(String(value));return` ${name.toLowerCase()}: ${shown}`})}
|
|
7
|
+
var BODY_LIMIT=4e3;function formatBody(raw){const safe=redactSecrets(stripTerminalControls(raw));return safe.length>BODY_LIMIT?`${safe.slice(0,BODY_LIMIT)}
|
|
8
8
|
\u2026\uFF08\u4EE5\u964D ${safe.length-BODY_LIMIT} \u6587\u5B57\u3092\u7701\u7565\uFF09`:safe}function isTextualContentType(contentType){if(contentType===null)return false;return/^\s*(text\/|application\/(json|xml|javascript|x-www-form-urlencoded)|application\/[\w.+-]*\+(json|xml))/i.test(contentType)}function withDebug(inner,options={}){const write=options.write??(text=>void process.stderr.write(text));const now=options.now??(()=>Date.now());return async(input,init)=>{const method=init?.method??
|
|
9
9
|
"GET";const lines=[`[debug] \u2192 ${method} ${redactSecrets(input)}`,...formatHeaders(init?.headers)];if(typeof init?.body==="string")lines.push(` ${formatBody(init.body)}`);write(`${lines.join("\n")}
|
|
10
10
|
`);const started=now();let res;try{res=await inner(input,init)}catch(err){write(`[debug] \u2717 \u901A\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F (${now()-started}ms): ${redactSecrets(err.message)}
|
|
@@ -31,18 +31,19 @@ ${operationSection}${subSection}
|
|
|
31
31
|
${GLOBAL_OPTIONS_HELP}
|
|
32
32
|
`}function renderOperationHelp(op,path2){const sections=[`twp ${path2} ${op.name} \u2014 ${op.summary}`,"","\u4F7F\u3044\u65B9:",` ${op.usage}`];if(op.description!==void 0){sections.push("",...op.description.split("\n"))}if(op.destructive===true){sections.push("","\u26A0 \u7834\u58CA\u7684\u306A\u64CD\u4F5C\u3067\u3059\u3002\u5B9F\u884C\u3059\u308B\u306B\u306F --yes \u304C\u5FC5\u8981\u3067\u3059\u3002")}if(op.flags.length>0){sections.push("","\u30AA\u30D7\u30B7\u30E7\u30F3:",alignedList(op.flags.
|
|
33
33
|
map(flag=>[flag.takesValue?`${flag.name} ${flag.placeholder??"<\u5024>"}`:flag.name,flag.summary])))}sections.push("",GLOBAL_OPTIONS_HELP,"");return sections.join("\n")}function renderUnknownOperation(resource,path2,attempted){const names=[...resource.operations.map(op=>op.name),...subresourcesOf(resource).map(sub=>`${sub.name} <\u64CD\u4F5C>`)].join(" / ");return attempted===void 0?`twp ${path2} \u306B\u306F\u64CD\u4F5C\u306E\u6307\u5B9A\u304C\u5FC5\u8981\u3067\u3059\uFF08${names}\uFF09\u3002\u8A73\u3057\u304F\u306F twp ${path2}\
|
|
34
|
-
${HELP_TOKEN}`:`twp ${path2} \u306B\u300C${attempted}\u300D\u3068\u3044\u3046\u64CD\u4F5C\u306F\u3042\u308A\u307E\u305B\u3093\uFF08${names}\uFF09\u3002\u8A73\u3057\u304F\u306F twp ${path2} ${HELP_TOKEN}`}var LOADERS={backlog:async()=>(await import("./backlog-AYEKG575.js")).backlogDomain,project:async()=>(await import("./project-OKTJ32JT.js")).projectDomain,task:async()=>(await import("./task-
|
|
34
|
+
${HELP_TOKEN}`:`twp ${path2} \u306B\u300C${attempted}\u300D\u3068\u3044\u3046\u64CD\u4F5C\u306F\u3042\u308A\u307E\u305B\u3093\uFF08${names}\uFF09\u3002\u8A73\u3057\u304F\u306F twp ${path2} ${HELP_TOKEN}`}var LOADERS={backlog:async()=>(await import("./backlog-AYEKG575.js")).backlogDomain,project:async()=>(await import("./project-OKTJ32JT.js")).projectDomain,task:async()=>(await import("./task-VVBXZLPU.js")).taskDomain};async function loadDomain(name){return LOADERS[name]()}var writeOut=text=>void process.stdout.write(text);var writeErr=text=>void process.stderr.write(text);function line(text){return text===""?"":text.endsWith("\n")?text:`${text}
|
|
35
35
|
`}function outputValue(operation,format,body){return format==="json"?operation.raw(body):operation.summarize(body)}function requiresYes(operation,yes){return operation.destructive===true&&!yes}function exitCodeForStatus(status){if(status===401)return EXIT_AUTH;if(status===429)return EXIT_API_SERVER;if(status>=400&&status<500)return EXIT_API_CLIENT;return EXIT_API_SERVER}function exitCodeFor(err){if(err instanceof UsageError)return EXIT_USAGE;if(err instanceof NotLoggedInError||err instanceof SessionExpiredError)
|
|
36
36
|
return EXIT_AUTH;if(err instanceof ApiError)return exitCodeForStatus(err.status);if(err instanceof ApiResponseError||err instanceof NetworkError)return EXIT_API_SERVER;if(err instanceof ResolveError){return err.status===null?EXIT_API_SERVER:exitCodeForStatus(err.status)}return EXIT_FAILURE}function safeText(text){return redactSecrets(stripTerminalControls(text))}function reportError(err,format,code){const message=safeText(err instanceof Error?err.message:String(err));const rawHint=err instanceof
|
|
37
37
|
UsageError?err.hint:void 0;const hint=rawHint!==void 0?safeText(rawHint):void 0;if(format==="json"){const body={code,message};if(err instanceof ApiError)body["status"]=err.status;if(err instanceof ResolveError&&err.status!==null)body["status"]=err.status;if(hint!==void 0)body["hint"]=hint;writeErr(`${JSON.stringify({error:body},null,2)}
|
|
38
38
|
`);return}writeErr(`${message}
|
|
39
39
|
`);if(hint!==void 0)writeErr(`${hint}
|
|
40
40
|
`)}function dryRunValue(apiUrl,plan){const value={method:plan.method,url:`${apiUrl}${appendQuery(plan.path,plan.query)}`};if(plan.body!==void 0)value["body"]=plan.body;return value}async function send(client,apiUrl,plan){try{return await client.request(plan.method,appendQuery(plan.path,plan.query),plan.body)}catch(err){if(err instanceof ApiError||err instanceof NotLoggedInError||err instanceof SessionExpiredError){throw err}throw new NetworkError(`${apiUrl} \u3078\u306E\u901A\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${err.
|
|
41
|
-
message}`,{cause:err})}}function
|
|
42
|
-
|
|
43
|
-
existsSync(
|
|
44
|
-
|
|
45
|
-
|
|
41
|
+
message}`,{cause:err})}}async function putSigned(fetchImpl,url,bytes,contentType){let res;try{res=await fetchImpl(url,{method:"PUT",headers:{"Content-Type":contentType},body:bytes})}catch(err){throw new NetworkError(`\u30B9\u30C8\u30EC\u30FC\u30B8\u3078\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${err.message}`,{cause:err})}if(!res.ok){throw new NetworkError(`\u30B9\u30C8\u30EC\u30FC\u30B8\u3078\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u304C\u62D2\u5426\u3055\u308C\u307E\u3057\u305F\uFF08HTTP ${res.
|
|
42
|
+
status}\uFF09`)}}function resolveDownloadTarget(spec,commandPath,operationName,input){const raw=input.flags.get(spec.outFlag);if(raw===void 0||raw.trim()===""){throw new UsageError(`${spec.outFlag} \u306F\u5FC5\u9808\u3067\u3059\uFF08twp ${commandPath} ${operationName}\uFF09`,`\u66F8\u304D\u51FA\u3057\u5148\u306E\u30D5\u30A1\u30A4\u30EB\u30D1\u30B9\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u6A19\u6E96\u51FA\u529B\u3078\u306F\u51FA\u3057\u307E\u305B\u3093\uFF09\u3002`)}return{out:path.
|
|
43
|
+
resolve(raw.trim()),force:input.flags.has(spec.forceFlag)}}function assertWritableTarget(target,forceFlag){if(!target.force&&fs.existsSync(target.out)){throw new UsageError(`\u66F8\u304D\u51FA\u3057\u5148\u304C\u65E2\u306B\u3042\u308A\u307E\u3059: ${target.out}`,`\u4E0A\u66F8\u304D\u3059\u308B\u306A\u3089 ${forceFlag} \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A\u3067\u306F\u4E0A\u66F8\u304D\u3057\u307E\u305B\u3093\uFF09\u3002`)}const dir=path.dirname(target.out);if(!fs.existsSync(
|
|
44
|
+
dir)){throw new UsageError(`\u66F8\u304D\u51FA\u3057\u5148\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u3042\u308A\u307E\u305B\u3093: ${dir}`,"\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u4F5C\u3063\u3066\u304B\u3089\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u81EA\u52D5\u3067\u306F\u4F5C\u6210\u3057\u307E\u305B\u3093\uFF09\u3002")}}async function download(args){let received;try{received=await args.client.requestBinary(args.plan.method,appendQuery(args.plan.path,args.plan.query))}catch(err){
|
|
45
|
+
if(err instanceof ApiError||err instanceof NotLoggedInError||err instanceof SessionExpiredError)throw err;throw new NetworkError(`${args.apiUrl} \u3078\u306E\u901A\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${err.message}`,{cause:err})}try{fs.writeFileSync(args.target.out,received.bytes,{flag:args.target.force?"w":"wx"})}catch(err){const code=err.code;if(code==="EEXIST"){throw new UsageError(`\u66F8\u304D\u51FA\u3057\u5148\u304C\u65E2\u306B\u3042\u308A\u307E\u3059: ${args.target.out}`,"\u4E0A\u66F8\u304D\
|
|
46
|
+
\u3059\u308B\u306A\u3089 --force \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}throw new Error(`\u66F8\u304D\u51FA\u3057\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${args.target.out}\uFF09: ${err.message}`,{cause:err})}return{path:args.target.out,size:received.bytes.byteLength,contentType:received.contentType}}var CURATED_PAGING_VOCABULARY={mode:"--all",resumeFlag:"--cursor",capAdvice:"--limit \u3092\u5927\u304D\u304F\u3057\u3066\u5F80\u5FA9\u3092\u6E1B\u3089\u3059\u304B\u3001--max-pages / --max-items \u3092\u4E0A\u3052\u3066\u304F\u3060\u3055\u3044\u3002"};
|
|
46
47
|
function capExceeded(vocabulary,reason,pages,count,cursor){return new UsageError(`${vocabulary.mode} \u304C\u4E0A\u9650\u306B\u9054\u3057\u305F\u305F\u3081\u4E2D\u65AD\u3057\u307E\u3057\u305F\uFF08${reason}\uFF0F${pages} \u30DA\u30FC\u30B8\u30FB${count} \u4EF6\u3092\u53D6\u5F97\u6E08\u307F\uFF09\u3002\u3053\u308C\u306F\u5168\u4EF6\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002`,`${vocabulary.capAdvice}\u7D9A\u304D\u3060\u3051\u3092\u53D6\u308B\u306A\u3089 ${vocabulary.resumeFlag} ${shellQuote(cursor)}\
|
|
47
48
|
\u304B\u3089\u518D\u958B\u3067\u304D\u307E\u3059`)}async function fetchAllPages(args){const{paging,maxPages,maxItems}=args;const vocabulary=args.vocabulary??CURATED_PAGING_VOCABULARY;const merged=[];const first=args.plan.query?.[paging.cursorParam];let sent=typeof first==="string"?first:"";for(let page=1;;page+=1){const plan=page===1?args.plan:{...args.plan,query:{...args.plan.query,[paging.cursorParam]:sent}};let body;try{body=page===1&&"firstPage"in args?args.firstPage:await send(args.client,
|
|
48
49
|
args.apiUrl,plan)}catch(err){if(page>1){writeErr(`${vocabulary.mode} \u306F ${page} \u30DA\u30FC\u30B8\u76EE\u3067\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${page-1} \u30DA\u30FC\u30B8\u30FB${merged.length} \u4EF6\u3092\u53D6\u5F97\u6E08\u307F\uFF09\u3002\u3053\u308C\u306F\u5168\u4EF6\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u7D9A\u304D\u306F ${vocabulary.resumeFlag} ${shellQuote(stripTerminalControls(sent))} \u304B\u3089\u518D\u958B\u3067\u304D\u307E\u3059\u3002
|
|
@@ -56,9 +57,10 @@ renderResourceHelp(domain,domain.name));return EXIT_OK}const target=domain.subre
|
|
|
56
57
|
void 0?options.operation:options.argv[0];const rest=sub===void 0?options.argv:options.argv.slice(1);if(sub!==void 0&&(operationName===HELP_TOKEN||options.help&&operationName===void 0)){writeOut(renderResourceHelp(sub,path2));return EXIT_OK}const operation=resource.operations.find(op=>op.name===operationName);if(operation===void 0){throw new UsageError(renderUnknownOperation(resource,path2,operationName))}if(options.help||rest[0]===HELP_TOKEN){writeOut(renderOperationHelp(operation,path2));return EXIT_OK}
|
|
57
58
|
const input=parseOperationArgs(rest,operation.flags);if(!globals.dryRun&&requiresYes(operation,globals.yes)){throw new UsageError(`twp ${path2} ${operation.name} \u306F\u7834\u58CA\u7684\u306A\u64CD\u4F5C\u3067\u3059\u3002\u5B9F\u884C\u3059\u308B\u306B\u306F --yes \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002`)}const paging=resolvePaging(operation,path2,input);const downloadTarget=operation.download===void 0?void 0:resolveDownloadTarget(operation.download,path2,operation.name,input);const stored=loadCredentials(
|
|
58
59
|
profile.name);const apiUrl=effectiveApiUrl(profile,stored?.api_url);const transport=options.fetchImpl??httpFetch;const fetchImpl=globals.debug?withDebug(transport):transport;const session=new AuthSession(profile.name,apiUrl,process.env,fetchImpl);const client=new TwpApiClient(apiUrl,session,fetchImpl,options.version);const ctx=buildPrepareContext({resolver:new Resolver(client,{profile:profile.name,refresh:globals.refresh,...profileAliases(profile.name)}),profileName:profile.name,env:process.env,
|
|
59
|
-
cwd:process.cwd()});const prepared=operation.prepare===void 0?input:await operation.prepare(input,ctx);const plan=operation.plan(prepared);if(operation.
|
|
60
|
-
for(const note of operation.plannedNotes?.(prepared)??[])writeErr(`${safeText(note)}
|
|
61
|
-
`);if(globals.dryRun){writeOut(line(renderOutput(dryRunValue(apiUrl,plan),format)));return EXIT_OK}let body;let paged;if(operation.
|
|
62
|
-
|
|
60
|
+
cwd:process.cwd()});const prepared=operation.prepare===void 0?input:await operation.prepare(input,ctx);const plan=operation.plan(prepared);if(operation.execute!==void 0&&(operation.download!==void 0||operation.paging!==void 0||operation.fetchCached!==void 0)){throw new Error(`twp ${path2} ${operation.name}: execute \u306F download / paging / fetchCached \u3068\u540C\u6642\u306B\u5BA3\u8A00\u3067\u304D\u307E\u305B\u3093\uFF08\u914D\u7DDA\u306E\u8AA4\u308A\uFF09`)}if(operation.fetchCached!==void 0&&
|
|
61
|
+
(operation.download!==void 0||operation.paging!==void 0||operation.destructive===true||plan.method!=="GET")){throw new Error(`twp ${path2} ${operation.name}: fetchCached \u306F\u9001\u4FE1\u3057\u306A\u3044\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u306E\u64CD\u4F5C\u306B\u3060\u3051\u5BA3\u8A00\u3067\u304D\u307E\u3059\uFF08\u914D\u7DDA\u306E\u8AA4\u308A\uFF09`)}for(const note of operation.plannedNotes?.(prepared)??[])writeErr(`${safeText(note)}
|
|
62
|
+
`);if(globals.dryRun){writeOut(line(renderOutput(dryRunValue(apiUrl,plan),format)));return EXIT_OK}let body;let paged;if(operation.execute!==void 0){const executeCtx={send:next=>send(client,apiUrl,next),putSigned:(url,bytes,contentType)=>putSigned(fetchImpl,url,bytes,contentType),warn:text=>writeErr(`${safeText(text)}
|
|
63
|
+
`)};body=await operation.execute(prepared,executeCtx)}else if(operation.fetchCached!==void 0){body=await operation.fetchCached(prepared,ctx)}else if(operation.download!==void 0&&downloadTarget!==void 0){assertWritableTarget(downloadTarget,operation.download.forceFlag);body=await download({client,apiUrl,plan,target:downloadTarget})}else if(paging.all&&operation.paging!==void 0){paged=await fetchAllPages({client,apiUrl,plan,paging:operation.paging,maxPages:paging.maxPages,maxItems:paging.maxItems});
|
|
64
|
+
body=paged.body}else{body=await send(client,apiUrl,plan)}const value=globals.query!==void 0?await evaluateQuery(globals.query,operation.raw(body)):outputValue(operation,format,body);writeOut(line(renderOutput(value,format)));if(paged!==void 0){writeErr(`--all: ${paged.pages} \u30DA\u30FC\u30B8\u3092\u8FBF\u3063\u3066 ${paged.count} \u4EF6\u3092\u53D6\u5F97\u3057\u307E\u3057\u305F\u3002
|
|
63
65
|
`)}const pagingNotes=operation.paging===void 0?[]:nextPageNotes(body,prepared,{command:`twp ${path2} ${operation.name}`,flags:operation.flags,profile:globals.profile});for(const note of[...pagingNotes,...operation.notes?.(body,prepared)??[]]){writeErr(`${safeText(note)}
|
|
64
66
|
`)}return EXIT_OK}catch(err){const code=exitCodeFor(err);reportError(err,format,code);return code}}export{redactSecretValues,withDebug,OUTPUT_FORMATS,resolveOutputFormat,evaluateQuery,renderOutput,outputValue,requiresYes,exitCodeFor,reportError,CURATED_PAGING_VOCABULARY,fetchAllPages,resolvePaging,buildPrepareContext,runDomain};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
var MODE_IDS=["dev","biz","plan"];function isModeId(value){return value!==void 0&&MODE_IDS.includes(value)}var MODES=[{id:"dev",label:"\u958B\u767A",color:"green",description:"\u30ED\u30FC\u30AB\u30EB\u30C4\u30FC\u30EB\u5168\u90E8 \uFF0B \u958B\u767A\u7CFB TWP \u30C9\u30E1\u30A4\u30F3\u5E38\u99D0",tools:["read_file","write_file","edit_file","bash","shell","glob","grep","git","twp_*"],permissions:{read_file:"allow",glob:"allow",grep:"allow",git:"ask",twp_get_task:"allow",twp_list_tasks:"allow",twp_update_task:"\
|
|
4
|
+
ask",bash:"ask",shell:"ask",write_file:"ask",edit_file:"ask","*":"ask"}},{id:"biz",label:"\u696D\u52D9",color:"cyan",description:"TWP \u30C9\u30E1\u30A4\u30F3\u4E2D\u5FC3\u3002bash \u3068 write_file \u306F deny",tools:["twp_*","read_file","glob","grep"],permissions:{read_file:"allow",glob:"allow",grep:"allow",twp_get_task:"allow",twp_list_tasks:"allow",twp_update_task:"ask",bash:"deny",shell:"deny",git:"deny",write_file:"deny",edit_file:"deny","*":"ask"}},{id:"plan",label:"\u30D7\u30E9\u30F3",color:"\
|
|
5
|
+
magenta",description:"\u8AAD\u307F\u53D6\u308A\u306E\u307F\u3002\u5168\u66F8\u304D\u8FBC\u307F deny",tools:["read_file","glob","grep","twp_get_*","twp_list_*"],permissions:{read_file:"allow",glob:"allow",grep:"allow",twp_get_task:"allow",twp_list_tasks:"allow",bash:"deny",shell:"deny",git:"deny",write_file:"deny",edit_file:"deny","*":"deny"}}];var activeModeList=MODES;var activeModeSources=new Map;function setActiveModes(modes,sources=new Map){activeModeList=MODES.map(builtin=>modes.find(m=>m.id===
|
|
6
|
+
builtin.id)??builtin);activeModeSources=sources}function modeSource(id){return activeModeSources.get(id)??null}function getMode(id){const found=activeModeList.find(m=>m.id===id);if(!found)throw new Error(`unknown mode: ${id}`);return found}function nextMode(id){const i=activeModeList.findIndex(m=>m.id===id);const next=activeModeList[(i+1)%activeModeList.length];return next?next.id:"dev"}function checkPermission(toolName,mode){const own=key=>Object.hasOwn(mode.permissions,key)?mode.permissions[key]:void 0;const found=own(toolName)??own("*");return found==="allow"||found==="ask"||found==="deny"?found:"ask"}var PERMISSION_MODE_IDS=["plan","acceptEdits","denyAll"];function isPermissionModeId(value){return value!==void 0&&PERMISSION_MODE_IDS.includes(value)}function describePermissionMode(permissionMode){if(permissionMode===void 0)return"\u672A\u6307\u5B9A\uFF08\u30E2\u30FC\u30C9\u306E\u65B9\u91DD\u306E\u307E\u307E\uFF09";switch(permissionMode){case"plan":return"plan\uFF08read \u306E\u307F\u8A31\u53EF\u3002write / exec \u306F\u62D2\u5426\uFF09";case"acceptEdits":return"acceptEdits\uFF08write \u306E\u78BA\u8A8D\u3092\u81EA\u52D5\u627F\u8A8D\u3002read\
|
|
7
|
+
/ exec \u306F\u30E2\u30FC\u30C9\u306E\u307E\u307E\uFF09";case"denyAll":return"denyAll\uFF08read \u3092\u542B\u3080\u5168\u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09";default:{const exhaustive=permissionMode;return`${String(exhaustive)}\uFF08\u4E0D\u660E\u306A\u5024\u3002\u5B89\u5168\u5074\u3067\u5168\u62D2\u5426\uFF09`}}}function applyPermissionMode(decision,risk,permissionMode){if(permissionMode===void 0)return{decision,reason:null};if(decision==="deny")return{decision,reason:null};switch(permissionMode){case"\
|
|
8
|
+
denyAll":return{decision:"deny",reason:"permission-mode=denyAll\uFF08\u5168\u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09"};case"plan":if(risk==="read")return{decision,reason:null};return{decision:"deny",reason:`permission-mode=plan\uFF08${risk} \u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09`};case"acceptEdits":if(risk==="write"&&decision==="ask"){return{decision:"allow",reason:"permission-mode=acceptEdits\uFF08write \u3092\u81EA\u52D5\u627F\u8A8D\uFF09"}}return{decision,reason:null};default:return{decision:"\
|
|
9
|
+
deny",reason:"\u4E0D\u660E\u306A permission-mode\uFF08\u5B89\u5168\u5074\u3067\u62D2\u5426\uFF09"}}}export{isModeId,MODES,setActiveModes,modeSource,getMode,nextMode,checkPermission,isPermissionModeId,describePermissionMode,applyPermissionMode};
|
|
@@ -14,9 +14,12 @@ ok:true,file:prog,args:[...shim.nodeArgs,target,...args],note:`${file} \u2192 ${
|
|
|
14
14
|
return ai==="claude"||!["gemini","codex","copilot"].includes(ai)}import{createHash}from"crypto";import fs2 from"fs";var FALSY=new Set(["0","false","no","off"]);function isBoolishTrue(raw){const v=(raw??"").trim();if(v==="")return false;return!FALSY.has(v.toLowerCase())}var EXCLUSIVE_SKILL_FLOOR=["support-triage"];function normalizeSkillName(skill){return skill.trim().replace(/^twp-/,"")}var stripPrefix=normalizeSkillName;function skillOfItem(item){const explicit=(item.ai_skill??"").trim();if(explicit)return stripPrefix(explicit);const m=/\/twp-([a-z0-9-]+)/.exec(item.prompt??"");return m?.[1]??""}function ageMinutesOf(item,now){for(const raw of[item.started_at,item.updated_at,item.dequeued_at,item.created_at]){if(!raw)continue;const ts=Date.parse(raw);if(Number.
|
|
15
15
|
isNaN(ts))continue;return Math.floor((now.getTime()-ts)/6e4)}return null}function exclusiveInflightEntries(groups,opts){const now=opts.now??new Date;const staleMinutes=opts.staleHours*60;const bySkill=new Map;for(const group of groups){for(const item of group.items){const skill=skillOfItem(item);if(!skill)continue;const status=group.status==="mixed"?item.status??"unknown":group.status;const ageMinutes=ageMinutesOf(item,now);if(status==="processing"&&ageMinutes!==null&&ageMinutes>staleMinutes)continue;
|
|
16
16
|
const entry={skill,status,runner:item.runner_id??"-",ageMinutes};const prev=bySkill.get(skill);if(!prev||(entry.ageMinutes??-1)>(prev.ageMinutes??-1))bySkill.set(skill,entry)}}return[...bySkill.values()].sort((a,b)=>a.skill.localeCompare(b.skill))}function formatExclusiveEntry(entry){const age=entry.ageMinutes===null?"\u4E0D\u660E":`${entry.ageMinutes}\u5206`;return`${entry.skill} status=${entry.status} runner=${entry.runner} \u7D4C\u904E=${age}`}import path2 from"path";var BUILTIN={primary_rotation:{complex:["claude"],search:["claude"],simple:["claude"]},fallback_chains:{complex:["claude","codex"],search:["codex","gemini","copilot","claude"],simple:["codex","gemini","copilot","claude"]}};function usesBedrock(env){return isBoolishTrue(env.CLAUDE_CODE_USE_BEDROCK)}var DEFAULT_CATEGORY="complex";var EFFORTS=new Set(["low","medium","high","xhigh","max"]);var MAX_COOLDOWN_SEC=3600;var DEFAULT_COOLDOWN_SEC=300;var AI_UNUSABLE_COOLDOWN_SEC=1800;
|
|
17
|
-
function loadAiConfig(inline,file,workspace){const
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
function loadAiConfig(inline,file,workspace){const read=readAiConfigFile(file,workspace);const warnings=read.problem===null?[]:[read.problem.startsWith("ai_config_file \u3092\u8AAD\u3081\u307E\u305B\u3093")?`${read.problem}
|
|
18
|
+
\u3053\u306E\u72B6\u614B\u3067\u306F\u5168\u30B9\u30AD\u30EB\u304C\u65E2\u5B9A\u30AB\u30C6\u30B4\u30EA\u3067\u8D70\u308A\u307E\u3059\u3002\u78BA\u8A8D: python3 -m json.tool <file>`:read.problem];return{config:new AiConfig(mergeAiConfig(read.file,inline)),warnings}}function readAiConfigFile(file,workspace){if(file===void 0||file.trim()==="")return{file:null,problem:null};const resolved=path2.isAbsolute(file)?file:path2.resolve(workspace,file);try{const parsed=JSON.parse(fs2.readFileSync(resolved,
|
|
19
|
+
"utf8"));if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed)){return{file:null,problem:`ai_config_file \u304C\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u306F\u3042\u308A\u307E\u305B\u3093: ${resolved}`}}return{file:parsed,problem:null}}catch(err){return{file:null,problem:`ai_config_file \u3092\u8AAD\u3081\u307E\u305B\u3093: ${resolved}\uFF08${err.message}\uFF09`}}}function mergeAiConfig(fromFile,inline){return{...fromFile??{},...inline??{}}}function reloadAiConfig(target,inline,file,workspace){
|
|
20
|
+
const hashBefore=target.hash();const read=readAiConfigFile(file,workspace);if(read.file===null){if(read.problem===null)return{status:"skipped",hashBefore,hashAfter:hashBefore,warnings:[]};return{status:"kept",hashBefore,hashAfter:hashBefore,warnings:[`${read.problem}
|
|
21
|
+
\u73FE\u5728\u306E\u8A2D\u5B9A\uFF08config_hash ${hashBefore}\uFF09\u306E\u307E\u307E\u8D70\u308A\u307E\u3059\u3002\u78BA\u8A8D: python3 -m json.tool <file>`]}}const changed=target.replace(mergeAiConfig(read.file,inline));return{status:changed?"updated":"unchanged",hashBefore,hashAfter:target.hash(),warnings:[]}}function stableJson(value){return JSON.stringify(value,(_key,v)=>v!==null&&typeof v==="object"&&!Array.isArray(v)?Object.fromEntries(Object.entries(v).sort(([a],[b])=>a.localeCompare(
|
|
22
|
+
b))):v)}var CHAIN_KEYS=["primary_rotation","fallback_chains"];var AiConfig=class _AiConfig{rotation=new Map;limitedUntil=new Map;unusableUntil=new Map;highRiskSkills;raw;constructor(raw){this.raw=raw;this.highRiskSkills=_AiConfig.highRiskSet(raw)}static highRiskSet(raw){return new Set((raw.high_risk_skills??[]).filter(v=>typeof v==="string"&&v!==""))}replace(next){if(stableJson(next)===stableJson(this.raw))return false;this.raw=next;this.highRiskSkills=_AiConfig.highRiskSet(next);return true}hash(){
|
|
20
23
|
const significant=Object.fromEntries(Object.entries(this.raw).filter(([k])=>!k.startsWith("_")&&!CHAIN_KEYS.includes(k)).sort(([a],[b])=>a.localeCompare(b)));return createHash("sha256").update(JSON.stringify(significant)).digest("hex").slice(0,16)}categoryForSkill(skill){const name=stripPrefix2(skill);return this.raw.skill_category?.[name]??DEFAULT_CATEGORY}usesAi(ai){const rotations=this.raw.primary_rotation??BUILTIN.primary_rotation;const chains=this.raw.fallback_chains??BUILTIN.fallback_chains;
|
|
21
24
|
const categories=new Set([DEFAULT_CATEGORY,...Object.keys(rotations),...Object.keys(chains),...Object.values(this.raw.skill_category??{})]);const matches=name=>isClaudeAi(ai)?isClaudeAi(name):name===ai;for(const category of categories){const rotation=rotations[category]??rotations[DEFAULT_CATEGORY]??BUILTIN.primary_rotation[DEFAULT_CATEGORY]??[];const chain=chains[category]??chains[DEFAULT_CATEGORY]??BUILTIN.fallback_chains[DEFAULT_CATEGORY]??["claude"];for(const name of[...rotation,...chain]){if(matches(
|
|
22
25
|
name))return true}}return false}chainFor(category){const chains=this.raw.fallback_chains??BUILTIN.fallback_chains;return chains[category]??chains[DEFAULT_CATEGORY]??BUILTIN.fallback_chains[DEFAULT_CATEGORY]??["claude"]}primaryFor(category,skill){const rotations=this.raw.primary_rotation??BUILTIN.primary_rotation;const entries=rotations[category]??rotations[DEFAULT_CATEGORY]??BUILTIN.primary_rotation[DEFAULT_CATEGORY]??[];if(entries.length===0)return"";const start=this.rotation.get(category)??0;for(let i=0;i<
|
|
@@ -45,4 +48,4 @@ return{auth:"unknown",detail:oneLine(`\u8CC7\u683C\u60C5\u5831\u3092\u89E3\u91C8
|
|
|
45
48
|
blockedReason:null}}function detectPending(ai){return{auth:"unknown",detail:"\u30ED\u30B0\u30A4\u30F3\u5224\u5B9A\u306E\u65B9\u6CD5\u304C\u672A\u78BA\u5B9A\u3067\u3059",blockedReason:`${ai} \u306F\u7121\u4EBA\u5B9F\u884C\u3067\u306E\u8A8D\u8A3C\u72B6\u614B\u3092\u5224\u5B9A\u3059\u308B\u65B9\u6CD5\u304C\u672A\u78BA\u5B9A\u306E\u305F\u3081\u9078\u629E\u3067\u304D\u307E\u305B\u3093`}}function detectAiClis(deps={}){const d=resolve(deps);return DETECTABLE_AIS.map(ai=>{const binPath=findOnPath(ai,d);
|
|
46
49
|
if(binPath===null){return{ai,installed:false,binPath:null,auth:"unknown",detail:"PATH \u306B\u898B\u3064\u304B\u308A\u307E\u305B\u3093\uFF08\u672A\u5C0E\u5165\uFF09",blockedReason:null}}const state=ai==="claude"?detectClaude(d):ai==="codex"?detectCodex(d,binPath):detectPending(ai);return{ai,installed:true,binPath,...state}})}function formatDetection(d,index){const selectable=isSelectable(d);const mark=selectable?d.auth==="authenticated"?"\u2705":"\u2754":" ";const num=index===null?" ":`${String(
|
|
47
50
|
index).padStart(2)}.`;const state=!d.installed?"\u672A\u5C0E\u5165":d.auth==="authenticated"?"\u30ED\u30B0\u30A4\u30F3\u6E08\u307F":d.auth==="unauthenticated"?"\u672A\u30ED\u30B0\u30A4\u30F3":"\u672A\u5224\u5B9A";const blocked=d.blockedReason===null?"":`
|
|
48
|
-
\u9078\u629E\u3067\u304D\u307E\u305B\u3093: ${oneLine(d.blockedReason)}`;return`${num} ${mark} ${d.ai.padEnd(8)} ${state.padEnd(8)} ${oneLine(d.detail)}${blocked}`}export{isBoolishTrue,resolveSpawnTarget,spawnSyncResolved,DEFAULT_CLAUDE_LAUNCHER,detectClaudeAutoSwitch,wrapWithAutoSwitch,activeSlotPath,isClaudeAi,normalizeSkillName,skillOfItem,exclusiveInflightEntries,formatExclusiveEntry,usesBedrock,loadAiConfig,AiConfig,modelFitsRoute,isUsableModelId,isDetectableAi,isSelectable,resolveDetectDeps,claudeConfigDir,detectAiClis,formatDetection};
|
|
51
|
+
\u9078\u629E\u3067\u304D\u307E\u305B\u3093: ${oneLine(d.blockedReason)}`;return`${num} ${mark} ${d.ai.padEnd(8)} ${state.padEnd(8)} ${oneLine(d.detail)}${blocked}`}export{isBoolishTrue,resolveSpawnTarget,spawnSyncResolved,DEFAULT_CLAUDE_LAUNCHER,detectClaudeAutoSwitch,wrapWithAutoSwitch,activeSlotPath,isClaudeAi,normalizeSkillName,skillOfItem,exclusiveInflightEntries,formatExclusiveEntry,usesBedrock,loadAiConfig,reloadAiConfig,AiConfig,modelFitsRoute,isUsableModelId,isDetectableAi,isSelectable,resolveDetectDeps,claudeConfigDir,detectAiClis,formatDetection};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{DEFAULT_CLAUDE_LAUNCHER,isBoolishTrue,loadAiConfig}from"./chunk-
|
|
3
|
+
import{DEFAULT_CLAUDE_LAUNCHER,isBoolishTrue,loadAiConfig}from"./chunk-H3JTPDCJ.js";import{killProcessTree}from"./chunk-N2UVRM3Z.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{projectFileKey}from"./chunk-GY7KI5E5.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";function stringField(value,key,fallback,warnings){if(value===void 0||value===null)return fallback;if(typeof value!=="string"||value.trim()===""){warnings.push(`claude_launcher.${key} \u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A '${fallback}' \u3092\u4F7F\u3044\u307E\u3059\uFF09`);return fallback}return value.trim()}function argvField(value,key,fallback,warnings,allowEmpty){if(value===void 0||value===null)return fallback;
|
|
4
4
|
if(!Array.isArray(value)){warnings.push(`claude_launcher.${key} \u306F\u6587\u5B57\u5217\u306E\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A [${fallback.join(", ")}] \u3092\u4F7F\u3044\u307E\u3059\uFF09`);return fallback}for(const v of value){if(typeof v!=="string"||v.trim()===""){warnings.push(`claude_launcher.${key} \u306E\u8981\u7D20\u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A [${fallback.
|
|
5
5
|
join(", ")}] \u3092\u4F7F\u3044\u307E\u3059\uFF09`);return fallback}}if(value.length===0&&!allowEmpty){warnings.push(`claude_launcher.${key} \u306F1\u3064\u4EE5\u4E0A\u306E\u5F15\u6570\u304C\u8981\u308A\u307E\u3059\uFF08\u65E2\u5B9A [${fallback.join(", ")}] \u3092\u4F7F\u3044\u307E\u3059\uFF09`);return fallback}return value.map(v=>v.trim())}function probeMatchField(value,warnings){const raw=stringField(value,"probe_match",DEFAULT_CLAUDE_LAUNCHER.probeMatch,warnings);try{new RegExp(raw,"m")}catch(err){
|
|
6
6
|
warnings.push(`claude_launcher.probe_match \u306F\u6B63\u898F\u8868\u73FE\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\uFF08${err.message}\uFF09\u3002\u65E2\u5B9A '${DEFAULT_CLAUDE_LAUNCHER.probeMatch}' \u3092\u4F7F\u3044\u307E\u3059`);return DEFAULT_CLAUDE_LAUNCHER.probeMatch}return raw}var NOT_YET_APPLIED=[{key:"probe",get:c=>c.probe},{key:"probe_match",get:c=>c.probeMatch},{key:"exec_args",get:c=>c.execArgs},{key:"active_args",get:c=>c.activeArgs}];function sameAsDefault(key,parsed){
|
|
@@ -74,4 +74,5 @@ daemon,maxCycles:input.daemon?Number.MAX_SAFE_INTEGER:input.maxCycles??1,interva
|
|
|
74
74
|
env.PLAN_LOCK_RENEW_INTERVAL,Math.trunc(planLockTtlSec/3),1,"PLAN_LOCK_RENEW_INTERVAL="),planLockStealAttempts:num2(env.PLAN_LOCK_STEAL_ATTEMPTS,3,0,"PLAN_LOCK_STEAL_ATTEMPTS="),planLockPermanentMax:num2(env.PLAN_LOCK_PERMANENT_MAX,3,1,"PLAN_LOCK_PERMANENT_MAX="),scheduleMidcycleMax:num2(env.SCHEDULE_MIDCYCLE_MAX,6,1,"SCHEDULE_MIDCYCLE_MAX="),blockerRecoveryMaxPerDay:num2(env.BLOCKER_RECOVERY_MAX_PER_DAY,2,1,"BLOCKER_RECOVERY_MAX_PER_DAY="),releaseRerunAutoEnqueue:env.RELEASE_RERUN_AUTOENQUEUE_ENABLED!==
|
|
75
75
|
"false",releaseRerunMaxPerCause:num2(env.RELEASE_RERUN_MAX_PER_CAUSE,2,1,"RELEASE_RERUN_MAX_PER_CAUSE="),writebackMaxAgeDays:num2(env.AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS,7,1,"AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS="),scheduleTimezone:nonEmpty(env.AGENT_LOOP_SCHEDULE_TZ)??"Asia/Tokyo",counterTimezone:nonEmpty(env.AGENT_LOOP_COUNTER_TZ)??"Asia/Tokyo",compileCommand:local.compile_command!==void 0&&local.compile_command.length>0?local.compile_command:null,charterFile:nonEmpty(env.CHARTER_FILE)??nonEmpty(local.
|
|
76
76
|
charter_file)??"CONSTITUTION.md",charterEnabled:resolveCharterEnabled(env.CHARTER_ENABLED,local.charter_enabled,m=>warnings.push(m)),charterPrefix:charterWrapper(env.CHARTER_PREFIX,local.charter_prefix,"charter_prefix",m=>warnings.push(m)),charterSuffix:charterWrapper(env.CHARTER_SUFFIX,local.charter_suffix,"charter_suffix",m=>warnings.push(m)),planEnabled:resolveBoolSetting(env.PLAN_ENABLED,local.plan_enabled,"plan_enabled",true,"\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u5B9F\u884C\u3057\u307E\u3059",
|
|
77
|
-
m=>warnings.push(m)),ai:ai.config,operations:operations.operations,claudeLauncher:claudeLauncher.launcher,capacityProbe:capacityProbe.probe,prefetch:prefetch.hooks,preflight:preflight.hooks,configHash:ai.config.hash(),version:input.version,warnings,releaseOutcomeLogPath:releaseOutcomeLogPath(env)}}function localDate(timezone,now=new Date){const fmt=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});
|
|
77
|
+
m=>warnings.push(m)),ai:ai.config,aiSource:{inline:local.ai,file:local.ai_config_file},operations:operations.operations,claudeLauncher:claudeLauncher.launcher,capacityProbe:capacityProbe.probe,prefetch:prefetch.hooks,preflight:preflight.hooks,configHash:ai.config.hash(),version:input.version,warnings,releaseOutcomeLogPath:releaseOutcomeLogPath(env)}}function localDate(timezone,now=new Date){const fmt=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});
|
|
78
|
+
return fmt.format(now)}export{runPrefetch,runPreflight,formatHookWiring,formatHookIds,CapacityReporter,parseClaudeLauncher,evaluateOwnership,describeOperations,loopStateDir,localConfigPath,buildLoopConfig,localDate};
|