@tocca-systems/twp-cli 0.24.0 → 0.25.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/CHANGELOG.public.md +14 -0
- package/README.md +98 -4
- package/dist/agent-loop-ZP47LTUE.js +75 -0
- package/dist/{ai-dispatch-36HRDRLF.js → ai-dispatch-VSCKUY6J.js} +1 -1
- package/dist/{api-command-NMYYJKZH.js → api-command-VWJXBUCJ.js} +2 -2
- package/dist/{app-2KMY3QPM.js → app-3JIU5OUX.js} +49 -48
- package/dist/attendance-42XLURM7.js +21 -0
- package/dist/{auto-update-worker-AXBJIMFP.js → auto-update-worker-OBFGN6FY.js} +1 -1
- package/dist/{backlog-7MJIOT22.js → backlog-KSMQIC2R.js} +1 -1
- package/dist/charter-command-ULFOEZWE.js +26 -0
- package/dist/chunk-BKZGBJWT.js +15 -0
- package/dist/{chunk-DMDVLOAY.js → chunk-G4OO4M44.js} +1 -1
- package/dist/{chunk-WGVHYTZV.js → chunk-IRAZ27WL.js} +1 -1
- package/dist/{chunk-4V4T5ZUS.js → chunk-KEP5QSS4.js} +40 -15
- package/dist/{chunk-I3YPO7CY.js → chunk-KUIFIN7P.js} +1 -1
- package/dist/{chunk-QOUFHYK5.js → chunk-NIAOX77K.js} +1 -1
- package/dist/chunk-P4AEFKLM.js +13 -0
- package/dist/{chunk-VCMVTC6B.js → chunk-PK6CUUAQ.js} +1 -1
- package/dist/chunk-SP27PYHC.js +3 -0
- package/dist/chunk-UDPJ2IGK.js +7 -0
- package/dist/chunk-VCZVITWG.js +13 -0
- package/dist/{chunk-UIWGEBWI.js → chunk-VGMWPPGD.js} +13 -11
- package/dist/{chunk-UG2I6VRD.js → chunk-VYDEUFGU.js} +1 -1
- package/dist/{chunk-Y2QAP6SU.js → chunk-WQ66EYZS.js} +1 -1
- package/dist/{chunk-6NCY4NPV.js → chunk-X45SJNT2.js} +4 -4
- package/dist/chunk-YWGYRISN.js +34 -0
- package/dist/{chunk-WOUKWOAR.js → chunk-Z2MNO3FT.js} +10 -9
- package/dist/cli.js +33 -8
- package/dist/{commands-U36UTCKR.js → commands-OFLBUP6O.js} +1 -1
- package/dist/{commands-6YTOVZ5P.js → commands-RG7M6E5K.js} +80 -85
- package/dist/{department-JOXXJKQB.js → department-GH475WCF.js} +1 -1
- package/dist/{job-title-L47J6TZY.js → job-title-FC2GWDE7.js} +1 -1
- package/dist/{logout-guard-FO7KZL3X.js → logout-guard-3PB3VMGP.js} +1 -1
- package/dist/{media-ZMDYHHNN.js → media-TD7D4TXF.js} +1 -1
- package/dist/{oneshot-KYATQPL7.js → oneshot-QQOOZZDT.js} +5 -5
- package/dist/{position-FHWCMMBQ.js → position-4RHTV3IK.js} +1 -1
- package/dist/{project-ZODASYER.js → project-DBNWB47J.js} +1 -1
- package/dist/{run-QCDT35NT.js → run-VNHAQO24.js} +1 -1
- package/dist/{schedule-command-GKXKNMLG.js → schedule-command-FJU7JFNR.js} +1 -1
- package/dist/{server-settings-CG3EM7R7.js → server-settings-YL6KALXG.js} +1 -1
- package/dist/{setup-6CXUVCF5.js → setup-BJKIHANC.js} +1 -1
- package/dist/skill-command-V26WGVXU.js +61 -0
- package/dist/{task-G5YWQ6L5.js → task-7VOYCG26.js} +2 -2
- package/dist/{update-PZBUIYOL.js → update-RLKK6N7U.js} +1 -1
- package/dist/user-UU2SLVC4.js +336 -0
- package/package.json +1 -1
- package/dist/charter-command-UBUE3KUO.js +0 -36
- package/dist/chunk-EJ474UDB.js +0 -3
- package/dist/chunk-HW3QGKYR.js +0 -30
- package/dist/chunk-IJLJGDMZ.js +0 -7
- package/dist/chunk-ODLJ2LNQ.js +0 -13
- package/dist/user-DO4VNIBR.js +0 -204
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelIndex,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{
|
|
4
|
-
import{DEFAULT_MAX_TOKENS,emptyUsage}from"./chunk-
|
|
3
|
+
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelIndex,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{redactSecretValues,redactSecrets}from"./chunk-YVAN3H5W.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{isSafePathSegment}from"./chunk-GMBJTG6A.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-FTYJZFEK.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-NAUH75MM.js";
|
|
4
|
+
import{DEFAULT_MAX_TOKENS,emptyUsage,isPrivateTwpHome,isTrustworthyCacheFile,writePrivateFileAtomic}from"./chunk-Z2MNO3FT.js";import{AuthSession,NotLoggedInError,SessionExpiredError,withFileLock}from"./chunk-XNLIEUAW.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{configReadDirs,ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs2 from"fs";import path3 from"path";import os2 from"os";import{realpathSync}from"fs";import{homedir}from"os";import{dirname,isAbsolute,relative,resolve,sep}from"path";var PathDeniedError=class extends Error{constructor(message){super(message);this.name="PathDeniedError"}};function resolveToolPath(input,cwd,home=homedir()){if(typeof input!=="string"||input.trim()===""){throw new PathDeniedError("path must be a non-empty string")}const expanded=expandHome(input,home);const abs=isAbsolute(expanded)?resolve(expanded):resolve(cwd,expanded);const root=realOrSelf(resolve(cwd));assertInside(abs,resolve(cwd),abs);assertNotSecret(abs,home);const real=realOrSelf(abs);if(real!==
|
|
5
5
|
abs){assertInside(real,root,abs);assertNotSecret(real,home)}return abs}function realToolPath(input,cwd,home=homedir()){return realOrSelf(resolveToolPath(input,cwd,home))}function assertInside(target,root,reported){const rel=relative(root,target);const outside=rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel);if(outside){throw new PathDeniedError(`path escapes the working directory (${reported}). Only paths under ${root} can be accessed.`)}}function realOrSelf(target){let current=target;const rest=[];
|
|
6
6
|
for(;;){try{const real=realpathSync(current);return rest.length===0?real:resolve(real,...rest.reverse())}catch{const parent=dirname(current);if(parent===current)return target;rest.push(current.slice(parent.length+1));current=parent}}}function assertNotSecret(absPath,home=homedir(),env=process.env){const reason=secretReason(absPath,home,env);if(reason!==null)throw new PathDeniedError(`refusing to access ${absPath}: ${reason}`)}function secretReason(absPath,_home=homedir(),env=process.env){const lower=absPath.
|
|
7
7
|
toLowerCase();const segments=lower.split(sep);const base=segments[segments.length-1]??"";const parent=segments[segments.length-2]??"";if(base===".env"||base.startsWith(".env."))return".env files are denied (design \xA77)";if(segments.includes(".ssh"))return"SSH key material is denied (design \xA77)";if(parent===".git"&&base==="config"){return".git/config is denied (it can hold a GitHub token in the remote URL)"}if(base===".netrc"||base==="_netrc"||base===".npmrc")return"credential files are deni\
|
|
@@ -74,9 +74,9 @@ home}:{},...c.root?{root:c.root}:{}}}function verdictFromRule(decision,c,target)
|
|
|
74
74
|
\u300C${name==="git"?`git ${prefix}`:prefix}\u300D\u3067\u59CB\u307E\u308B\u30B3\u30DE\u30F3\u30C9\u3092\u78BA\u8A8D\u3057\u306A\u3044`}else{rule=name;label=`\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u306F ${name} \u3092\u78BA\u8A8D\u3057\u306A\u3044`}if(rejectReason(rule)!==null)return[];const{rule:parsed}=parseRule(rule,"allow");if(parsed===null||!ruleMatches(parsed,{toolName:name,input:target.input,cwd}))return[];return[{rule,label}]}function prefixFor(toolName,input){if(toolName===
|
|
75
75
|
"git"){const sub=input["subcommand"];return typeof sub==="string"&&SUBCOMMAND.test(sub)?sub:null}if(toolName!=="bash")return null;const command=input["command"];if(typeof command!=="string")return null;const words=command.trim().split(/[ \t]+/);const head=words[0]??"";if(!HEAD.test(head)||NO_PREFIX_HEADS.has(head))return null;const second=words[1];if(second===void 0||!SUBCOMMAND.test(second))return null;const pair=`${head} ${second}`;if(!RUNNER_SUBCOMMANDS.has(pair))return pair;const third=words[2];
|
|
76
76
|
return third!==void 0&&SCRIPT_NAME.test(third)?`${pair} ${third}`:null}function validateInput(schema,input){const errors=[];if(typeof input!=="object"||input===null||Array.isArray(input)){return{ok:false,errors:["input must be a JSON object"],value:{}}}const value={...input};const props=schema.properties??{};for(const key of schema.required??[]){if(value[key]===void 0||value[key]===null)errors.push(`missing required property: ${key}`)}if(schema.additionalProperties===false){for(const key of Object.keys(value)){if(!(key in props))errors.push(`unknown property: ${key}`)}}
|
|
77
|
-
for(const[key,sub]of Object.entries(props)){if(value[key]===void 0){if(sub.default!==void 0)value[key]=sub.default;continue}checkValue(`${key}`,sub,value[key],errors)}return{ok:errors.length===0,errors,value}}function checkValue(
|
|
78
|
-
isInteger(value))errors.push(`${
|
|
79
|
-
if(schema.enum&&!schema.enum.some(v=>v===value)){errors.push(`${
|
|
77
|
+
for(const[key,sub]of Object.entries(props)){if(value[key]===void 0){if(sub.default!==void 0)value[key]=sub.default;continue}checkValue(`${key}`,sub,value[key],errors)}return{ok:errors.length===0,errors,value}}function checkValue(path9,schema,value,errors){switch(schema.type){case"string":if(typeof value!=="string")errors.push(`${path9} must be a string`);break;case"boolean":if(typeof value!=="boolean")errors.push(`${path9} must be a boolean`);break;case"integer":if(typeof value!=="number"||!Number.
|
|
78
|
+
isInteger(value))errors.push(`${path9} must be an integer`);break;case"number":if(typeof value!=="number"||!Number.isFinite(value))errors.push(`${path9} must be a number`);break;case"array":if(!Array.isArray(value)){errors.push(`${path9} must be an array`);break}if(schema.items){value.forEach((item,i)=>checkValue(`${path9}[${i}]`,schema.items,item,errors))}break;case"object":if(typeof value!=="object"||value===null||Array.isArray(value)){errors.push(`${path9} must be an object`)}break;default:break}
|
|
79
|
+
if(schema.enum&&!schema.enum.some(v=>v===value)){errors.push(`${path9} must be one of: ${schema.enum.join(", ")}`)}if(typeof value==="number"){if(schema.minimum!==void 0&&value<schema.minimum)errors.push(`${path9} must be >= ${schema.minimum}`);if(schema.maximum!==void 0&&value>schema.maximum)errors.push(`${path9} must be <= ${schema.maximum}`)}}async function executeTool(tool,rawInput,deps,callId){const validated=validateInput(tool.inputSchema,rawInput);if(!validated.ok){const content=`Invalid input for ${tool.name}:
|
|
80
80
|
- ${validated.errors.join("\n- ")}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"error",bytes:Buffer.byteLength(content),mode:deps.mode.id,reasonCode:"invalid_input",callId});return{content,isError:true,summary:`${tool.name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}const input=validated.value;if(tool.name===INDIRECT_TOOL&&deps.prepareIndirect){await deps.prepareIndirect(input).catch(()=>void 0)}let judged={tool};const verdictTarget=()=>judged;const recordDecision=(decision,reasonCode,reason)=>{
|
|
81
81
|
deps.audit.record({event:"decision",tool:verdictTarget().tool.name,risk:verdictTarget().tool.risk,decision,reasonCode,reason,mode:deps.mode.id,rawInput:input,callId})};const verdict=checkToolPermission({tool,input},{mode:deps.mode,cwd:deps.ctx.cwd,sessionAllow:deps.sessionAllow,...deps.sessionRules?{sessionRules:deps.sessionRules}:{},...deps.permissionLayers?{layers:deps.permissionLayers}:{},...deps.permissionMode!==void 0?{permissionMode:deps.permissionMode}:{},...deps.resolveTool?{resolveTool:deps.
|
|
82
82
|
resolveTool}:{}});const policy=verdict.decision;judged=verdict.target;const target=verdict.target;if(policy==="deny"){recordDecision("deny",reasonCodeOf(verdict),verdict.reason);return{content:denyMessage(tool.name,verdict,deps),isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08${denySummary(verdict,deps)}\uFF09`}}const preview=safePreview(tool,input);const noAlwaysReason=neverAutoAllowReason(target.tool,target.input)??autoApproveExemptReason(target.tool,target.input,deps.ctx.cwd)??verdict.
|
|
@@ -204,20 +204,43 @@ limit"]:DEFAULT_LIMIT_LINES;const slice=lines.slice(offset-1,offset-1+limit);let
|
|
|
204
204
|
ne breaks."}},required:["path","content"]},preview(input){const content=typeof input["content"]==="string"?input["content"]:"";return`write_file \xB7 ${String(input["path"]??"")} (${content.split("\n").length} \u884C)`},async prepare(input,ctx){const abs=resolveToolPath(String(input["path"]),ctx.cwd);const before=await readFile4(abs,"utf8").catch(()=>"");return{path:toolRelative(ctx.cwd,abs),before,after:String(input["content"]??"")}},async run(input,ctx){const abs=resolveToolPath(String(input["\
|
|
205
205
|
path"]),ctx.cwd);const existing=await readFile4(abs,"utf8").catch(()=>null);const eol=existing===null?"\n":detectEol(existing);const body=applyEol(String(input["content"]),eol);await mkdir(dirname3(abs),{recursive:true});await writeFile2(abs,body,"utf8");const rel=toolRelative(ctx.cwd,abs);return{content:`Wrote ${rel} (${body.split(eol).length} lines${eol==="\r\n"?", CRLF preserved":""}).`,summary:`write_file \xB7 ${rel}`,diff:{path:rel,before:existing??"",after:String(input["content"])}}}};var RESIDENT_TOKEN_CAP=8e3;function localTools(choice=selectShell()){return[readFileTool,writeFileTool,editFileTool,createBashTool(choice),globTool,grepTool,gitTool]}function buildResidentSet(mode,opts={}){const all=opts.tools??localTools();const cap=opts.cap??RESIDENT_TOKEN_CAP;const eligible=all.filter(tool=>matchesAnyGlob(tool.name,mode.tools)&&applyPermissionMode(checkPermission(tool.name,mode),tool.risk,opts.permissionMode).decision!=="deny"&&!isWholeToolDenied(tool.name,opts.permissionLayers??[]));const usage=opts.usage;
|
|
206
206
|
const pinned=opts.pinned;const ordered=usage===void 0&&pinned===void 0?eligible:eligible.map((tool,i)=>({tool,i,pin:pinned?.has(tool.name)===true,uses:usage?.get(tool.name)??0})).sort((a,b)=>Number(b.pin)-Number(a.pin)||b.uses-a.uses||a.i-b.i).map(entry=>entry.tool);const tools=[];const dropped=[];let tokens=0;for(const tool of ordered){const cost=estimateToolTokens(tool);if(tokens+cost>cap){dropped.push(tool.name);continue}tools.push(tool);tokens+=cost}return{tools,wire:tools.map(toWireTool),tokens,
|
|
207
|
-
dropped}}function estimateToolTokens(tool){return Math.ceil(JSON.stringify(toWireTool(tool)).length/4)}function matchesAnyGlob(name,patterns){return patterns.some(pattern=>globToRegExp(pattern).test(name))}function globToRegExp(pattern){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${escaped}$`)}
|
|
207
|
+
dropped}}function estimateToolTokens(tool){return Math.ceil(JSON.stringify(toWireTool(tool)).length/4)}function matchesAnyGlob(name,patterns){return patterns.some(pattern=>globToRegExp(pattern).test(name))}function globToRegExp(pattern){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${escaped}$`)}import fs5 from"fs";import path8 from"path";import{createHash}from"crypto";var TOOL_CATALOG_PATH="/api/v2/cli/tool-catalog";var CACHE_LOCK_WAIT_MS=2e3;var bundledReader={index:loadCommandModelIndex,domain:loadCommandModelDomain};function cacheKey(profile,apiUrl){return createHash("sha256").update(`${profile}
|
|
208
|
+
${apiUrl}`).digest("hex").slice(0,24)}function toolCatalogCachePaths(profile,apiUrl,env=process.env){const base=path8.join(twpHomeDir(env),`tool-catalog-${cacheKey(profile,apiUrl)}`);return{meta:`${base}.meta.json`,body:`${base}.json`,lock:`${base}.lock`}}function homeIsPrivate(env){return isPrivateTwpHome(twpHomeDir(env))}var REASON_NO_CACHE="\u30B5\u30FC\u30D0\u914D\u4FE1\u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u3042\u308A\u307E\u305B\u3093";var REASON_UNTRUSTED_HOME="~/.twp \u304C\u4ED6\u30E6\u30FC\u30B6\u30FC\u304B\u3089\u66F8\u3051\u308B\u30FB\u30EA\u30F3\u30AF\u3067\
|
|
209
|
+
\u3042\u308B\u305F\u3081\u3001\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u4F7F\u3044\u307E\u305B\u3093";var REASON_BROKEN="\u30B5\u30FC\u30D0\u914D\u4FE1\u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u58CA\u308C\u3066\u3044\u308B\u305F\u3081\u540C\u68B1\u7248\u3092\u4F7F\u3044\u307E\u3059";function readTrustedJson(file,env){if(!homeIsPrivate(env)||!isTrustworthyCacheFile(file))return void 0;try{return JSON.parse(fs5.readFileSync(file,"utf8"))}catch{return void 0}}function readMeta(profile,apiUrl,account,env){
|
|
210
|
+
const raw=readTrustedJson(toolCatalogCachePaths(profile,apiUrl,env).meta,env);if(!raw||typeof raw!=="object")return null;if(raw.profile!==profile||raw.api_url!==apiUrl||(raw.account??null)!==account)return null;if(typeof raw.version!=="string"||!isVersionToken(raw.version))return null;return{version:raw.version,profile,api_url:apiUrl,account,catalog_version:typeof raw.catalog_version==="string"?raw.catalog_version:null,tool_count:typeof raw.tool_count==="number"?raw.tool_count:0,fetched_at:typeof raw.
|
|
211
|
+
fetched_at==="string"?raw.fetched_at:"",checked_at:typeof raw.checked_at==="string"?raw.checked_at:"",last_result:raw.last_result==="not-modified"?"not-modified":"updated"}}function isVersionToken(value){return/^[A-Za-z0-9._-]{1,128}$/.test(value)}var DOMAIN_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var METHODS=new Set(["GET","POST","PUT","PATCH","DELETE"]);var PATH_RE=/^\/v2\/[A-Za-z0-9_\-{}/.]*$/;function isSafeOperationPath(value){return PATH_RE.test(value)&&!value.split("/").some(segment=>segment===".\
|
|
212
|
+
."||segment===".")}var RISKS=new Set(["read","write","destructive"]);function isParam(value){if(typeof value!=="object"||value===null)return false;const p=value;return typeof p["name"]==="string"&&(typeof p["type"]==="string"||Array.isArray(p["type"])&&p["type"].every(t=>typeof t==="string"))&&typeof p["required"]==="boolean"&&(p["description"]===void 0||typeof p["description"]==="string")}function isCatalogOperation(value){if(typeof value!=="object"||value===null)return false;const o=value;const body=o["\
|
|
213
|
+
body"];return typeof o["name"]==="string"&&typeof o["domain"]==="string"&&DOMAIN_RE.test(o["domain"])&&typeof o["operationId"]==="string"&&typeof o["method"]==="string"&&METHODS.has(o["method"])&&typeof o["path"]==="string"&&isSafeOperationPath(o["path"])&&typeof o["summary"]==="string"&&Array.isArray(o["pathParams"])&&o["pathParams"].every(isParam)&&Array.isArray(o["queryParams"])&&o["queryParams"].every(isParam)&&(body===null||typeof body==="object"&&!Array.isArray(body))&&(o["resultPath"]===null||
|
|
214
|
+
typeof o["resultPath"]==="string")&&typeof o["risk"]==="string"&&RISKS.has(o["risk"])&&Array.isArray(o["aliases"])&&o["aliases"].every(a=>typeof a==="string")}function parseToolCatalog(raw){if(typeof raw!=="object"||raw===null)return null;const r=raw;const version=r["version"];const tools=r["tools"];if(typeof version!=="string"||!isVersionToken(version)||!Array.isArray(tools))return null;if(!tools.every(isCatalogOperation))return null;const names=new Set;for(const op of tools){const key=`${op.domain}\
|
|
215
|
+
${op.name}`;if(names.has(key))return null;names.add(key)}return{version,catalogVersion:typeof r["catalog_version"]==="string"?r["catalog_version"]:null,tools}}var RISK_ORDER={read:0,write:1,destructive:2};function methodFloor(method){if(method==="GET")return"read";return method==="DELETE"?"destructive":"write"}function stronger(a,b){return RISK_ORDER[a]>=RISK_ORDER[b]?a:b}function readerFromTools(tools,bundled=bundledReader){const byDomain=new Map;for(const op of tools){const list=byDomain.get(
|
|
216
|
+
op.domain);if(list)list.push(op);else byDomain.set(op.domain,[op])}let indexCache=null;const domainCache=new Map;return{index:async()=>{if(indexCache!==null)return indexCache;const summaries=new Map;try{for(const entry of(await bundled.index()).domains)summaries.set(entry.domain,entry.summary)}catch{}const domains=[...byDomain.entries()].map(([domain,ops])=>({domain,summary:summaries.get(domain)??"",operationCount:ops.length}));indexCache={schemaVersion:1,specVersion:"",domains,totals:{domains:domains.
|
|
217
|
+
length,operations:tools.length}};return indexCache},domain:async domain=>{const cached=domainCache.get(domain);if(cached!==void 0)return cached;const ops=byDomain.get(domain);if(ops===void 0){throw new CommandModelMissingError(`\u30C9\u30E1\u30A4\u30F3 ${domain} \u306F\u3053\u306E\u30A2\u30AB\u30A6\u30F3\u30C8\u306E\u30AB\u30BF\u30ED\u30B0\u306B\u3042\u308A\u307E\u305B\u3093`)}const floor=new Map;try{for(const op of(await bundled.domain(domain)).operations)floor.set(op.operationId,op.risk)}catch{}
|
|
218
|
+
const file={domain,operations:ops.map(op=>{const risk=stronger(stronger(op.risk,methodFloor(op.method)),floor.get(op.operationId)??"read");return risk===op.risk?op:{...op,risk}})};domainCache.set(domain,file);return file}}}var ToolCatalog=class{profile;apiUrl;env;bundled;now;account;decided=null;refreshState;refreshPromise=null;constructor(opts){this.profile=opts.profile;this.apiUrl=opts.apiUrl;this.env=opts.env??process.env;this.bundled=opts.bundled??bundledReader;this.now=opts.now??Date.now;this.
|
|
219
|
+
account=opts.account??(()=>null)}meta(){return readMeta(this.profile,this.apiUrl,this.account(),this.env)}index(){return this.decide().reader.index()}domain(domain){return this.decide().reader.domain(domain)}status(){const refresh=this.refreshState!==void 0?{refresh:this.refreshState}:{};if(this.decided!==null){const{origin,reason,meta:meta2}=this.decided;return{origin,...reason!==void 0?{reason}:{},...metaFields(meta2),...refresh}}if(!homeIsPrivate(this.env))return{origin:"undecided",next:"bund\
|
|
220
|
+
led",reason:REASON_UNTRUSTED_HOME,...refresh};const meta=this.meta();if(meta!==null&&!isTrustworthyCacheFile(toolCatalogCachePaths(this.profile,this.apiUrl,this.env).body)){return{origin:"undecided",next:"bundled",reason:REASON_BROKEN,...refresh}}return meta!==null?{origin:"undecided",next:"server-cache",...metaFields(meta),...refresh}:{origin:"undecided",next:"bundled",reason:REASON_NO_CACHE,...refresh}}decide(){if(this.decided!==null)return this.decided;this.decided=this.loadCache()??{reader:this.
|
|
221
|
+
bundled,origin:"bundled",reason:homeIsPrivate(this.env)?REASON_NO_CACHE:REASON_UNTRUSTED_HOME};return this.decided}loadCache(){const meta=this.meta();if(meta===null)return null;const paths=toolCatalogCachePaths(this.profile,this.apiUrl,this.env);const parsed=parseToolCatalog(readTrustedJson(paths.body,this.env));if(parsed===null||parsed.version!==meta.version){removeQuietly(paths.meta);return{reader:this.bundled,origin:"bundled",reason:REASON_BROKEN}}return{reader:readerFromTools(parsed.tools,this.
|
|
222
|
+
bundled),origin:"server-cache",meta}}refresh(get){this.refreshPromise??=this.doRefresh(get).then(outcome=>{this.refreshState=outcome;return outcome});if(this.refreshState===void 0)this.refreshState="running";return this.refreshPromise}async doRefresh(get){if(!homeIsPrivate(this.env))return{result:"failed",detail:REASON_UNTRUSTED_HOME};const account=this.account();const meta=this.meta();const paths=toolCatalogCachePaths(this.profile,this.apiUrl,this.env);const since=meta!==null&&isTrustworthyCacheFile(
|
|
223
|
+
paths.body)?meta.version:null;let raw;try{raw=await get(TOOL_CATALOG_PATH,since!==null?{since}:void 0)}catch(err){const status=statusOf(err);if(status===304&&meta!==null){try{await this.locked(paths.lock,async()=>{if(this.meta()?.version===meta.version)this.writeMeta(paths.meta,{...meta,checked_at:this.iso(),last_result:"not-modified"})})}catch{}return{result:"not-modified"}}if(status===404||status===401||status===403||isAuthError(err)){removeQuietly(paths.meta);removeQuietly(paths.body);return{
|
|
224
|
+
result:"unavailable",detail:status!==null?`\u30B5\u30FC\u30D0\u304C ${status} \u3092\u8FD4\u3057\u307E\u3057\u305F`:"\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093"}}return{result:"failed",detail:status!==null?`\u30B5\u30FC\u30D0\u304C ${status} \u3092\u8FD4\u3057\u307E\u3057\u305F`:`\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\uFF08${messageOf(err)}\uFF09`}}const parsed=parseToolCatalog(raw);if(parsed===null)return{result:"failed",detail:"\u30B5\u30FC\u30D0\u306E\u5FDC\u7B54\u306E\u5F62\u304C\u9055\u3044\u307E\u3059"};
|
|
225
|
+
try{ensureTwpHome(this.env);await this.locked(paths.lock,async()=>{writePrivateFileAtomic(paths.body,JSON.stringify({version:parsed.version,catalog_version:parsed.catalogVersion,tools:parsed.tools}));const at=this.iso();this.writeMeta(paths.meta,{version:parsed.version,profile:this.profile,api_url:this.apiUrl,account,catalog_version:parsed.catalogVersion,tool_count:parsed.tools.length,fetched_at:at,checked_at:at,last_result:"updated"})})}catch(err){return{result:"failed",detail:`\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u66F8\u3051\u307E\u305B\u3093\uFF08${messageOf(
|
|
226
|
+
err)}\uFF09`}}return{result:"updated"}}async locked(lockPath,fn){await withFileLock(lockPath,fn,CACHE_LOCK_WAIT_MS)}writeMeta(file,meta){try{ensureTwpHome(this.env);writePrivateFileAtomic(file,`${JSON.stringify(meta,null,2)}
|
|
227
|
+
`)}catch{}}iso(){return new Date(this.now()).toISOString()}};function metaFields(meta){if(meta===void 0)return{};return{version:meta.version,toolCount:meta.tool_count,...meta.fetched_at!==""?{fetchedAt:meta.fetched_at}:{},...meta.checked_at!==""?{checkedAt:meta.checked_at}:{}}}function statusOf(err){const status=err?.status;return typeof status==="number"?status:null}function isAuthError(err){return err instanceof NotLoggedInError||err instanceof SessionExpiredError}function messageOf(err){return err instanceof
|
|
228
|
+
Error?err.message:String(err)}function removeQuietly(file){try{fs5.rmSync(file,{force:true})}catch{}}function describeToolCatalog(status){const origin=status.origin==="undecided"?status.next:status.origin;const head=origin==="server-cache"?`\u30B5\u30FC\u30D0\u914D\u4FE1\uFF08${status.toolCount??"?"} \u64CD\u4F5C\u30FB\u7248 ${status.version?.slice(0,12)??"?"}\u30FB\u53D6\u5F97 ${status.fetchedAt??"?"}\uFF09`:`\u540C\u68B1\u7248\uFF08${status.reason??"\u7406\u7531\u4E0D\u660E"}\uFF09`;const when=status.
|
|
229
|
+
origin==="undecided"?"\uFF08\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u306F\u307E\u3060\u672A\u4F7F\u7528\u30FB\u6B21\u306B\u4F7F\u3046\u51FA\u3069\u3053\u308D\uFF09":"";const refresh=status.refresh;const tail=refresh===void 0?"\u66F4\u65B0: \u672A\u5B9F\u884C":refresh==="running"?"\u66F4\u65B0: \u53D6\u5F97\u4E2D":`\u66F4\u65B0: ${REFRESH_LABEL[refresh.result]}${refresh.detail!==void 0?`\uFF08${refresh.detail}\uFF09`:""}`;return`TWP \u30C4\u30FC\u30EB\u30AB\u30BF\u30ED\u30B0: ${head}${when}\
|
|
230
|
+
\xB7 ${tail}`}var REFRESH_LABEL={updated:"\u65B0\u3057\u3044\u7248\u3092\u53D6\u5F97\u3057\u3066\u4FDD\u5B58","not-modified":"\u6700\u65B0\uFF08304\uFF09",unavailable:"\u30B5\u30FC\u30D0\u914D\u4FE1\u306A\u3057\u30FB\u6B21\u56DE\u304B\u3089\u540C\u68B1\u7248",failed:"\u5931\u6557\u30FB\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u7DAD\u6301"};var CATALOG_TOOL_PREFIX="twp_";var WIRE_NAME_RE=/^[A-Za-z0-9_-]{1,64}$/;var MAX_RESULT_CHARS=4e4;function catalogToolName(op){if(op.name.includes("_")||op.domain.includes("_"))return null;const name=`${CATALOG_TOOL_PREFIX}${op.name.replace(/\./g,"-")}_${op.domain}`;return WIRE_NAME_RE.test(name)?name:null}function parseCatalogToolName(name){if(!name.startsWith(CATALOG_TOOL_PREFIX))return null;const rest=name.slice(CATALOG_TOOL_PREFIX.length);const sep4=rest.indexOf("_");if(sep4<=0||sep4===rest.length-
|
|
208
231
|
1)return null;const domain=rest.slice(sep4+1);return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(domain)?{domain}:null}function toolRiskOf(risk){switch(risk){case"read":return"read";case"write":return"write";default:return"exec"}}var SIMPLE_TYPES=new Set(["string","integer","number","boolean","array","object"]);function paramSchema(param){const declared=param.type;const schema={};if(typeof declared==="string"&&SIMPLE_TYPES.has(declared)&&declared!=="integer"&&declared!=="number"){schema.type=declared}if(param.
|
|
209
232
|
description!==void 0&¶m.description!=="")schema.description=param.description;return schema}function inputSchemaOf(op){const properties={};const required=[];for(const param of op.pathParams){properties[param.name]={description:param.description||`path parameter ${param.name}`};required.push(param.name)}for(const param of op.queryParams){if(Object.hasOwn(properties,param.name))continue;properties[param.name]=paramSchema(param);if(param.required)required.push(param.name)}if(op.body!==null&&op.
|
|
210
233
|
method!=="GET"){properties["body"]={type:"object",description:"JSON request body (see twp_describe_tools for its schema)"}}return{type:"object",properties,...required.length>0?{required}:{},additionalProperties:false}}function catalogTool(op,deps){const name=catalogToolName(op);if(name===null)return null;const summary=op.summary!==""?op.summary:`${op.method} ${op.path}`;const risk=toolRiskOf(op.risk);return{name,domain:op.domain,risk,description:`${summary} (${op.method} ${op.path})`,inputSchema:inputSchemaOf(
|
|
211
|
-
op),preview:input=>previewOf(op,input),run:async input=>runOperation(op,name,input,deps)}}function previewOf(op,input){let
|
|
212
|
-
const raw=input[param.name];const value=typeof raw==="number"?String(raw):raw;if(!isSafePathSegment(value)){errors.push(`${param.name}: \u30D1\u30B9\u8981\u7D20\u3068\u3057\u3066\u4F7F\u3048\u306A\u3044\u5024\u3067\u3059`);continue}
|
|
213
|
-
op.method!=="GET")errors.push(...validateBody(op.body.schema,body??{}));if(errors.length>0)return{ok:false,errors};return{ok:true,path:
|
|
234
|
+
op),preview:input=>previewOf(op,input),run:async input=>runOperation(op,name,input,deps)}}function previewOf(op,input){let path9=op.path;for(const param of op.pathParams){const value=input[param.name];path9=path9.split(`{${param.name}}`).join(typeof value==="string"||typeof value==="number"?String(value):`{${param.name}}`)}return`${op.method} ${path9}`}function buildRequest(op,input){const errors=[];let path9=op.path;const pathNames=new Set;for(const param of op.pathParams){pathNames.add(param.name);
|
|
235
|
+
const raw=input[param.name];const value=typeof raw==="number"?String(raw):raw;if(!isSafePathSegment(value)){errors.push(`${param.name}: \u30D1\u30B9\u8981\u7D20\u3068\u3057\u3066\u4F7F\u3048\u306A\u3044\u5024\u3067\u3059`);continue}path9=path9.split(`{${param.name}}`).join(value)}const query={};for(const[key,value]of Object.entries(input)){if(pathNames.has(key)||key==="body")continue;query[key]=value}const body=input["body"];errors.push(...validateQuery(op.queryParams,query));if(op.body!==null&&
|
|
236
|
+
op.method!=="GET")errors.push(...validateBody(op.body.schema,body??{}));if(errors.length>0)return{ok:false,errors};return{ok:true,path:path9.toLowerCase().startsWith("/api/")?path9:`/api${path9}`,query,body}}async function runOperation(op,name,input,deps){const built=buildRequest(op,input);if(!built.ok){const shown=built.errors.slice(0,MAX_REPORTED_VIOLATIONS);return{content:`Invalid input for ${name}:
|
|
214
237
|
- ${shown.join("\n- ")}`,isError:true,summary:`${name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}let response;try{response=await deps.client().request(op.method,appendQuery(built.path,built.query),built.body)}catch(err){if(err instanceof ApiError){return{content:`${name} failed: ${err.message}`,isError:true,summary:`${name} \xB7 HTTP ${err.status}`}}throw err}return{content:truncate(redactSecrets(JSON.stringify(redactSecretValues(response??null),null,1))),summary:previewOf(op,input)}}function truncate(text,limit=MAX_RESULT_CHARS){
|
|
215
238
|
if(text.length<=limit)return text;return`${text.slice(0,limit)}
|
|
216
|
-
\u2026(truncated: ${text.length-limit} more characters. Narrow the request with query parameters such as limit / keyword.)`}var SEARCH_LIMIT=20;var DESCRIBE_LIMIT=10;var MOUNT_LIMIT=12;var bundledSource={index:loadCommandModelIndex,domain:loadCommandModelDomain};var TwpToolkit=class{source;client;tools=new Map;operations=new Map;loadedDomains=new Set;mountedNames=[];usage=new Map;meta;constructor(opts){this.source=opts.source??bundledSource;this.client=opts.client;this.meta=[this.domainsTool(),this.searchTool(),this.describeTool(),this.callTool(),this.mountTool()]}
|
|
217
|
-
mountedNames.flatMap(name=>{const tool=this.tools.get(name);return tool?[tool]:[]})}resolveTool=name=>this.tools.get(name);prepareIndirect=async input=>{const name=input["name"]??input["tool"];if(typeof name!=="string")return;await this.ensureLoaded(
|
|
218
|
-
const file=await this.source.domain(domain);if(!this.loadedDomains.has(domain)){for(const op of file.operations){const tool=catalogTool(op,{client:this.client});if(tool===null||this.tools.has(tool.name))continue;const run=tool.
|
|
219
|
-
domains.map(d=>this.loadDomain(d.domain).catch(()=>[])))}domainsTool(){return{name:"twp_domains",domain:"meta",risk:"read",description:"List TWP API domains (tasks, projects, attendance, sales, ...) with operation counts.
|
|
220
|
-
)${d.summary!==""?`: ${d.summary}`:""}`);return{content:`${index.totals.domains} domains / ${index.totals.operations} operations
|
|
239
|
+
\u2026(truncated: ${text.length-limit} more characters. Narrow the request with query parameters such as limit / keyword.)`}var SEARCH_LIMIT=20;var DESCRIBE_LIMIT=10;var MOUNT_LIMIT=12;var bundledSource={index:loadCommandModelIndex,domain:loadCommandModelDomain};var TwpToolkit=class{source;client;tools=new Map;operations=new Map;loadedDomains=new Set;mountedNames=[];usage=new Map;meta;catalog;constructor(opts){this.catalog=opts.catalog;this.source=opts.catalog?.reader??opts.source??bundledSource;this.client=opts.client;this.meta=[this.domainsTool(),this.searchTool(),this.describeTool(),this.callTool(),this.mountTool()]}refreshCatalog(){
|
|
240
|
+
return this.catalog?this.catalog.reader.refresh(this.catalog.get):Promise.resolve(null)}cancelCatalogRefresh(){this.catalog?.cancel()}catalogStatus(){return this.catalog?.reader.status()??null}metaTools(){return[...this.meta]}mountedTools(){return this.mountedNames.flatMap(name=>{const tool=this.tools.get(name);return tool?[tool]:[]})}resolveTool=name=>this.tools.get(name);prepareIndirect=async input=>{const name=input["name"]??input["tool"];if(typeof name!=="string")return;await this.ensureLoaded(
|
|
241
|
+
name).catch(()=>void 0)};recordUse(name){this.usage.set(name,(this.usage.get(name)??0)+1)}async ensureLoaded(name){const parsed=parseCatalogToolName(name);if(parsed===null)return void 0;await this.loadDomain(parsed.domain);return this.tools.get(name)}async loadDomain(domain){const file=await this.source.domain(domain);if(!this.loadedDomains.has(domain)){for(const op of file.operations){const tool=catalogTool(op,{client:this.client});if(tool===null||this.tools.has(tool.name))continue;const run=tool.
|
|
242
|
+
run;this.tools.set(tool.name,{...tool,run:async(input,ctx)=>{this.recordUse(tool.name);return run(input,ctx)}});this.operations.set(tool.name,op)}this.loadedDomains.add(domain)}return file.operations}async loadAll(){const index=await this.source.index();await Promise.all(index.domains.map(d=>this.loadDomain(d.domain).catch(()=>[])))}domainsTool(){return{name:"twp_domains",domain:"meta",risk:"read",description:"List TWP API domains (tasks, projects, attendance, sales, ...) with operation counts. \
|
|
243
|
+
Use twp_search_tools to find a specific operation.",inputSchema:{type:"object",properties:{},additionalProperties:false},preview:()=>"twp_domains",run:async()=>guarded(async()=>{const index=await this.source.index();const lines=index.domains.map(d=>`${d.domain} (${d.operationCount})${d.summary!==""?`: ${d.summary}`:""}`);return{content:`${index.totals.domains} domains / ${index.totals.operations} operations
|
|
221
244
|
${lines.join("\n")}`}})}}searchTool(){return{name:"twp_search_tools",domain:"meta",risk:"read",description:"Search the TWP API tool catalog. Returns tool names with a one-line summary only (no schema). Query words match tool name, domain, path and summary (Japanese summaries are common, so Japanese keywords work). Then call twp_describe_tools for the schema and twp_call to run it.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Space separated keywords"},domain:{type:"s\
|
|
222
245
|
tring",description:"Limit the search to one domain (see twp_domains)"}},required:["query"],additionalProperties:false},preview:input=>`twp_search_tools ${String(input["query"]??"")}`,run:async input=>guarded(async()=>{const domain=typeof input["domain"]==="string"&&input["domain"]!==""?input["domain"]:null;if(domain!==null)await this.loadDomain(domain);else await this.loadAll();const all=searchCatalog([...this.operations.entries()],String(input["query"]??""),domain,Number.POSITIVE_INFINITY);if(all.
|
|
223
246
|
length===0)return{content:"No matching tools. Try other keywords or twp_domains."};const hits=all.slice(0,SEARCH_LIMIT);const lines=hits.map(({name,op})=>`${name} [${op.risk}] ${op.summary||`${op.method} ${op.path}`}`);if(all.length>hits.length)lines.push(`(${all.length-hits.length} more matches; narrow the query or pass domain)`);return{content:lines.join("\n")}})}}describeTool(){return{name:"twp_describe_tools",domain:"meta",risk:"read",description:`Return the full JSON Schema of the named TWP\
|
|
@@ -229,4 +252,6 @@ name);if(!tool)return{content:`Unknown tool: ${name}. Use twp_search_tools.`,isE
|
|
|
229
252
|
- ${validated.errors.join("\n- ")}`,isError:true,summary:`${name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}return tool.run(validated.value,ctx)})}}mountTool(){return{name:"twp_mount",domain:"meta",risk:"read",description:`Add up to ${MOUNT_LIMIT} main tools of a TWP domain to your tool list from the next turn on (sticky for this session). Use it when you will call the same domain repeatedly; otherwise twp_call is enough.`,inputSchema:{type:"object",properties:{domain:{type:"string"}},required:["dom\
|
|
230
253
|
ain"],additionalProperties:false},preview:input=>`twp_mount ${String(input["domain"]??"")}`,run:async input=>guarded(async()=>{const domain=String(input["domain"]);const ops=await this.loadDomain(domain);const picked=pickMainOperations(ops).map(op=>catalogToolName(op)).filter(name=>name!==null&&this.tools.has(name));for(const name of picked)if(!this.mountedNames.includes(name))this.mountedNames.push(name);return{content:`Mounted from the next turn: ${picked.join(", ")||"(none)"}`}})}}};function pickMainOperations(ops){
|
|
231
254
|
const order={read:0,write:1,destructive:2};return[...ops].sort((a,b)=>order[a.risk]-order[b.risk]).slice(0,MOUNT_LIMIT)}function searchCatalog(entries,query,domain,limit=SEARCH_LIMIT){const words=query.toLowerCase().split(/\s+/).filter(w=>w!=="");if(words.length===0)return[];const hits=[];for(const[name,op]of entries){if(domain!==null&&op.domain!==domain)continue;const haystack=`${name} ${op.domain} ${op.path} ${op.summary} ${op.aliases.join(" ")}`.toLowerCase();let score=0;for(const word of words)
|
|
232
|
-
if(haystack.includes(word))score+=op.summary.toLowerCase().includes(word)?2:1;if(score>0)hits.push({name,op,score})}return hits.sort((a,b)=>b.score-a.score||a.name.localeCompare(b.name)).slice(0,limit)}async function guarded(fn){try{return await fn()}catch(err){if(err instanceof CommandModelMissingError)return{content:err.message,isError:true};throw err}}function safe(fn,fallback){try{return fn()}catch{return fallback}}function createTwpToolkit(runtime,cliVersion){let
|
|
255
|
+
if(haystack.includes(word))score+=op.summary.toLowerCase().includes(word)?2:1;if(score>0)hits.push({name,op,score})}return hits.sort((a,b)=>b.score-a.score||a.name.localeCompare(b.name)).slice(0,limit)}async function guarded(fn){try{return await fn()}catch(err){if(err instanceof CommandModelMissingError)return{content:err.message,isError:true};throw err}}function safe(fn,fallback){try{return fn()}catch{return fallback}}function createTwpToolkit(runtime,cliVersion,fetchImpl=httpFetch){let session=null;const sharedSession=()=>session??=runtime.session??new AuthSession(runtime.profileName,runtime.apiUrl);let client=null;const abort=new AbortController;const get=(path9,query)=>new TwpApiClient(runtime.apiUrl,sharedSession(),withSignal(fetchImpl,()=>AbortSignal.any([abort.signal,AbortSignal.timeout(CATALOG_FETCH_TIMEOUT_MS)])),cliVersion).get(path9,query);const account=()=>{try{const creds=sharedSession().loadOrThrow();
|
|
256
|
+
return`${creds.tenant_code??""}:${creds.user?.id??""}`}catch{return null}};return new TwpToolkit({client:()=>{client??=new TwpApiClient(runtime.apiUrl,sharedSession(),fetchImpl,cliVersion);return client},catalog:{reader:new ToolCatalog({profile:runtime.profileName,apiUrl:runtime.apiUrl,account}),get,cancel:()=>abort.abort()}})}var CATALOG_FETCH_TIMEOUT_MS=2e4;function withSignal(fetchImpl,signal){return(input,init)=>fetchImpl(input,{...init,signal:signal()})}function residentInputs(toolkit,local=localTools()){
|
|
257
|
+
const meta=toolkit.metaTools();return{tools:[...local,...meta,...toolkit.mountedTools()],usage:toolkit.usage,pinned:new Set([...local,...meta].map(t=>t.name))}}export{secretReason,parseRule,projectPermissionsPath,projectRootFor,persistProjectAllow,activatePermissionSettings,executeTool,buildSystemPrompt,runTurn,parseFrontMatter,lstatOrNull,findProjectTwpSubdir,activateModeFiles,describeAuditLog,createAuditLogger,currentBranch,displayCwd,resolveGitExecutable,readFileTool,RESIDENT_TOKEN_CAP,localTools,buildResidentSet,describeToolCatalog,createTwpToolkit,residentInputs};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{PRIVATE_PROJECT_REF,isPrivateProjectRef}from"./chunk-GY7KI5E5.js";import{
|
|
3
|
+
import{PRIVATE_PROJECT_REF,isPrivateProjectRef}from"./chunk-GY7KI5E5.js";import{isSafePathSegment,safeProjectIdPolicy}from"./chunk-GMBJTG6A.js";import{requireResolved,singleRef,withResolved}from"./chunk-ZN5EFDH7.js";import{PRIVATE_TASK_KEY_PREFIX,isPrivateTaskKey,isTaskKey}from"./chunk-II5RVJQN.js";import{checkUploadQuota}from"./chunk-DDKZ5IPT.js";import{isRecord,pick}from"./chunk-ZWVYVS2A.js";import{ApiResponseError,UsageError}from"./chunk-7WSNIXTQ.js";function classifyTaskRef(ref){const value=ref.trim();if(safeProjectIdPolicy.isDirectId(value))return{kind:"id",value};if(isTaskKey(value))return{kind:"key",value};return{kind:"unknown",value}}function wantsPrivateSurface(input){const project=input.flags.get("--project");return project!==void 0&&isPrivateProjectRef(project)}function taskSurface(input,ref){const project=input.flags.get("--project");const{kind,value}=classifyTaskRef(ref);if(project!==void 0&&isPrivateProjectRef(project)){if(kind===
|
|
4
4
|
"key"&&!isPrivateTaskKey(value)){throw new UsageError(`--project ${PRIVATE_PROJECT_REF}\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\uFF09\u306B ${value} \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u306F ${PRIVATE_TASK_KEY_PREFIX}-<\u756A\u53F7> \u306E\u5F62\u3067\u3059\u3002ID\uFF08UUID / ULID\uFF09\u3067\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002
|
|
5
5
|
\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3092\u6307\u3059\u306A\u3089 --project ${PRIVATE_PROJECT_REF} \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return"private"}if(kind==="key"&&isPrivateTaskKey(value)&&project===void 0){throw new UsageError(`${value} \u306F\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u306B\u3082\u3001\u30B3\u30FC\u30C9 ${PRIVATE_TASK_KEY_PREFIX} \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u30AD\u30FC\u306B\u3082\u8AAD\u3081\u307E\u3059`,
|
|
6
6
|
`\u3069\u3061\u3089\u3092\u6307\u3059\u304B --project \u3067\u9078\u3093\u3067\u304F\u3060\u3055\u3044\u3002
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{
|
|
3
|
+
import{ResolveError,UUID_RE,isSafePathSegment,resolveProjectRef,safeProjectIdPolicy}from"./chunk-GMBJTG6A.js";import{ApiError}from"./chunk-FTYJZFEK.js";import{isTaskKey}from"./chunk-II5RVJQN.js";import{loadProjectConfig,loadUserConfig}from"./chunk-NERYSBA4.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{UsageError}from"./chunk-7WSNIXTQ.js";var BACKLOG_BASE_PATH="/api/v2/integrations/backlog";function assertBacklogPathSegment(value,label){if(!isSafePathSegment(value)){throw new ResolveError(`${label}\u3068\u3057\u3066 URL \u306B\u5165\u308C\u3089\u308C\u306A\u3044\u5024\u304C\u30B5\u30FC\u30D0\u304B\u3089\u8FD4\u308A\u307E\u3057\u305F: ${JSON.stringify(value)}\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return value}function backlogSpacePath(spaceId,suffix=""){assertBacklogPathSegment(spaceId,
|
|
4
4
|
"Backlog \u30B9\u30DA\u30FC\u30B9 ID");return`${BACKLOG_BASE_PATH}/${encodeURIComponent(spaceId)}${suffix}`}function idString(value){if(typeof value==="number"&&Number.isFinite(value))return String(value);if(typeof value==="string"&&value.trim()!=="")return value.trim();return null}function text(value){return typeof value==="string"&&value.trim()!==""?value.trim():null}function backlogSpaceAliases(spaceUrl){const aliases=[];const trimmed=spaceUrl.trim().replace(/\/+$/,"");if(trimmed==="")return aliases;
|
|
5
5
|
let host;try{host=new URL(trimmed).host}catch{host=trimmed.replace(/^\/+/,"").split("/")[0]??""}if(host==="")return aliases;aliases.push(host);const label=host.split(".")[0];if(label!==void 0&&label!==""&&label!==host)aliases.push(label);return aliases}function backlogSpaceRow(row){const url=text(row["space_url"]);return{id:idString(row["id"]),name:url,code:null,aliases:url!==null?backlogSpaceAliases(url):[]}}function backlogProjectRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:text(
|
|
6
6
|
row["projectKey"])}}function backlogStatusRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:null}}function backlogUserRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:null,aliases:[text(row["userId"]),text(row["mailAddress"])].filter(v=>v!==null)}}var DEFAULT_LOOKUP_SCOPE="\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8";function fold(value){return value.trim().toLowerCase()}function keysOf(ref){return[ref.id,ref.code,ref.name,...ref.aliases??[]].filter(v=>typeof v==="string"&&v.trim()!=="").map(fold)}function describe(ref){return ref.code!==void 0&&ref.code!==null&&ref.code!==""&&ref.code!==ref.name?`${ref.name}\uFF08${ref.code}\uFF09`:ref.name}async function suggest(input,candidates){try{const{default:fuzzysort}=await import("./fuzzysort-DFVKV4B4.js");
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{buildDiffLines,diffStat}from"./chunk-VRBI2NPI.js";import{EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH}from"./chunk-7WSNIXTQ.js";import*as fs from"fs";function readUtf8Strict(p){return new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(fs.readFileSync(p))}function apiExit(res){if(res.status===401)return EXIT_AUTH;if(res.status!==null&&res.status>=400&&res.status<500)return EXIT_API_CLIENT;return EXIT_API_SERVER}function pickNumber(b,key){const v=b[key];return typeof v==="number"&&Number.isInteger(v)&&v>=0?v:null}function str(v){return typeof v==="string"?v:""}function currentRevisionOf(res){const json=res.json??{};const data=json["dat\
|
|
4
|
+
a"]&&typeof json["data"]==="object"?json["data"]:{};return pickNumber(json,"current_revision")??pickNumber(data,"current_revision")}function errorDetail(res){if(res.status===null)return`transport_error=${res.transportError??"\u4E0D\u660E"}`;const json=res.json??{};const data=json["data"]&&typeof json["data"]==="object"?json["data"]:{};const errorField=json["error"];const errorObj=errorField&&typeof errorField==="object"?errorField:{};const reason=(typeof errorField==="string"?errorField:"")||str(
|
|
5
|
+
errorObj["code"])||str(json["reason"])||str(data["reason"]);const message=str(json["error_description"])||str(errorObj["message"])||str(json["message"])||str(data["message"]);const parts=[`http=${res.status}`];if(reason)parts.push(`reason=${reason}`);if(message)parts.push(message.slice(0,300));const errors=json["errors"]??data["errors"]??json["error_list"];if(errors&&typeof errors==="object")parts.push(JSON.stringify(errors).slice(0,300));if(!reason&&!message)parts.push(`\u5FDC\u7B54\u306E\u5148\u982D: ${res.
|
|
6
|
+
raw.slice(0,160)}`);return parts.join(" ")}var HIDDEN_CHARS=/[\x00-\x08\x0B-\x1F\x7F-\x9F\u00AD\u061C\u180E\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF\uFFF9-\uFFFB\u{E0000}-\u{E007F}\u{E0100}-\u{E01EF}]/gu;function printDiff(out,fromLabel,toLabel,before,after){const lines=buildDiffLines(before,after);const{added,removed}=diffStat(lines);out(`--- ${fromLabel}
|
|
7
|
+
+++ ${toLabel}
|
|
8
|
+
`);for(const l of lines)out(`${l.sign} ${l.text}
|
|
9
|
+
`);out(`\uFF08+${added} / -${removed} \u884C\uFF09
|
|
10
|
+
`);if(before!==after&&before.replace(/\n$/,"")===after.replace(/\n$/,"")){out(`\uFF08\u9055\u3044\u306F\u672B\u5C3E\u306E\u6539\u884C\u306E\u6709\u7121\u3060\u3051\u3067\u3059: ${after.endsWith("\n")?"\u6539\u884C\u3092\u8DB3\u3059":"\u6539\u884C\u3092\u6D88\u3059"}\uFF09
|
|
11
|
+
`)}warnHiddenChars(out,after)}function warnHiddenChars(out,content,label){const hidden=(content.match(HIDDEN_CHARS)??[]).length;if(hidden>0){out(`\u26A0\uFE0F ${label!==void 0?`${label}: `:""}\u66F8\u304D\u8FBC\u307E\u308C\u308B\u5185\u5BB9\u306B\u3001\u5DEE\u5206\u8868\u793A\u3067\u306F\u898B\u3048\u306A\u3044\u6587\u5B57\uFF08\u5236\u5FA1\u6587\u5B57\u30FBCR\u30FB\u53CC\u65B9\u5411\u5236\u5FA1\u30FB\u30BC\u30ED\u5E45\u30FB\u30BF\u30B0\u6587\u5B57\u7B49\uFF09\u304C ${hidden} \u7B87\u6240\u3042\u308A\u307E\u3059\u3002\u78BA\u5B9A\u3059\u308B\u524D\u306B\u5185\u5BB9\u3092\u78BA\u8A8D\u3057\
|
|
12
|
+
\u3066\u304F\u3060\u3055\u3044
|
|
13
|
+
`)}}function shellQuote(v){return/^[A-Za-z0-9_./:@=-]+$/.test(v)?v:`'${v.replace(/'/g,`'\\''`)}'`}export{readUtf8Strict,apiExit,pickNumber,str,currentRevisionOf,errorDetail,printDiff,warnHiddenChars,shellQuote};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{createRuntime}from"./chunk-
|
|
3
|
+
import{createRuntime}from"./chunk-Z2MNO3FT.js";import{findExecutable}from"./chunk-PMOUHEJQ.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{describeAutoUpdate}from"./chunk-ILKQDXI5.js";import{PACKAGE_NAME,UPDATE_COMMAND,compareVersionCores,isBelowMinSupported,parseVersionCore}from"./chunk-DXXFUNYN.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{execFile}from"child_process";import fs from"fs";import path from"path";function resolveNpmCommand(deps={}){const platform=deps.platform??process.platform;const env=deps.env??process.env;const npmPath=(deps.find??(name=>findExecutable(name,{env,platform})))("npm");if(npmPath===null)return null;if(platform!=="win32")return{file:npmPath,prefix:[]};if(/\.exe$/i.test(npmPath))return{file:npmPath,prefix:[]};const cliJs=path.win32.join(path.win32.dirname(npmPath),"node_modules","npm","bin","npm-cli.js");return(deps.exists??fs.existsSync)(cliJs)?{file:deps.nodePath??process.
|
|
4
4
|
execPath,prefix:[cliJs]}:null}var DEFAULT_REGISTRY="https://registry.npmjs.org";function registryBase(env=process.env){const configured=env["npm_config_registry"]?.trim();if(configured===void 0||configured==="")return DEFAULT_REGISTRY;try{const url=new URL(configured);if(url.protocol!=="https:"&&url.protocol!=="http:")return DEFAULT_REGISTRY}catch{return DEFAULT_REGISTRY}return configured.replace(/\/+$/,"")}async function fetchFromRegistry(fetchImpl=httpFetch,env=process.env){const url=`${registryBase(env)}/${PACKAGE_NAME.replace(
|
|
5
5
|
"/","%2f")}`;const res=await fetchImpl(url,{headers:{Accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(5e3)});if(!res.ok){throw new Error(`registry \u304C ${res.status} \u3092\u8FD4\u3057\u307E\u3057\u305F`)}const body=await res.json();const latest=body["dist-tags"]?.latest;if(typeof latest!=="string"||parseVersionCore(latest)===null){throw new Error("registry \u306E\u5FDC\u7B54\u306B dist-tags.latest \u304C\u3042\u308A\u307E\u305B\u3093")}return{version:latest.trim(),source:"\
|
|
6
6
|
registry"}}async function fetchFromNpmCli(){const npm=resolveNpmCommand();if(npm===null){throw new Error("npm \u304C PATH \u306B\u898B\u3064\u304B\u308A\u307E\u305B\u3093")}const stdout=await new Promise((resolve,reject)=>{execFile(npm.file,[...npm.prefix,"view",PACKAGE_NAME,"version","--json"],{timeout:15e3,windowsHide:true},(error,out)=>error?reject(error):resolve(out))});const parsed=JSON.parse(stdout.trim());const latest=typeof parsed==="string"?parsed:null;if(latest===null||parseVersionCore(
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
var DOMAIN_NAMES=["agent-loop","attendance","backlog","department","job-title","media","position","project","storage","task","user"];function isDomainName(value){return value!==void 0&&DOMAIN_NAMES.includes(value)}var HELP_TOKEN="help";var API_TOKEN="api";export{isDomainName,HELP_TOKEN,API_TOKEN};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{UsageError}from"./chunk-7WSNIXTQ.js";var ISO_DATE_RE=/^\d{4}-\d{2}-\d{2}$/;function isoDate(input,flag){const raw=input.flags.get(flag);if(raw===void 0)return void 0;return isoDateValue(raw,flag)}function isoDateValue(raw,label){const value=raw.trim();if(!ISO_DATE_RE.test(value)){throw new UsageError(`${label} \u306F YYYY-MM-DD \u306E\u5F62\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${raw}`,"\u4F8B: 2026-09-30")}const[y,m,d]=value.split("-").map(Number);const probe=new Date(Date.UTC(y,m-1,d));if(probe.getUTCFullYear()!==
|
|
4
|
+
y||probe.getUTCMonth()+1!==m||probe.getUTCDate()!==d){throw new UsageError(`${label} \u306B\u5B58\u5728\u3057\u306A\u3044\u65E5\u4ED8\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059: ${raw}`,"\u4F8B: 2026-09-30")}return value}function booleanText(flag,raw){const value=raw.trim().toLowerCase();if(value==="true")return true;if(value==="false")return false;throw new UsageError(`${flag} \u306F true \u304B false \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${raw}`,`\u4F8B: ${flag} fa\
|
|
5
|
+
lse`)}function priority(input,flag="--priority"){const raw=input.flags.get(flag);if(raw===void 0)return void 0;const trimmed=raw.trim();const value=/^\d+$/.test(trimmed)?Number(trimmed):Number.NaN;if(!Number.isInteger(value)||value<1||value>3){throw new UsageError(`${flag} \u306F 1 / 2 / 3 \u306E\u3044\u305A\u308C\u304B\u3067\u3059: ${raw}`,"1: \u9AD8 \uFF0F 2: \u4E2D \uFF0F 3: \u4F4E")}return value}function decimal(input,flag,options){const raw=input.flags.get(flag);if(raw===void 0)return void 0;
|
|
6
|
+
const trimmed=raw.trim();const value=/^\d+(\.\d+)?$/.test(trimmed)?Number(trimmed):Number.NaN;if(!Number.isFinite(value)||value<options.min||value>options.max){throw new UsageError(`${flag} \u306F ${options.min} \u4EE5\u4E0A ${options.max} \u4EE5\u4E0B\u306E\u6570\u5024\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${raw}`,"\u4F8B: 3 / 3.5")}return value}function boundedText(input,flag,options){const raw=input.flags.get(flag);if(raw===void 0)return void 0;if(raw.trim()===""){throw new UsageError(
|
|
7
|
+
`${flag} \u306B\u7A7A\u306E\u5024\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`${options.label}\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}const count=[...raw].length;if(count>options.maxChars){throw new UsageError(`${options.label}\u304C\u9577\u3059\u304E\u307E\u3059\uFF08${count} \u6587\u5B57\u30FB\u4E0A\u9650 ${options.maxChars} \u6587\u5B57\uFF09`,`${flag} \u3092 ${options.maxChars} \u6587\u5B57\u4EE5\u5185\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return raw}export{isoDate,isoDateValue,booleanText,priority,decimal,boundedText};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{extractLeadingTaskKey}from"./chunk-II5RVJQN.js";var LEDGER_TASK_KEY_MAX=50;var CONTROL_CHAR_RE=/[\u0000-\u001f\u007f]/;var FLAG_TOKEN_RE=/(?:^|\s)-/;function loosen(source){let t=source.replace(/^[ \t]*\/\/[^\n]*$/gm,"");t=t.replace(/\/\*[\s\S]*?\*\//g,"");t=t.replace(/,(\s*[}\]])/g,"$1");return t===source?null:t}function tryParsePlan(source){for(const candidate of[source,loosen(source)]){if(candidate===null)continue;try{const obj=JSON.parse(candidate);if(obj!==null&&typeof obj==="object"&&Array.isArray(obj.steps)){return obj}}catch{}}return null}
|
|
4
|
+
function fencedBlocks(text,tag){const re=new RegExp("```"+tag+"\\s*\\n([\\s\\S]*?)\\n```","g");const out=[];for(const m of text.matchAll(re)){if(m[1]!==void 0)out.push(m[1])}return out}function extractGeminiEnvelope(text){const anchor=/\{[^{}]*"session_id"[^{}]*"response"\s*:\s*"/g;for(const m of text.matchAll(anchor)){const start=m.index;if(start===void 0)continue;let depth=0;let inStr=false;let escape=false;for(let i=start;i<text.length;i++){const c=text[i];if(escape){escape=false;continue}if(c===
|
|
5
|
+
"\\"){escape=true;continue}if(c==='"'){inStr=!inStr;continue}if(inStr)continue;if(c==="{")depth++;else if(c==="}"){depth--;if(depth===0){try{const obj=JSON.parse(text.slice(start,i+1));if(obj!==null&&typeof obj==="object"&&typeof obj.response==="string"){return obj.response}}catch{}break}}}}return null}function extractPlanJson(rawText){const text=rawText.replace(/^\s*\[\d{2}:\d{2}:\d{2}\]\s*/gm,"");for(const tag of["json:execution-plan","json"]){for(const block of fencedBlocks(text,tag).reverse()){
|
|
6
|
+
const plan=tryParsePlan(block);if(plan)return plan}}const resp=extractGeminiEnvelope(text);if(resp!==null){for(const block of[...fencedBlocks(resp,"json:execution-plan"),...fencedBlocks(resp,"json")].reverse()){const plan2=tryParsePlan(block);if(plan2)return plan2}const plan=tryParsePlan(resp);if(plan)return plan}const whole=tryParsePlan(text.trim());if(whole)return whole;for(const m of[...text.matchAll(/\{[^{}]*"steps"[^{}]*\[[\s\S]*?\][\s\S]*?\}/g)].reverse()){const plan=tryParsePlan(m[0]);if(plan)
|
|
7
|
+
return plan}return null}function ledgerTaskKey(args){const key=extractLeadingTaskKey(args);if(key.length>LEDGER_TASK_KEY_MAX)return"";if(CONTROL_CHAR_RE.test(key))return"";if(FLAG_TOKEN_RE.test(key))return"";return key}function placeholderTaskKey(args){for(const token of args.split(/\s+/)){if(token==="")continue;if(token.startsWith("-"))continue;const m=/^[A-Z]{2,}[A-Z0-9]*-([A-Za-z0-9_<>{}]*)$/.exec(token);if(!m)return null;if(/^\d+$/.test(m[1]??""))return null;return token}return null}function stepToItem(step,assign){
|
|
8
|
+
const skill=typeof step.skill==="string"?step.skill.trim():"";if(!skill)return null;const args=(step.args??"").trim();const priority=step.priority??"P2";const prompt=`/twp-${skill}${args?` ${args}`:""}`;let label=(step.label??"").trim();if(!label||label.startsWith("/twp-")||label.startsWith("[P"))label=prompt;const taskKey=ledgerTaskKey(args);const category=assign?.categoryForSkill(skill)??step.ai_category??"complex";const display=taskKey&&!label.includes(taskKey)?`[${priority}] ${taskKey} ${label}\
|
|
9
|
+
#ai:${category}`:`[${priority}] ${label} #ai:${category}`;const item={label:display.slice(0,200),prompt,task_key:taskKey};if(assign!==void 0){const ai=assign.selectPrimary(category,skill,priority,display);if(ai!=="")item.ai_type=ai}return item}function parsePlanExcludeKeys(prefetchSection){const m=/OPS_PLAN_EXCLUDE_KEYS\s+([^\s]*)\s+-->/.exec(prefetchSection);const keys=new Set;if(!m||!m[1])return keys;for(const raw of m[1].split(",")){const key=raw.trim();if(key!=="")keys.add(key)}return keys}
|
|
10
|
+
function excludedKeyInArgs(args,excluded){if(excluded.size===0)return null;for(const key of[...excluded].sort()){const re=new RegExp(`(?<![A-Za-z0-9-])${key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![0-9])`);if(re.test(args))return key}return null}function parseOpsCount(prefetchSection,field){const marker=/OPS_COUNTS\s+([^>]*?)-->/.exec(prefetchSection);if(!marker||!marker[1])return null;const escaped=field.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const hit=new RegExp(`(?:^|\\s)${escaped}=(-?\\d+)(?:\
|
|
11
|
+
\\s|$)`).exec(marker[1]);if(!hit||hit[1]===void 0)return null;const n=Number.parseInt(hit[1],10);if(!Number.isFinite(n)||n<0)return null;return n}function releaseDeployDropReason(verifyBacklog,devVerifyPlanned){if(verifyBacklog===null){return"\u52D5\u4F5C\u78BA\u8A8D\u306E\u4EF6\u6570\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\uFF08\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u30EA\u30EA\u30FC\u30B9\u306F\u898B\u9001\u308B\uFF09"}if(verifyBacklog>devVerifyPlanned){return`\u52D5\u4F5C\u78BA\u8A8D${verifyBacklog}\
|
|
12
|
+
\u4EF6 > \u8A08\u753B\u5185dev-verify${devVerifyPlanned}\u4EF6\uFF08Phase 1\u306E0\u4EF6\u898B\u8FBC\u307F\u304C\u7ACB\u305F\u306A\u3044\uFF09`}return null}function duplicateTaskKeyDropReason(enqueuedKeys,taskKey){if(!taskKey)return null;if(!enqueuedKeys.has(taskKey))return null;return`${taskKey} \u306F\u672C\u8A08\u753B\u3067\u65E2\u306B\u6295\u5165\u6E08\u307F\uFF08\u540C\u4E00\u30AD\u30FC\u306F1\u8A08\u753B1\u4EF6\uFF09`}var NO_ZERO_TARGET_GATES={};function zeroTargetDropReasons(prefetchSection,gates=NO_ZERO_TARGET_GATES){
|
|
13
|
+
const reasons=new Map;for(const[skill,gate]of Object.entries(gates)){const n=parseOpsCount(prefetchSection,gate.field);if(n===null)reasons.set(skill,`${gate.label}\u4EF6\u6570\u304C\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u898B\u9001\u308A`);else if(n===0)reasons.set(skill,`${gate.label}0\u4EF6\u306E\u305F\u3081\u5BFE\u8C61\u306A\u3057`)}return reasons}export{extractPlanJson,placeholderTaskKey,stepToItem,parsePlanExcludeKeys,excludedKeyInArgs,parseOpsCount,releaseDeployDropReason,duplicateTaskKeyDropReason,zeroTargetDropReasons};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{
|
|
3
|
+
import{DEFAULT_CLAUDE_LAUNCHER,loadAiConfig}from"./chunk-TYNCXQSN.js";import{killProcessTree}from"./chunk-N2UVRM3Z.js";import{projectFileKey}from"./chunk-GY7KI5E5.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{isBoolishTrue}from"./chunk-5WGOHFAS.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){
|
|
@@ -44,19 +44,21 @@ e \u306E\u51FA\u529B\u304C ${probe.format} \u306E\u60F3\u5B9A\u3068\u9055\u3044\
|
|
|
44
44
|
ected_shape")}}var CapacityReporter=class{constructor(probe,cwd,log,env=process.env,now=()=>Date.now()){this.probe=probe;this.cwd=cwd;this.log=log;this.env=env;this.now=now}probe;cwd;log;env;now;cached=null;lastProbedAt=0;pending=false;running=false;async refreshIfDue(){const at=this.now();if(this.cached!==null&&at-this.lastProbedAt<this.probe.interval*1e3)return;await this.refresh()}async refresh(){if(this.running)return;this.running=true;try{this.cached=await probeCapacity(this.probe,this.cwd,
|
|
45
45
|
this.log,this.env);this.lastProbedAt=this.now();this.pending=true}finally{this.running=false}}take(){if(!this.pending||this.cached===null)return null;this.pending=false;return this.cached}rearm(){if(this.cached!==null)this.pending=true}};function evaluateOwnership(item,runnerId,runId){if(!item){return{verdict:"unknown",reason:"\u30A2\u30A4\u30C6\u30E0\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"}}if(runnerId===""||runId===""){return{verdict:"unknown",reason:"\u81EA\u5206\u306E runner_id / run_id \u304C\u7A7A\u3067\u3059"}}const status=(item.status??"").trim();if(status===""){return{verdict:"unknown",reason:"\u5FDC\u7B54\u306B status \u304C\u3042\u308A\u307E\u305B\u3093"}}if(status!=="processing"){return{verdict:"\
|
|
46
46
|
lost",reason:`status=${status}\uFF08processing \u3067\u306F\u3042\u308A\u307E\u305B\u3093\uFF09`}}const itemRunner=(item.runner_id??"").trim();const itemRun=(item.run_id??"").trim();if(itemRunner===""||itemRun===""){return{verdict:"unknown",reason:"\u5FDC\u7B54\u306B runner_id / run_id \u304C\u3042\u308A\u307E\u305B\u3093"}}if(itemRunner!==runnerId){return{verdict:"lost",reason:`\u5225\u306E\u30E9\u30F3\u30CA\u30FC\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08runner=${itemRunner}\uFF09`}}
|
|
47
|
-
if(itemRun!==runId){return{verdict:"lost",reason:`\u540C\u3058\u6A5F\u4F53\u306E\u5225\u306E\u8D77\u52D5\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08run_id \u304C\u4E00\u81F4\u3057\u307E\u305B\u3093\uFF09`}}return{verdict:"held",reason:"processing \u304B\u3064 runner_id / run_id \u304C\u4E00\u81F4"}}var OWNERSHIP_CHECK_INTERVAL_SEC=60;var NO_OPERATIONS={exclusiveSkills:new Set,statusEndpoint:null,highRiskSkills:new Set,preflightHosts:[],releaseRecoverySkill:null,postSuccessEnqueue:new Map,contractSkills:new Set,zeroTargetGates:{}};var DEFAULT_STATUS_PATH="/api/release/list";var DEFAULT_STATUS_HEADER="X-API-Key";function stringArray(value,label,warnings){if(value===void 0||value===null)return[];if(!Array.isArray(value)){warnings.push(`operations.${label} \u306F\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);
|
|
47
|
+
if(itemRun!==runId){return{verdict:"lost",reason:`\u540C\u3058\u6A5F\u4F53\u306E\u5225\u306E\u8D77\u52D5\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08run_id \u304C\u4E00\u81F4\u3057\u307E\u305B\u3093\uFF09`}}return{verdict:"held",reason:"processing \u304B\u3064 runner_id / run_id \u304C\u4E00\u81F4"}}var OWNERSHIP_CHECK_INTERVAL_SEC=60;var NO_OPERATIONS={exclusiveSkills:new Set,statusEndpoint:null,highRiskSkills:new Set,preflightHosts:[],releaseRecoverySkill:null,postSuccessEnqueue:new Map,contractSkills:new Set,zeroTargetGates:{},countHooks:new Map};var DEFAULT_STATUS_PATH="/api/release/list";var DEFAULT_STATUS_HEADER="X-API-Key";function stringArray(value,label,warnings){if(value===void 0||value===null)return[];if(!Array.isArray(value)){warnings.push(`operations.${label} \u306F\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);
|
|
48
48
|
return[]}const out=[];for(const v of value){if(typeof v!=="string"||v.trim()===""){warnings.push(`operations.${label} \u306E\u8981\u7D20\u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u8981\u7D20\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}out.push(v.trim())}return out}function stringMap(value,label,warnings){const out=new Map;if(value===void 0||value===null)return out;if(typeof value!=="object"||Array.isArray(value)){
|
|
49
49
|
warnings.push(`operations.${label} \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);return out}for(const[k,v]of Object.entries(value)){if(typeof v!=="string"||v.trim()===""){warnings.push(`operations.${label}.${k} \u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u9805\u76EE\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}out.set(
|
|
50
50
|
k,v.trim())}return out}function parseZeroTargetGates(value,warnings){const out={};if(value===void 0||value===null)return out;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.zero_target_gates \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return out}for(const[skill,v]of Object.entries(value)){if(typeof v!=="object"||v===null||Array.isArray(v)){warnings.push(`operations.zero_ta\
|
|
51
51
|
rget_gates.${skill} \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}const g=v;const field=typeof g["field"]==="string"?g["field"].trim():"";const label=typeof g["label"]==="string"?g["label"].trim():"";if(field===""||label===""){warnings.push(`operations.zero_target_gates.${skill} \u306B\u306F field \u3068 label \u304C\u8981\u308A\u307E\u3059\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}
|
|
52
|
-
out[skill]={field,label}}return out}function
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if(
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
52
|
+
out[skill]={field,label}}return out}function parseCountHooks(value,warnings){const out=new Map;if(value===void 0||value===null)return out;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.count_hooks \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return out}for(const[key,v]of Object.entries(value)){const entry=v!==null&&typeof v==="object"&&!Array.isArray(v)?{id:`count:${key}`,
|
|
53
|
+
...v}:v;const{hooks,warnings:w}=validateHooks([entry],`operations.count_hooks.${key}`);warnings.push(...w);const hook=hooks[0];if(hook)out.set(key,hook)}return out}function parseEndpoint(value,warnings){if(value===void 0||value===null)return null;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.status_endpoint \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059\uFF09");
|
|
54
|
+
return null}const o=value;const url=typeof o["url"]==="string"?o["url"].trim():"";if(url===""){warnings.push("operations.status_endpoint.url \u304C\u7121\u3044\u305F\u3081\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059");return null}if(!/^https?:\/\//i.test(url)){warnings.push(`operations.status_endpoint.url \u306F http(s) \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${url}\uFF08\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059\uFF09`);return null}const path2=typeof o["pat\
|
|
55
|
+
h"]==="string"&&o["path"].trim()!==""?o["path"].trim():DEFAULT_STATUS_PATH;const apiKeyEnvRaw=o["api_key_env"];const apiKeyEnv=typeof apiKeyEnvRaw==="string"&&apiKeyEnvRaw.trim()!==""?apiKeyEnvRaw.trim():null;const headerRaw=o["header"];const header=typeof headerRaw==="string"&&headerRaw.trim()!==""?headerRaw.trim():DEFAULT_STATUS_HEADER;return{url:url.replace(/\/+$/,""),path:path2.startsWith("/")?path2:`/${path2}`,apiKeyEnv,header}}function parseOperations(value){const warnings=[];if(value===void 0||
|
|
56
|
+
value===null)return{operations:NO_OPERATIONS,warnings};if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return{operations:NO_OPERATIONS,warnings}}const o=value;const exclusiveSkills=new Set(stringArray(o["exclusive_skills"],"exclusive_skills",warnings));const statusEndpoint=parseEndpoint(o["status_endpoint"],warnings);if(exclusiveSkills.
|
|
57
|
+
size>0&&statusEndpoint===null){warnings.push("operations.exclusive_skills \u306F\u3042\u308A\u307E\u3059\u304C status_endpoint \u304C\u7121\u3044\u305F\u3081\u3001\u5B9A\u671F\u67A0\u306E\u6392\u4ED6\u306F\u884C\u3044\u307E\u305B\u3093")}if(exclusiveSkills.size===0&&statusEndpoint!==null){warnings.push("operations.status_endpoint \u306F\u3042\u308A\u307E\u3059\u304C exclusive_skills \u304C\u7A7A\u306E\u305F\u3081\u3001\u554F\u3044\u5408\u308F\u305B\u306F\u884C\u3044\u307E\u305B\u3093")}const releaseRecoveryRaw=o["\
|
|
58
|
+
release_recovery_skill"];const releaseRecoverySkill=typeof releaseRecoveryRaw==="string"&&releaseRecoveryRaw.trim()!==""?releaseRecoveryRaw.trim():null;return{operations:{exclusiveSkills,statusEndpoint,highRiskSkills:new Set(stringArray(o["high_risk_skills"],"high_risk_skills",warnings)),preflightHosts:stringArray(o["preflight_hosts"],"preflight_hosts",warnings),releaseRecoverySkill,postSuccessEnqueue:stringMap(o["post_success_enqueue"],"post_success_enqueue",warnings),contractSkills:new Set(stringArray(
|
|
59
|
+
o["contract_skills"],"contract_skills",warnings)),zeroTargetGates:parseZeroTargetGates(o["zero_target_gates"],warnings),countHooks:parseCountHooks(o["count_hooks"],warnings)},warnings}}function describeOperations(ops){if(ops===NO_OPERATIONS||ops.exclusiveSkills.size===0&&ops.highRiskSkills.size===0){return"\u904B\u7528\u8A2D\u5B9A: \u306A\u3057\uFF08\u30B9\u30AD\u30EB\u540D\u306B\u3088\u308B\u7279\u5225\u6271\u3044\u306F\u884C\u3044\u307E\u305B\u3093\uFF09"}const parts=[];if(ops.exclusiveSkills.
|
|
60
|
+
size>0&&ops.statusEndpoint){parts.push(`\u6392\u4ED6 ${[...ops.exclusiveSkills].join(",")} \u2190 ${ops.statusEndpoint.url}`)}else if(ops.exclusiveSkills.size>0){parts.push(`\u6392\u4ED6 ${[...ops.exclusiveSkills].join(",")}\uFF08\u554F\u3044\u5408\u308F\u305B\u5148\u304C\u7121\u3044\u305F\u3081\u7121\u52B9\uFF09`)}if(ops.highRiskSkills.size>0)parts.push(`\u9AD8\u30EA\u30B9\u30AF ${ops.highRiskSkills.size}\u4EF6`);if(ops.releaseRecoverySkill)parts.push(`\u56DE\u53CE ${ops.releaseRecoverySkill}`);
|
|
61
|
+
return`\u904B\u7528\u8A2D\u5B9A: ${parts.join(" / ")}`}function sanitizeInt(value,fallback,min=1){const n=typeof value==="number"?value:Number.parseInt(String(value??""),10);if(Number.isInteger(n)&&n>=min)return{value:n,warning:null};if(value===void 0||value===null||value==="")return{value:fallback,warning:null};return{value:fallback,warning:`'${String(value)}' \u306F${min}\u4EE5\u4E0A\u306E\u6574\u6570\u3067\u306F\u3042\u308A\u307E\u305B\u3093 \u2192 \u65E2\u5B9A ${fallback} \u3092\u4F7F\u3044\u307E\u3059`}}function nonEmpty(value){const t=value?.trim();
|
|
60
62
|
return t===void 0||t===""?void 0:value}function resolveCharterEnabled(raw,local,warn){return resolveBoolSetting(raw,local,"charter_enabled",true,"\u61B2\u7AE0\u3092\u524D\u7F6E\u3057\u307E\u3059",warn)}function resolveBoolSetting(raw,local,key,fallback,fallbackNote,warn){const v=(raw??"").trim();if(v!=="")return isBoolishTrue(v);if(local===void 0)return fallback;if(typeof local==="boolean")return local;if(typeof local==="string")return isBoolishTrue(local.trim()===""?String(fallback):local);warn(
|
|
61
63
|
`${key} \u306F\u771F\u507D\u5024\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u89E3\u91C8\u3067\u304D\u306A\u3044\u305F\u3081\u3001${fallbackNote}\uFF09`);return fallback}function charterWrapper(raw,local,key,warn){if(raw!==void 0)return raw;if(local===void 0)return null;if(typeof local==="string")return local;warn(`${key} \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u7121\u8996\u3057\u3001\u65E2\u5B9A\u306E\u56F2\u307F\u6587\u3092\u4F7F\u3044\u307E\u3059\uFF09`);
|
|
62
64
|
return null}function loopStateDir(env=process.env){const explicit=env.TWP_OPS_STATE_DIR?.trim();if(explicit)return explicit;return path.join(os.homedir(),".twp-ops")}function releaseOutcomeLogPath(env=process.env){const explicit=env.RELEASE_OUTCOME_LOG?.trim();if(explicit)return explicit;return path.join(loopStateDir(env),"release-outcomes.tsv")}function localConfigPath(projectId,env=process.env){return path.join(twpHomeDir(env),"loops",`${projectFileKey(projectId)}.json`)}function loadLocalConfig(projectId,env=process.
|
|
@@ -75,4 +77,4 @@ env.PLAN_LOCK_RENEW_INTERVAL,Math.trunc(planLockTtlSec/3),1,"PLAN_LOCK_RENEW_INT
|
|
|
75
77
|
"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
78
|
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
79
|
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};
|
|
80
|
+
return fmt.format(now)}export{runHook,runPrefetch,runPreflight,formatHookWiring,formatHookIds,CapacityReporter,parseClaudeLauncher,evaluateOwnership,describeOperations,loopStateDir,localConfigPath,loadLocalConfig,buildLoopConfig,localDate};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{describeError}from"./chunk-
|
|
3
|
+
import{describeError}from"./chunk-BKZGBJWT.js";import{httpFetch}from"./chunk-J7QYPKVK.js";var ScheduleApi=class{constructor(api){this.api=api}api;async definitions(){const res=await this.api.request("GET","/schedules/definitions");if(!res.ok)return fetchError("\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u306E\u5B9A\u7FA9\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093",res);const body=res.json??{};const schedules=body["schedules"];if(!Array.isArray(schedules)){return{kind:"error",message:`\u5B9A\u7FA9\u306E\u5FDC\u7B54\u306B schedules \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.
|
|
4
4
|
raw.slice(0,120)}\uFF09`,status:res.status}}const gates=Array.isArray(body["gates"])?body["gates"]:[];return{kind:"ok",config:{schedules,gates,max_per_cycle:body["max_per_cycle"],warnings:Array.isArray(body["warnings"])?body["warnings"]:[]}}}async history(since){const suffix=since?`/schedules/history?since=${encodeURIComponent(since)}`:"/schedules/history";const res=await this.api.request("GET",suffix);if(!res.ok)return fetchError("\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u306E\u5C65\u6B74\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093",
|
|
5
5
|
res);const body=res.json??{};const rows=body["rows"];if(!Array.isArray(rows)){return{kind:"error",message:`\u5C65\u6B74\u306E\u5FDC\u7B54\u306B rows \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.raw.slice(0,120)}\uFF09`,status:res.status}}if(body["truncated"]===true||body["reason"]==="history_truncated"){return{kind:"error",message:"\u5C65\u6B74\u306E\u8D70\u67FB\u304C\u6253\u3061\u5207\u3089\u308C\u307E\u3057\u305F\uFF08\u5224\u5B9A\u306B\u4F7F\u3048\u307E\u305B\u3093\uFF09",
|
|
6
6
|
status:res.status}}const windowCounts={};const counts=body["window_counts"];if(counts&&typeof counts==="object"){for(const[k,v]of Object.entries(counts)){if(typeof v==="number"){if(Number.isInteger(v))windowCounts[k]=v}else if(/^-?\d+$/.test(String(v))){windowCounts[k]=Number(String(v))}}}const normalized=rows.map(r=>{const row=r??{};return{ts:str(row["ts"]),schedule_id:str(row["schedule_id"]),window_key:str(row["window_key"]),status:str(row["status"]),item_id:str(row["item_id"]),args:str(row["a\
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{describeError}from"./chunk-
|
|
3
|
+
import{describeError}from"./chunk-BKZGBJWT.js";import{CHAIN_KEYS,reloadAiConfig}from"./chunk-TYNCXQSN.js";import{isPrivateProjectId}from"./chunk-GY7KI5E5.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs from"fs";import path from"path";var PROMPT_KEYS=["charter","charter_prefix","charter_suffix","plan_preamble","step_budget","non_interactive_note","safe_mode_note"];function parseServerSettings(res){const json=res.json;if(json===null||typeof json!=="object"||Array.isArray(json))return null;const top=json;const data=top["data"];const b=data!==null&&typeof data==="object"&&!Array.isArray(data)&&"revision"in data?data:top;const revision=b["revision"];if(typeof revision!=="number"||!Number.isInteger(revision)||revision<0)return null;
|
|
4
4
|
const rawAi=b["ai"];const ai=rawAi!==null&&typeof rawAi==="object"&&!Array.isArray(rawAi)?Object.fromEntries(Object.entries(rawAi).filter(([,v])=>v!==null&&v!==void 0)):{};const prompts={};const rawPrompts=b["prompts"];if(rawPrompts!==null&&typeof rawPrompts==="object"&&!Array.isArray(rawPrompts)){for(const key of PROMPT_KEYS){const v=rawPrompts[key];if(typeof v==="string")prompts[key]=v}}return{revision,ai,prompts}}function formatConfigHash(aiHash,revision,ai,charter){return`${aiHash};r=${revision}\
|
|
5
5
|
;ai=${ai};charter=${charter}`}function renderStepBudget(template,vars){return template.replaceAll("{timeout_min}",String(vars.timeoutMin)).replaceAll("{soft_min}",String(vars.softMin)).replaceAll("{wrap_up_min}",String(vars.wrapUpMin))}var LoopSettingsApplier=class{constructor(deps){this.deps=deps}deps;last=null;lastWarning="";lastAiWarning="";lastSummary="";serverAiApplied=false;lastSafeWarning="";async apply(){const{config,log}=this.deps;const outcome=await this.fetch();const warning=outcome.warning??
|
|
6
6
|
"";if(warning!==""&&warning!==this.lastWarning)log(` \u26A0\uFE0F ${warning}`);else if(warning===""&&this.lastWarning!=="")log("\u30EB\u30FC\u30D7\u8A2D\u5B9A\u3092\u30B5\u30FC\u30D0\u304B\u3089\u518D\u3073\u53D6\u5F97\u3067\u304D\u308B\u3088\u3046\u306B\u306A\u308A\u307E\u3057\u305F");this.lastWarning=warning;const settings=outcome.settings;config.serverPrompts=settings?.prompts??{};const safeNote=config.serverPrompts.safe_mode_note;const safeWarning=config.safeMode&&safeNote!==void 0?safeNote===
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{parseOperationArgs}from"./chunk-IOGVQVGD.js";import{renderOutput}from"./chunk-5Q2CH4E7.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-YVAN3H5W.js";import{
|
|
4
|
-
import{GLOBAL_OPTIONS_HELP}from"./chunk-TAN5I2DP.js";import{HELP_TOKEN}from"./chunk-
|
|
3
|
+
import{parseOperationArgs}from"./chunk-IOGVQVGD.js";import{renderOutput}from"./chunk-5Q2CH4E7.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-YVAN3H5W.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-G4OO4M44.js";import{Resolver,requireDefaultProject}from"./chunk-NIAOX77K.js";import{ResolveError}from"./chunk-GMBJTG6A.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-FTYJZFEK.js";
|
|
4
|
+
import{GLOBAL_OPTIONS_HELP}from"./chunk-TAN5I2DP.js";import{HELP_TOKEN}from"./chunk-SP27PYHC.js";import{AuthSession,NotLoggedInError,SessionExpiredError,loadCredentials}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,loadUserConfig,resolveConfiguredOutput,resolveProfile}from"./chunk-NERYSBA4.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-K2ONOH3L.js";import{stringWidth}from"./chunk-WVS4W5FY.js";import{
|
|
5
5
|
stripTerminalControls}from"./chunk-NHYMHCAT.js";import{evaluateQuery}from"./chunk-GDM2QUBL.js";import{ApiRejectedError,ApiResponseError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,NetworkError,UsageError}from"./chunk-7WSNIXTQ.js";import fs from"fs";import path from"path";var NO_REDACT_FLAG={name:"--no-redact",summary:"\u5FDC\u7B54\u306E\u4F0F\u5B57\u5316\u3092\u89E3\u9664\u3057\u3066\u751F\u306E\u5024\u3092\u51FA\u3059\uFF08\u9375\u306E\u53D7\u3051\u53D6\u308A\u7B49\uFF09",takesValue:false};var NO_REDACT_NOTICE="\u6CE8\u8A18: --no-redact \u306E\u305F\u3081\u51FA\u529B\u3092\u4F0F\u5B57\u5316\u3057\u307E\u305B\u3093\uFF08\u7AEF\u672B\u3068\u30ED\u30B0\u306B\u5E73\u6587\u3067\u6B8B\u308A\u307E\u3059\uFF09\u3002";function withCommonFlags(flags){return flags.some(flag=>flag.
|
|
6
6
|
name===NO_REDACT_FLAG.name)?flags:[...flags,NO_REDACT_FLAG]}function alignedList(entries,indent=" "){const width=entries.reduce((max,[left])=>Math.max(max,stringWidth(left)),0);return entries.map(([left,right])=>`${indent}${left}${" ".repeat(Math.max(0,width-stringWidth(left)))} ${right}`).join("\n")}function subresourcesOf(resource){return resource.subresources??[]}function renderResourceHelp(resource,path2){const subresources=subresourcesOf(resource);const operationSection=resource.operations.length===0?"":`
|
|
7
7
|
\u64CD\u4F5C:
|
|
@@ -18,8 +18,8 @@ ${operationSection}${subSection}
|
|
|
18
18
|
${GLOBAL_OPTIONS_HELP}
|
|
19
19
|
`}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")}const flags=withCommonFlags(op.flags);if(flags.length>0){sections.push("","\u30AA\u30D7\u30B7\u30E7\u30F3:",
|
|
20
20
|
alignedList(flags.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}\
|
|
21
|
-
\uFF09\u3002\u8A73\u3057\u304F\u306F twp ${path2} ${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={
|
|
22
|
-
storageDomain,task:async()=>(await import("./task-
|
|
21
|
+
\uFF09\u3002\u8A73\u3057\u304F\u306F twp ${path2} ${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={"agent-loop":async()=>(await import("./agent-loop-ZP47LTUE.js")).agentLoopDomain,attendance:async()=>(await import("./attendance-42XLURM7.js")).attendanceDomain,backlog:async()=>(await import("./backlog-KSMQIC2R.js")).backlogDomain,department:async()=>(await import("./department-GH475WCF.js")).departmentDomain,"job-title":async()=>(await import("./job-title-FC2GWDE7.js")).jobTitleDomain,media:async()=>(await import("./media-TD7D4TXF.js")).mediaDomain,position:async()=>(await import("./position-4RHTV3IK.js")).
|
|
22
|
+
positionDomain,project:async()=>(await import("./project-DBNWB47J.js")).projectDomain,storage:async()=>(await import("./storage-ANKKJJJO.js")).storageDomain,task:async()=>(await import("./task-7VOYCG26.js")).taskDomain,user:async()=>(await import("./user-UU2SLVC4.js")).userDomain};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}
|
|
23
23
|
`}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)
|
|
24
24
|
return EXIT_AUTH;if(err instanceof ApiError)return exitCodeForStatus(err.status);if(err instanceof ApiRejectedError)return EXIT_API_CLIENT;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,write=writeErr){const message=safeText(err instanceof
|
|
25
25
|
Error?err.message:String(err));const rawHint=err instanceof 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;write(`${JSON.stringify({error:body},null,2)}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{isModeId,isPermissionModeId}from"./chunk-NAUH75MM.js";import{API_TOKEN,HELP_TOKEN,isDomainName}from"./chunk-SP27PYHC.js";import{splitFlagToken}from"./chunk-QQRJLH6B.js";var BUILTIN_COMMANDS=["login","logout","whoami","update","task-loop"];var TASK_LOOP_ACTIONS=["run","status","stop","schedule","setup","charter","skill"];var VALUE_FLAGS=new Set(["-p","--print","--profile","--tenant","--mode","--permission-mode","--model","--allowed-tools","--disallowed-tools","--project","--engine","--interval","--max-cycles","--ai","--workspace","--ai-config-file","--now","--counts","--gate","--file","--out","--revision","--dir","--output","--query"]);var BOOLEAN_FLAGS=new Set(
|
|
4
|
+
["-h","--help","-v","--version","--no-tui","--doctor","--password","--token","--no-browser","--safe","--daemon","--force-runner","--force","--drain","--yes","-y","--no-ai-config-file","--verbose","--all","--dry-run","--debug","--refresh"]);function dispatch(argv,limit=2){const tokens=[];const indexes=[];let truncated=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg===void 0)continue;if(arg.startsWith("-")&&arg!=="-"){const{name,value:inline}=splitFlagToken(arg);if(BOOLEAN_FLAGS.has(
|
|
5
|
+
name)){if(inline!==void 0){truncated=true;break}continue}if(VALUE_FLAGS.has(name)){if(inline!==void 0)continue;const next=argv[i+1];if(next!==void 0&&(!next.startsWith("-")||next==="-"))i++;continue}truncated=true;break}if(arg===""||arg==="-")continue;if(tokens.length>=limit)break;tokens.push(arg);indexes.push(i)}return{tokens,indexes,truncated}}function isBuiltin(token){return token!==void 0&&BUILTIN_COMMANDS.includes(token)}function isTaskLoopAction(token){return token!==void 0&&TASK_LOOP_ACTIONS.
|
|
6
|
+
includes(token)}function resolveRoute(result){const{tokens,indexes}=result;const[first,second]=tokens;const firstIndex=indexes[0];if(first===void 0||firstIndex===void 0)return{kind:"none",consumed:[]};const consumed=[firstIndex];const secondIndex=indexes[1];if(isBuiltin(first)){if(first==="task-loop"&&isTaskLoopAction(second)){if(secondIndex!==void 0)consumed.push(secondIndex);return{kind:"builtin",command:first,action:second,consumed}}return{kind:"builtin",command:first,...first==="task-loop"?{
|
|
7
|
+
action:"run"}:{},consumed}}if(second!==void 0&&secondIndex!==void 0)consumed.push(secondIndex);return{kind:"domain",domain:first,...second!==void 0?{operation:second}:{},consumed}}var GLOBAL_FLAGS=new Set(["-h","--help","-v","--version","--profile","--output","--query","--dry-run","--debug","--yes","-y","--refresh"]);function parseArgv(argv){const out={command:"tui",safe:false,daemon:false,forceRunner:false,stopForce:false,logoutForce:false,stopDrain:false,noTui:false,doctor:false,yes:false,skillAll:false,noAiConfigFile:false,verbose:false,loginMethod:"browser",loginNoBrowser:false,promptFromStdin:false,domainArgv:[],domainHelp:false,dryRun:false,debug:false,refresh:false,
|
|
8
|
+
unknown:[],allowedTools:[],disallowedTools:[]};const route=resolveRoute(dispatch(argv));const consumed=new Set;const[firstIndex,secondIndex]=route.consumed;if(route.kind==="builtin"){out.command=route.command;if(route.action!==void 0)out.taskLoopAction=route.action;for(const index of route.consumed)consumed.add(index)}else if(route.kind==="domain"){if(route.domain===HELP_TOKEN){if(route.operation===void 0){out.command="help";if(firstIndex!==void 0)consumed.add(firstIndex)}else if(isDomainName(route.
|
|
9
|
+
operation)){out.command="domain";out.domain=route.operation;out.domainHelp=true;if(firstIndex!==void 0)consumed.add(firstIndex);if(secondIndex!==void 0)consumed.add(secondIndex)}else if(route.operation===API_TOKEN){out.command="api";out.domainHelp=true;if(firstIndex!==void 0)consumed.add(firstIndex);if(secondIndex!==void 0)consumed.add(secondIndex)}}else if(route.domain===API_TOKEN){out.command="api";if(firstIndex!==void 0)consumed.add(firstIndex)}else if(isDomainName(route.domain)){out.command=
|
|
10
|
+
"domain";out.domain=route.domain;if(route.operation!==void 0)out.operation=route.operation;for(const index of route.consumed)consumed.add(index)}}const hasSubcommandToken=route.kind==="builtin"||route.kind==="domain"&&(route.domain===HELP_TOKEN||route.domain===API_TOKEN||isDomainName(route.domain));const isDomainRoute=out.command==="domain"||out.command==="api";const takeValue=(i,flag,inline)=>{const value=inline??argv[i+1];if(value===void 0||inline===void 0&&value.startsWith("-")){out.unknown.push(
|
|
11
|
+
flag);return{step:0}}if(value.trim()===""){out.unknown.push(inline===void 0?`${flag} `:`${flag}=${inline}`);return{step:0}}return{value,step:inline===void 0?1:0}};let optionsClosed=false;for(let i=0;i<argv.length;i++){if(consumed.has(i))continue;const raw=argv[i];if(raw===void 0)continue;if(isDomainRoute&&raw==="--")optionsClosed=true;const{name:arg,value:inline}=splitFlagToken(raw);if(isDomainRoute&&(optionsClosed||!GLOBAL_FLAGS.has(arg))){out.domainArgv.push(raw);continue}if(inline!==void 0&&BOOLEAN_FLAGS.
|
|
12
|
+
has(arg)){out.unknown.push(raw);continue}switch(arg){case"-h":case"--help":if(isDomainRoute)out.domainHelp=true;else out.command="help";break;case"-v":case"--version":out.command="version";break;case"--no-tui":out.noTui=true;break;case"--doctor":out.doctor=true;break;case"--password":out.loginMethod="password";break;case"--token":out.loginMethod="token";break;case"--no-browser":out.loginNoBrowser=true;break;case"--profile":{const{value,step}=takeValue(i,"--profile",inline);if(value!==void 0){out.
|
|
13
|
+
profile=value;i+=step}break}case"-p":case"--print":{const next=inline??argv[i+1];const step=inline===void 0?1:0;if(hasSubcommandToken){out.unknown.push(raw)}else if(next==="-"){out.command="print";out.promptFromStdin=true;out.prompt="";i+=step}else if(next!==void 0&&(inline!==void 0||!next.startsWith("-"))){out.command="print";out.prompt=next;i+=step}else{out.unknown.push(raw)}break}case"--output":{const{value,step}=takeValue(i,"--output",inline);if(value!==void 0){out.output=value;i+=step}break}case"\
|
|
14
|
+
--query":{const{value,step}=takeValue(i,"--query",inline);if(value!==void 0){out.query=value;i+=step}break}case"--dry-run":out.dryRun=true;break;case"--debug":out.debug=true;break;case"--refresh":out.refresh=true;break;case"--tenant":{const{value,step}=takeValue(i,"--tenant",inline);if(value!==void 0){out.tenant=value;i+=step}break}case"--mode":{const next=inline??argv[i+1];const step=inline===void 0?1:0;if(isModeId(next)){out.mode=next;i+=step}else if(next!==void 0&&(inline!==void 0||!next.startsWith(
|
|
15
|
+
"-"))){out.unknown.push(inline!==void 0?raw:`--mode ${next}`);i+=step}else{out.unknown.push("--mode")}break}case"--permission-mode":{const next=inline??argv[i+1];const step=inline===void 0?1:0;if(isPermissionModeId(next)){out.permissionMode=next;i+=step}else if(next!==void 0&&(inline!==void 0||!next.startsWith("-"))){out.unknown.push(inline!==void 0?raw:`--permission-mode ${next}`);i+=step}else{out.unknown.push("--permission-mode")}break}case"--allowed-tools":case"--disallowed-tools":{const{value,
|
|
16
|
+
step}=takeValue(i,arg,inline);if(value!==void 0){(arg==="--allowed-tools"?out.allowedTools:out.disallowedTools).push(value);i+=step}break}case"--model":{const{value,step}=takeValue(i,"--model",inline);if(value!==void 0){out.model=value;i+=step}break}case"--safe":out.safe=true;break;case"--daemon":out.daemon=true;break;case"--force-runner":out.forceRunner=true;break;case"--force":out.stopForce=true;break;case"--drain":out.stopDrain=true;break;case"--project":{const{value,step}=takeValue(i,"--proj\
|
|
17
|
+
ect",inline);if(value!==void 0){out.project=value;i+=step}break}case"--engine":{const{value,step}=takeValue(i,"--engine",inline);if(value!==void 0){out.engine=value;i+=step}break}case"--interval":case"--max-cycles":{const{value,step}=takeValue(i,arg,inline);if(value!==void 0){const n=Number.parseInt(value,10);if(Number.isInteger(n)&&n>0){if(arg==="--interval")out.interval=n;else out.maxCycles=n}else{out.unknown.push(inline!==void 0?raw:`${arg} ${value}`)}i+=step}break}case"--yes":case"-y":out.yes=
|
|
18
|
+
true;break;case"--ai":{const{value:v,step}=takeValue(i,"--ai",inline);if(v!==void 0){out.ais=[...out.ais??[],v];i+=step}break}case"--no-ai-config-file":out.noAiConfigFile=true;break;case"--workspace":{const{value:v,step}=takeValue(i,"--workspace",inline);if(v!==void 0){out.workspace=v;i+=step}break}case"--ai-config-file":{const{value:v,step}=takeValue(i,"--ai-config-file",inline);if(v!==void 0){out.aiConfigFile=v;i+=step}break}case"--verbose":out.verbose=true;break;case"--now":{const{value:v,step}=takeValue(
|
|
19
|
+
i,"--now",inline);if(v!==void 0){out.scheduleNow=v;i+=step}break}case"--counts":{const{value:v,step}=takeValue(i,"--counts",inline);if(v!==void 0){out.scheduleCounts=v;i+=step}break}case"--gate":{const{value:v,step}=takeValue(i,"--gate",inline);if(v!==void 0){out.scheduleGate=v;i+=step}break}case"--file":{const{value:v,step}=takeValue(i,"--file",inline);if(v!==void 0){out.charterFile=v;i+=step}break}case"--out":{const{value:v,step}=takeValue(i,"--out",inline);if(v!==void 0){out.charterOut=v;i+=step}
|
|
20
|
+
break}case"--revision":{const{value:v,step}=takeValue(i,"--revision",inline);if(v!==void 0){out.charterRevision=v;i+=step}break}case"--dir":{const{value:v,step}=takeValue(i,"--dir",inline);if(v!==void 0){out.skillDir=v;i+=step}break}case"--all":out.skillAll=true;break;default:if(out.command==="task-loop"&&out.taskLoopAction==="charter"&&out.charterOp===void 0&&(raw==="push"||raw==="pull")){out.charterOp=raw;break}if(out.command==="task-loop"&&out.taskLoopAction==="skill"){if(out.skillOp===void 0&&
|
|
21
|
+
(raw==="push"||raw==="pull")){out.skillOp=raw;break}if(out.skillOp!==void 0&&out.skillName===void 0&&!raw.startsWith("-")){out.skillName=raw;break}}out.unknown.push(raw)}}if(out.command!=="login"&&out.loginMethod!=="browser"){out.unknown.push(out.loginMethod==="password"?"--password":"--token");out.loginMethod="browser"}if(out.permissionMode!==void 0&&out.command!=="tui"&&out.command!=="print"){out.unknown.push("--permission-mode");delete out.permissionMode}if(out.command!=="tui"&&out.command!==
|
|
22
|
+
"print"){if(out.allowedTools.length>0)out.unknown.push("--allowed-tools");if(out.disallowedTools.length>0)out.unknown.push("--disallowed-tools");out.allowedTools=[];out.disallowedTools=[]}if(out.loginNoBrowser&&!(out.command==="login"&&out.loginMethod==="browser")){out.unknown.push("--no-browser");out.loginNoBrowser=false}if(out.command==="logout"&&out.stopForce){out.logoutForce=true;out.stopForce=false}if(out.command!=="task-loop"){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.
|
|
23
|
+
push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.stopForce)out.unknown.push("--force");if(out.stopDrain)out.unknown.push("--drain");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles");if(out.project!==void 0)out.unknown.push("--project");if(out.verbose)out.unknown.push("--verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==
|
|
24
|
+
void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate");if(out.ais!==void 0)out.unknown.push("--ai");if(out.workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file");if(out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision");if(out.
|
|
25
|
+
skillDir!==void 0)out.unknown.push("--dir");if(out.skillAll)out.unknown.push("--all")}if(out.yes&&out.command!=="task-loop"&&!isDomainRoute)out.unknown.push("--yes");const acceptsOutput=isDomainRoute||out.command==="whoami";if(!acceptsOutput){if(out.output!==void 0)out.unknown.push("--output");if(out.query!==void 0)out.unknown.push("--query")}if(!isDomainRoute){if(out.dryRun)out.unknown.push("--dry-run");if(out.debug)out.unknown.push("--debug");if(out.refresh)out.unknown.push("--refresh")}if(out.
|
|
26
|
+
command==="api"&&out.refresh){out.unknown.push("--refresh");out.refresh=false}if(out.command==="task-loop"&&out.taskLoopAction!=="schedule"){if(out.verbose)out.unknown.push("--verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopForce){out.unknown.push("--force")}if(out.command==="task-loop"&&out.taskLoopAction!==
|
|
27
|
+
"stop"&&out.stopDrain){out.unknown.push("--drain")}if(out.command==="task-loop"&&out.taskLoopAction==="stop"&&out.stopForce&&out.stopDrain){out.unknown.push("--force \u3068 --drain \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");out.stopForce=false;out.stopDrain=false}if(out.command==="task-loop"&&out.taskLoopAction!=="setup"){if(out.yes&&out.taskLoopAction!=="charter"&&out.taskLoopAction!=="skill")out.unknown.push("--yes");if(out.ais!==void 0)out.unknown.push("--ai");if(out.
|
|
28
|
+
workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file")}if(out.command==="task-loop"&&(out.taskLoopAction==="stop"||out.taskLoopAction==="status")){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push(
|
|
29
|
+
"--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="setup"){if(out.engine!==void 0)out.unknown.push("--engine");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="charter"){if(out.
|
|
30
|
+
charterOp===void 0){out.unknown.push("charter \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}if(out.charterOp!=="push"&&out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOp!=="push"&&out.charterRevision!==void 0)out.unknown.push("--revision");if(out.charterOp!=="pull"&&out.charterOut!==void 0)out.unknown.push("--out");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--for\
|
|
31
|
+
ce-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}else if(out.command==="task-loop"&&out.taskLoopAction==="skill"){if(out.skillOp===void 0){out.unknown.push("skill \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}else if(out.skillName===void 0&&!out.skillAll){out.unknown.push(`skill ${out.skillOp} \u306B\u306F\u30B9\u30AD\u30EB\u540D\u304B --all \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`)}else if(out.
|
|
32
|
+
skillName!==void 0&&out.skillAll){out.unknown.push("\u30B9\u30AD\u30EB\u540D\u3068 --all \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093")}if(out.skillOp!=="push"&&out.charterRevision!==void 0)out.unknown.push("--revision");if(out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOut!==void 0)out.unknown.push("--out");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==
|
|
33
|
+
void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}else if(out.command==="task-loop"){if(out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision")}if(out.command==="task-loop"&&out.taskLoopAction!=="skill"){if(out.skillDir!==void 0)out.unknown.push("--dir");if(out.skillAll)out.unknown.push(
|
|
34
|
+
"--all")}return out}export{parseArgv};
|