@tocca-systems/twp-cli 0.155.0 → 0.155.1

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.
@@ -11,6 +11,10 @@
11
11
  `CHANGELOG.md` に残してあります。顧客向けの履歴は public 公開以降を対象とします。
12
12
  -->
13
13
 
14
+ ## 0.155.1
15
+
16
+ AI がファイルを扱うときの安全策を強化しました。ハードリンクや特殊ファイル、.git フォルダの中身は読み書きしません。
17
+
14
18
  ## 0.155.0
15
19
 
16
20
  予実管理の按分設定に、部署ごと・期間ごとの備考(計算根拠)を書けるようになりました。
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-DEIIS7JP.js";import{exitCodeFor,fetchAllPages,reportError}from"./chunk-RJV2VT2X.js";import"./chunk-GIFOJFVU.js";import{evaluateQuery}from"./chunk-PAJAEUPA.js";import{renderOutput}from"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{describeWaitResult,parseWaitOptions,waitUntilTerminal}from"./chunk-3EFJQDC4.js";
3
+ import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-DEIIS7JP.js";import{exitCodeFor,fetchAllPages,reportError}from"./chunk-6NJSB2SM.js";import"./chunk-XYCZIUWI.js";import{evaluateQuery}from"./chunk-PAJAEUPA.js";import{renderOutput}from"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{describeWaitResult,parseWaitOptions,waitUntilTerminal}from"./chunk-3EFJQDC4.js";
4
4
  import{readBody}from"./chunk-V5WDGX4S.js";import{ALLOW_REDACTED_FLAG,NO_REDACT_FLAG,NO_REDACT_NOTICE}from"./chunk-W4NLJ2YK.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-BD7O73GK.js";import{parseOperationArgs,repeatedValues}from"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import{ApiError,RepeatedQueryValue,TwpApiClient,appendQuery,appendRepeatable,isArrayQueryKey}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";
5
5
  import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,envelopePaging,isPageNumberEnvelope,pageRangeNotes,positiveInteger,readEnvelopeCursor,readPageNumberCursor,shellQuote}from"./chunk-TDO6V3ZW.js";import"./chunk-HCTPCUST.js";import{ApiResponseError,EXIT_OK,EXIT_WAIT_TIMEOUT,NetworkError,UsageError}from"./chunk-STILP3Z6.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-TZL2342W.js";import{AuthSession,NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";
6
6
  import{loadCredentials}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,resolveConfiguredOutput,resolveProfile}from"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import{HELP_TOKEN}from"./chunk-F3UL5POS.js";import"./chunk-OKATZ4SN.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var MIN_SEGMENT_CHARS=3;var parsedCache=new WeakMap;function splitSegments(path){return path.split("/").filter(segment=>segment!=="")}function parseRoutes(routes){const cached=parsedCache.get(routes);if(cached!==void 0)return cached;const parsed=[];for(const[key,domain]of Object.entries(routes.routes)){const space=key.indexOf(" ");if(space<=0)continue;const template=key.slice(space+1);parsed.push({method:key.slice(0,space),template,domain,segments:splitSegments(template).map(segment=>/^\{[^/{}]+\}$/.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{RESIDENT_TOKEN_CAP,activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,createTwpToolkit,currentBranch,describeAuditLog,describeToolCatalog,displayCwd,executeTool,findProjectTwpSubdir,localTools,lstatOrNull,parseFrontMatter,parseRule,persistProjectAllow,projectPermissionsPath,projectRootFor,readFileTool,residentInputs,resolveGitExecutable,runTurn}from"./chunk-Q5DW75AO.js";import"./chunk-DEIIS7JP.js";import{buildDiffLines,diffStat}from"./chunk-VRBI2NPI.js";
4
- import{secretReason}from"./chunk-XCU3PDQV.js";import{require_fuzzysort}from"./chunk-DIMZRTLE.js";import"./chunk-N2UVRM3Z.js";import"./chunk-BD7O73GK.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-STILP3Z6.js";import{RelayError,builtinCatalog,classifyModelSwitch,createRuntime,formatContextRemaining,
3
+ import{RESIDENT_TOKEN_CAP,activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,createTwpToolkit,currentBranch,describeAuditLog,describeToolCatalog,displayCwd,executeTool,findProjectTwpSubdir,localTools,lstatOrNull,parseFrontMatter,parseRule,persistProjectAllow,projectPermissionsPath,projectRootFor,readFileTool,residentInputs,resolveGitExecutable,runTurn}from"./chunk-XYLJSSKY.js";import"./chunk-DEIIS7JP.js";import{buildDiffLines,diffStat}from"./chunk-VRBI2NPI.js";
4
+ import{secretReason}from"./chunk-UQP47QOV.js";import{require_fuzzysort}from"./chunk-DIMZRTLE.js";import"./chunk-N2UVRM3Z.js";import"./chunk-BD7O73GK.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-STILP3Z6.js";import{RelayError,builtinCatalog,classifyModelSwitch,createRuntime,formatContextRemaining,
5
5
  loadCachedCatalog,modelLabel,pickModel,specFor,toModelInfos}from"./chunk-CASLLD23.js";import"./chunk-D233KKXW.js";import"./chunk-PMOUHEJQ.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import{proxyDiagnostics}from"./chunk-J7QYPKVK.js";import{checkMinSupportedVersion,isBelowMinSupported,minSupportedBlockMessage}from"./chunk-DXXFUNYN.js";import"./chunk-EDF4U5BT.js";import{configReadDirs,twpHomeDir}from"./chunk-RZVI6PMW.js";import{parseArgv}from"./chunk-P75ML6PX.js";
6
6
  import{applyPermissionMode,checkPermission,describePermissionMode,getMode,isModeId,modeSource,nextMode}from"./chunk-2LOT54OO.js";import"./chunk-NJL3H2BB.js";import"./chunk-F3UL5POS.js";import"./chunk-MS52L74Z.js";import{formatUnknownArgs}from"./chunk-OKATZ4SN.js";import{isFullWidth,isWide,stringWidth,stripAnsi}from"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{__commonJS,__export,__require,__toESM}from"./chunk-VSJBJXZO.js";var require_react_production=__commonJS({"node_modules/react/cjs/react.production.js"(exports){"use strict";var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element");var REACT_PORTAL_TYPE=Symbol.for("react.portal");var REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");var REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode");var REACT_PROFILER_TYPE=Symbol.for("react.profiler");var REACT_CONSUMER_TYPE=Symbol.for("react.consumer");var REACT_CONTEXT_TYPE=Symbol.for("react.context");var REACT_FORWARD_REF_TYPE=Symbol.
7
7
  for("react.forward_ref");var REACT_SUSPENSE_TYPE=Symbol.for("react.suspense");var REACT_MEMO_TYPE=Symbol.for("react.memo");var REACT_LAZY_TYPE=Symbol.for("react.lazy");var REACT_ACTIVITY_TYPE=Symbol.for("react.activity");var REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition");var MAYBE_ITERATOR_SYMBOL=Symbol.iterator;function getIteratorFn(maybeIterable){if(null===maybeIterable||"object"!==typeof maybeIterable)return null;maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||
@@ -1212,7 +1212,7 @@ cwd()){const listed=await gitListFiles(cwd2);const raw=listed??await walkFiles(c
1212
1212
  1;const after=/^[^\s]*/.exec(text.slice(cursor))?.[0]??"";return{query,start,end:cursor+after.length}}var TWP_SLASH_ROUTES={"/tasks":{domain:"task",operation:"list"},"/task":{domain:"task",operation:"get"},"/projects":{domain:"project",operation:"list"}};function isTwpSlashCommand(name){return Object.hasOwn(TWP_SLASH_ROUTES,name)}async function runTwpSlashCommand(name,args,deps){const route=TWP_SLASH_ROUTES[name];if(!Object.hasOwn(TWP_SLASH_ROUTES,name)||route===void 0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u30B3\u30DE\u30F3\u30C9: ${name}
1213
1213
  `}}const parsed=parseArgv([route.domain,route.operation,...args]);if(parsed.command!=="domain"||parsed.domain!==route.domain){return{code:2,out:"",err:`${name}: \u3053\u306E\u5F15\u6570\u306F\u4F7F\u3048\u307E\u305B\u3093\uFF08${args.join(" ")}\uFF09
1214
1214
  `}}if(parsed.unknown.length>0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u5F15\u6570: ${formatUnknownArgs(parsed.unknown)}
1215
- `}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-X5DTRFHA.js");try{const code=await runDomain({domain:route.domain,...parsed.operation!==void 0?{operation:parsed.operation}:
1215
+ `}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-GIXUKZEL.js");try{const code=await runDomain({domain:route.domain,...parsed.operation!==void 0?{operation:parsed.operation}:
1216
1216
  {},argv:parsed.domainArgv,help:parsed.domainHelp,globals,version:deps.version,io,...deps.fetchImpl!==void 0?{fetchImpl:deps.fetchImpl}:{}});return{code,out,err}}catch(e){return{code:1,out,err:`${err}${e.message}
1217
1217
  `}}}var GIT_LOG_OUTPUT=["9f3c1a2 feat(ui): \u4E00\u89A7\u306E\u30D5\u30A3\u30EB\u30BF\u3092 URL \u30AF\u30A8\u30EA\u3068\u540C\u671F\u3059\u308B","4b8e0d7 fix(ui): \u4EEE\u60F3\u30B9\u30AF\u30ED\u30FC\u30EB\u306E\u884C\u9AD8\u3055\u3092\u5B9F\u6E2C\u5024\u306B\u5408\u308F\u305B\u308B","c15a99e refactor(api): \u4E00\u89A7\u53D6\u5F97\u306E\u30DA\u30FC\u30B8\u30F3\u30B0\u51E6\u7406\u3092\u5171\u901A\u5316\u3059\u308B","2d70f4b test: \u4E00\u89A7\u30D5\u30A3\u30EB\u30BF\u306E\u56DE\u5E30\u30C6\u30B9\u30C8\u3092\u8FFD\u52A0\u3059\u308B",
1218
1218
  "a6e2b38 fix(api): \u7A7A\u306E\u691C\u7D22\u6761\u4EF6\u3067\u5168\u4EF6\u8FD4\u3089\u306A\u3044\u3088\u3046\u306B\u3059\u308B","7c40d51 chore(deps): \u958B\u767A\u4F9D\u5B58\u3092\u6700\u65B0\u3078\u66F4\u65B0\u3059\u308B","e83b1c6 docs: \u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u624B\u9806\u306B Node 22 \u306E\u524D\u63D0\u3092\u8FFD\u8A18\u3059\u308B","b91f7a4 fix(ui): \u30E2\u30FC\u30C0\u30EB\u306E\u91CD\u306A\u308A\u9806\u3092\u6307\u5B9A\u3059\u308B","5a2c8e0 perf(api): \u4E00\u89A7\u306E N+1 \u3092\u89E3\u6D88\u3059\u308B",
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{loadDomain}from"./chunk-GIFOJFVU.js";import{evaluateQuery}from"./chunk-PAJAEUPA.js";import{renderDocument,renderOutput}from"./chunk-P4QSPSOQ.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{NO_REDACT_NOTICE,withCommonFlags}from"./chunk-W4NLJ2YK.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-BD7O73GK.js";import{parseOperationArgs}from"./chunk-6NHLWYI2.js";import{Resolver,credentialIdentity,requireDefaultProject}from"./chunk-QLH5IJQV.js";
3
+ import{loadDomain}from"./chunk-XYCZIUWI.js";import{evaluateQuery}from"./chunk-PAJAEUPA.js";import{renderDocument,renderOutput}from"./chunk-P4QSPSOQ.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{NO_REDACT_NOTICE,withCommonFlags}from"./chunk-W4NLJ2YK.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-BD7O73GK.js";import{parseOperationArgs}from"./chunk-6NHLWYI2.js";import{Resolver,credentialIdentity,requireDefaultProject}from"./chunk-QLH5IJQV.js";
4
4
  import{ApiError,MultipartBody,TwpApiClient,appendQuery}from"./chunk-3CEGTEI3.js";import{ResolveError}from"./chunk-HVZUXLQ4.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-TDO6V3ZW.js";import{isRecord}from"./chunk-HCTPCUST.js";import{ApiRejectedError,ApiResponseError,ConflictError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_CONFLICT,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,EXIT_WAIT_TIMEOUT,NetworkError,UsageError,WaitTimeoutError}from"./chunk-STILP3Z6.js";
5
5
  import{GLOBAL_OPTIONS_HELP}from"./chunk-TZL2342W.js";import{AuthSession,NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";import{loadCredentials}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,loadUserConfig,resolveConfiguredBacklogSpace,resolveConfiguredOutput,resolveProfile}from"./chunk-EDF4U5BT.js";import{HELP_TOKEN}from"./chunk-F3UL5POS.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-RKBUJKI5.js";
6
6
  import{stringWidth}from"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs from"fs";import path from"path";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?"":`
@@ -0,0 +1,15 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{configReadDirs}from"./chunk-RZVI6PMW.js";import{constants as fsConstants,lstatSync,readlinkSync,realpathSync,statSync}from"fs";import{open}from"fs/promises";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),input);assertNotSecret(abs,home,process.env,input);assertNotGitMetadata(
4
+ abs,resolve(cwd),input);const real=realOrSelf(abs);if(real!==abs){assertInside(real,root,input);assertNotSecret(real,home,process.env,input);assertNotGitMetadata(real,root,input)}assertPlainEntry(real,input);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(
5
+ `path escapes the working directory (${reported}). Only paths under the working directory can be accessed.`)}}function gitMetadataReason(absPath,root){const rel=relative(root,absPath);if(rel===""||rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))return null;return rel.toLowerCase().split(sep).includes(".git")?"git metadata (.git) is denied; use the git tool to inspect history":null}function assertNotGitMetadata(absPath,root,reported){const reason=gitMetadataReason(absPath,root);if(reason!==
6
+ null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function assertPlainEntry(real,reported){let info;try{info=statSync(real)}catch{return}const reason=plainEntryReason(info);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function plainEntryReason(info){if(info.isDirectory())return null;if(!info.isFile())return"not a regular file (FIFO, socket and device files are denied)";if(info.nlink>1)return"hard links are denied (the file has \
7
+ another name that may be outside the working directory)";return null}function specialFileReason(absPath){try{return plainEntryReason(statSync(absPath))}catch{return null}}var O_NONBLOCK=fsConstants.O_NONBLOCK??0;async function openPlainFile(absPath,reported,mode){const flags=mode==="write"?fsConstants.O_RDWR|fsConstants.O_CREAT|O_NONBLOCK:mode==="update"?fsConstants.O_RDWR|O_NONBLOCK:fsConstants.O_RDONLY|O_NONBLOCK;let handle;try{handle=await open(absPath,flags,438)}catch(err){if(err.code==="ENO\
8
+ ENT"&&mode!=="write")return null;throw err}try{const info=await handle.stat();if(info.isDirectory())throw Object.assign(new Error(`${reported} is a directory`),{code:"EISDIR"});const reason=plainEntryReason(info);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}catch(err){await handle.close();throw err}return handle}async function replaceContent(handle,text){const buf=Buffer.from(text,"utf8");await handle.truncate(0);let offset=0;while(offset<buf.length){const{
9
+ bytesWritten}=await handle.write(buf,offset,buf.length-offset,offset);offset+=bytesWritten}}function isGitMetadata(abs,cwd){const root=resolve(cwd);return gitMetadataReason(abs,root)!==null||gitMetadataReason(realOrSelf(abs),realOrSelf(root))!==null}function redactPaths(text,cwd,home=homedir()){const roots=[];for(const dir of new Set([resolve(cwd),realOrSelf(resolve(cwd))]))roots.push([dir,"."]);if(home!==""&&home!==sep){for(const dir of new Set([resolve(home),realOrSelf(resolve(home))]))roots.push(
10
+ [dir,"~"])}roots.sort((a,b)=>b[0].length-a[0].length);let out=text;for(const[dir,label]of roots){if(dir===sep)continue;const sepClass=sep==="\\"?"[\\\\/]":"/";const escaped=dir.split(sep).map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(sepClass);out=out.replace(new RegExp(`(?<![\\w./\\\\-])${escaped}(?=${sepClass}|$|[^\\w.-]|\\.(?![\\w-]))`,sep==="\\"?"gi":"g"),label)}return out}function realOrSelf(target){let current=target;const rest=[];let hops=0;for(;;){try{const real=realpathSync(
11
+ current);return rest.length===0?real:resolve(real,...rest.reverse())}catch{let link=null;try{if(lstatSync(current).isSymbolicLink())link=readlinkSync(current)}catch{link=null}if(link!==null&&hops<40){hops+=1;current=resolve(dirname(current),link);continue}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,reported=absPath){const reason=secretReason(absPath,home,
12
+ env);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function secretReason(absPath,_home=homedir(),env=process.env){const lower=absPath.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===
13
+ "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 denied";if(parent===".aws"&&(base==="credentials"||base==="config"))return"AWS credentials are denied";for(const dir of configReadDirs(env)){if(lower===resolve(dir,"credentials.json").toLowerCase()){return"TWP credentials are denied (design \xA77)"}}if(parent===".twp"&&base==="credentials.json")return"TWP credentials are denied (d\
14
+ esign \xA77)";if(parent==="logs"&&base.startsWith("session-")&&base.endsWith(".jsonl")){const grandparent=segments[segments.length-3]??"";if(grandparent===".twp")return"TWP audit logs are denied (design \xA77)";for(const dir of configReadDirs(env)){if(lower.startsWith(resolve(dir,"logs").toLowerCase()+sep)){return"TWP audit logs are denied (design \xA77)"}}}return null}function toolRelative(cwd,absPath){const rel=relative(cwd,absPath);return sep==="\\"?rel.split("\\").join("/"):rel}function isInsideCwd(absPath,cwd){
15
+ const root=resolve(cwd);if(!withinLexically(absPath,root))return false;const real=realOrSelf(absPath);return real===absPath||withinLexically(real,realOrSelf(root))}function withinLexically(target,root){const rel=relative(root,target);return!(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))}function expandHome(input,home){if(input==="~")return home;if(input.startsWith("~/")||input.startsWith(`~${sep}`))return resolve(home,input.slice(2));return input}export{PathDeniedError,resolveToolPath,realToolPath,specialFileReason,openPlainFile,replaceContent,isGitMetadata,redactPaths,realOrSelf,secretReason,toolRelative,isInsideCwd};
@@ -4,8 +4,8 @@ var LOADERS={agent:async()=>(await import("./agent-K5CM2ADZ.js")).agentDomain,"a
4
4
  attendanceDomainWithRecords,"audit-log":async()=>(await import("./audit-log-AFBDNA3K.js")).auditLogDomain,backlog:async()=>(await import("./backlog-2MAC27XU.js")).backlogDomain,brief:async()=>(await import("./brief-R2VU6PZG.js")).briefDomain,budget:async()=>(await import("./budget-WF3NMBSR.js")).budgetDomain,"business-hours":async()=>(await import("./business-hours-QL763KSA.js")).businessHoursDomain,"business-place":async()=>(await import("./sales-master-MRUDSFL3.js")).businessPlaceDomain,
5
5
  chat:async()=>(await import("./chat-UZG2LBDF.js")).chatDomain,company:async()=>(await import("./company-IBFYPT24.js")).companyDomain,content:async()=>(await import("./content-3LKHXHYD.js")).contentDomain,contract:async()=>(await import("./contract-R6LTDOSM.js")).contractDomain,corporate:async()=>(await import("./corporate-BFCZA2SM.js")).corporateDomain,customer:async()=>(await import("./company-IBFYPT24.js")).customerDomain,department:async()=>(await import("./department-E7AJZGE2.js")).
6
6
  departmentDomain,deposit:async()=>(await import("./deposit-ERYZ6LUL.js")).depositDomain,equipment:async()=>(await import("./equipment-3BUGFDO2.js")).equipmentDomain,estimate:async()=>(await import("./estimate-SMPPKNDS.js")).estimateDomain,evaluation:async()=>(await import("./evaluation-IVNIFO5F.js")).evaluationDomain,expense:async()=>(await import("./expense-PYUKOXSH.js")).expenseDomain,faq:async()=>(await import("./faq-ZNVLPTZY.js")).faqDomain,"fiscal-year":async()=>(await import("./fiscal-year-V6ARMCIC.js")).
7
- fiscalYearDomain,github:async()=>(await import("./github-ZJEMBA6G.js")).githubDomain,hearing:async()=>(await import("./hearing-ODVABJEZ.js")).hearingDomain,holiday:async()=>(await import("./holiday-7R3GZPJB.js")).holidayDomain,"goal-sheet":async()=>(await import("./evaluation-IVNIFO5F.js")).goalSheetDomain,inquiry:async()=>(await import("./inquiry-YT6FF4D3.js")).inquiryDomain,invoice:async()=>(await import("./invoice-O2WWX5G5.js")).invoiceDomain,"job-title":async()=>(await import("./job-title-YSURWRLQ.js")).
8
- jobTitleDomain,journal:async()=>(await import("./journal-E3GQQR4S.js")).journalDomain,knowledge:async()=>(await import("./domain-knowledge-3U57CM4H.js")).knowledgeDomain,leave:async()=>(await import("./leave-2MTVFD5J.js")).leaveDomain,license:async()=>(await import("./license-XDBDNNGO.js")).licenseDomain,"login-history":async()=>(await import("./login-history-S3NCJGSU.js")).loginHistoryDomain,media:async()=>(await import("./media-RV46QW3P.js")).mediaDomain,meeting:async()=>(await import("./knowledge-5RLWQ4TS.js")).
7
+ fiscalYearDomain,github:async()=>(await import("./github-U3LQ2EMQ.js")).githubDomain,hearing:async()=>(await import("./hearing-ODVABJEZ.js")).hearingDomain,holiday:async()=>(await import("./holiday-7R3GZPJB.js")).holidayDomain,"goal-sheet":async()=>(await import("./evaluation-IVNIFO5F.js")).goalSheetDomain,inquiry:async()=>(await import("./inquiry-YT6FF4D3.js")).inquiryDomain,invoice:async()=>(await import("./invoice-O2WWX5G5.js")).invoiceDomain,"job-title":async()=>(await import("./job-title-YSURWRLQ.js")).
8
+ jobTitleDomain,journal:async()=>(await import("./journal-E3GQQR4S.js")).journalDomain,knowledge:async()=>(await import("./domain-knowledge-3U57CM4H.js")).knowledgeDomain,leave:async()=>(await import("./leave-2MTVFD5J.js")).leaveDomain,license:async()=>(await import("./license-XDBDNNGO.js")).licenseDomain,"login-history":async()=>(await import("./login-history-S3NCJGSU.js")).loginHistoryDomain,media:async()=>(await import("./media-TR4DPGIL.js")).mediaDomain,meeting:async()=>(await import("./knowledge-5RLWQ4TS.js")).
9
9
  meetingDomain,note:async()=>(await import("./note-QKO2N4BU.js")).noteDomain,notification:async()=>(await import("./notification-NJO7Y63S.js")).notificationDomain,ojt:async()=>(await import("./ojt-6SRI2C4U.js")).ojtDomain,onedrive:async()=>(await import("./onedrive-QT3BIYM3.js")).onedriveDomain,outlook:async()=>(await import("./outlook-RSWPGKML.js")).outlookDomain,payee:async()=>(await import("./sales-master-MRUDSFL3.js")).payeeDomain,position:async()=>(await import("./position-P5VDX4WS.js")).
10
10
  positionDomain,project:async()=>(await import("./project-3D4T7YPA.js")).projectDomain,"process-master":async()=>(await import("./project-masters-UE6PKPN3.js")).processMasterDomain,prospect:async()=>(await import("./prospect-ET4D6AKD.js")).prospectDomain,purchase:async()=>(await import("./purchase-ECXYTHDQ.js")).purchaseDomain,qualification:async()=>(await import("./skill-5M5L4AR4.js")).qualificationDomain,"quality-check-item":async()=>(await import("./project-masters-UE6PKPN3.js")).qualityCheckItemDomain,
11
11
  receivable:async()=>(await import("./receivable-EUPSJBHO.js")).receivableDomain,redmine:async()=>(await import("./redmine-RPC66X3F.js")).redmineDomain,report:async()=>(await import("./report-QTN2RPG2.js")).reportDomain,"role-template":async()=>(await import("./evaluation-IVNIFO5F.js")).roleTemplateDomain,"rounding-setting":async()=>(await import("./sales-numbering-WUFZZRTN.js")).roundingSettingDomain,"seal-impression":async()=>(await import("./sales-master-MRUDSFL3.js")).sealImpressionDomain,
@@ -1,8 +1,8 @@
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,withCommonQueryParams}from"./chunk-DEIIS7JP.js";import{PathDeniedError,isInsideCwd,realOrSelf,realToolPath,resolveToolPath,secretReason,toolRelative}from"./chunk-XCU3PDQV.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{redactSecretValues}from"./chunk-BD7O73GK.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-3CEGTEI3.js";
4
- import{isSafePathSegment}from"./chunk-HVZUXLQ4.js";import{DEFAULT_MAX_HISTORY_BYTES,DEFAULT_MAX_TOKENS,effectiveModelSpec,emptyUsage}from"./chunk-CASLLD23.js";import{isPrivateTwpHome,isTrustworthyCacheFile,writePrivateFileAtomic}from"./chunk-D233KKXW.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{AuthSession,NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";import{withFileLock}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";
5
- import{configReadDirs,ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-2LOT54OO.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs2 from"fs";import path3 from"path";import os2 from"os";import path from"path";import{homedir}from"os";import{sep}from"path";function isSingleCommand(command){let quote=null;for(let i=0;i<command.length;i++){const ch=command[i];const next=command[i+1];if(quote==="'"){if(ch==="'")quote=null;continue}if(quote==='"'){if(ch==="\\"){i++;continue}if(ch==="`")return false;if(ch==="$"&&next==="(")return false;if(ch==='"')quote=null;continue}switch(ch){case'"':case"'":quote=ch;continue;case"\\":i++;continue;case";":case"&":case"|":case"\n":case"`":case">":case"<":return false;case"$":if(next==="(")return false;if(next==="'")return false;
3
+ import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelIndex,validateBody,validateQuery,withCommonQueryParams}from"./chunk-DEIIS7JP.js";import{PathDeniedError,isGitMetadata,isInsideCwd,openPlainFile,realOrSelf,realToolPath,redactPaths,replaceContent,resolveToolPath,secretReason,specialFileReason,toolRelative}from"./chunk-UQP47QOV.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{redactSecretValues}from"./chunk-BD7O73GK.js";
4
+ import{ApiError,TwpApiClient,appendQuery}from"./chunk-3CEGTEI3.js";import{isSafePathSegment}from"./chunk-HVZUXLQ4.js";import{DEFAULT_MAX_HISTORY_BYTES,DEFAULT_MAX_TOKENS,effectiveModelSpec,emptyUsage}from"./chunk-CASLLD23.js";import{isPrivateTwpHome,isTrustworthyCacheFile,writePrivateFileAtomic}from"./chunk-D233KKXW.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{AuthSession,NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";
5
+ import{withFileLock}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{configReadDirs,ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-2LOT54OO.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs2 from"fs";import path3 from"path";import os2 from"os";import path from"path";import{homedir}from"os";import{sep}from"path";function isSingleCommand(command){let quote=null;for(let i=0;i<command.length;i++){const ch=command[i];const next=command[i+1];if(quote==="'"){if(ch==="'")quote=null;continue}if(quote==='"'){if(ch==="\\"){i++;continue}if(ch==="`")return false;if(ch==="$"&&next==="(")return false;if(ch==='"')quote=null;continue}switch(ch){case'"':case"'":quote=ch;continue;case"\\":i++;continue;case";":case"&":case"|":case"\n":case"`":case">":case"<":return false;case"$":if(next==="(")return false;if(next==="'")return false;
6
6
  continue;case"#":{const prev=command[i-1];if(i===0||prev===" "||prev===" ")return false;continue}default:continue}}return true}function isRecursiveForceRemove(command){const re=/(^|[^\w.-])(rm|rmdir)([^\w.-]|$)/g;for(;;){const m=re.exec(command);if(m===null)return false;const tail=command.slice(m.index+m[0].length);const segment=tail.split(/[;&|\n]/)[0]??"";const tokens=segment.split(/\s+/).filter(t=>t.startsWith("-"));let recursive=false;let force=false;for(const flag of tokens){if(flag==="--re\
7
7
  cursive")recursive=true;if(flag==="--force")force=true;if(!flag.startsWith("--")){if(flag.includes("r")||flag.includes("R"))recursive=true;if(flag.includes("f"))force=true}}if(recursive&&force)return true}}function neverAutoAllowReason(tool,input){if(tool.risk!=="exec")return null;let declared;try{declared=tool.execCommands?.(input)??null}catch{declared=null}const shell=(declared?.shell??[]).filter(command=>typeof command==="string"&&command!=="");const argv=(declared?.argv??[]).map(entry=>Array.
8
8
  isArray(entry)?entry.join(" "):"").filter(command=>command!=="");if(shell.length===0&&argv.length===0){return`${tool.name} \u304C\u5B9F\u884C\u3059\u308B\u30B3\u30DE\u30F3\u30C9\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059`}for(const command of[...shell,...argv]){if(isRecursiveForceRemove(command))return"rm -rf \u3092\u542B\u3080\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059"}for(const command of shell){if(!isSingleCommand(command)){
@@ -82,10 +82,10 @@ return{content:instead===""?`permission denied: the user declined to run ${tool.
82
82
  ${instead}`,isError:true,denied:true,summary:instead===""?`${tool.name} \xB7 \u5229\u7528\u8005\u304C\u62D2\u5426`:`${tool.name} \xB7 \u5229\u7528\u8005\u304C\u62D2\u5426\uFF08\u4EE3\u308F\u308A\u306E\u6307\u793A\u3042\u308A\uFF09`}}if(answer==="always"&&noAlwaysReason===null&&target.tool.name!==INDIRECT_TOOL){deps.sessionAllow.add(target.tool.name)}let persisted=false;if(typeof answer==="object"&&answer.kind==="persist"&&noAlwaysReason===null&&persistOptions.some(o=>o.rule===answer.rule)&&deps.
83
83
  persistAllow){persisted=await deps.persistAllow(answer.rule);if(persisted)deps.sessionRules?.push(answer.rule)}const how=answer==="always"?"\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u4ECA\u5F8C\u805E\u304B\u306A\u3044\uFF09":typeof answer==="object"&&answer.kind==="persist"?persisted?`\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u306F\u4ECA\u5F8C\u805E\u304B\u306A\u3044: ${answer.rule}\uFF09`:"\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u4ECA\u5F8C\u805E\u304B\u306A\u3044\u306E\u4FDD\u5B58\u306F\u884C\u308F\u306A\u304B\u3063\u305F\uFF09":
84
84
  "\u5229\u7528\u8005\u304C\u627F\u8A8D";recordDecision("allow","user_approved",`${how}\uFF08\u78BA\u8A8D\u306E\u7406\u7531: ${verdict.reason}\uFF09`)}}else{recordDecision("allow",reasonCodeOf(verdict),verdict.reason)}deps.onStart?.(tool,preview);try{const result=await tool.run(input,deps.ctx);deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:result.isError===true?"error":"ok",bytes:Buffer.byteLength(result.content),mode:deps.mode.id,callId});return{summary:preview,...result}}catch(err){
85
- if(err instanceof PathDeniedError){deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"denied",bytes:Buffer.byteLength(err.message),mode:deps.mode.id,reasonCode:"path_denied",callId});return{content:err.message,isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF09`}}const message=`${tool.name} failed: ${err.message}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"error",bytes:Buffer.byteLength(
86
- message),mode:deps.mode.id,callId});return{content:message,isError:true,summary:`${tool.name} \xB7 \u30A8\u30E9\u30FC`}}}function reasonCodeOf(verdict){switch(verdict.source){case"mode":case"default":return"mode_policy";case"permission_mode":return"permission_mode";case"session":return"session_allow";case"broken_settings":return"broken_settings";case"indirect_unresolved":case"indirect_self":return"indirect_unresolved";case"cli":case"local":case"project":case"user_project":case"user":return"setti\
87
- ngs_rule";default:{const exhaustive=verdict.source;return exhaustive}}}function denyMessage(name,verdict,deps){switch(verdict.source){case"mode":case"default":return`permission denied: ${name} is not available in ${deps.mode.id} mode.`;case"permission_mode":return`permission denied: ${name} is blocked by --permission-mode=${deps.permissionMode??""}.`;case"indirect_unresolved":case"indirect_self":return`permission denied: ${verdict.reason}`;case"project":case"local":return`permission denied: ${name}\
88
- is blocked by a permission rule in the project settings (.twp/).`;default:return`permission denied: ${name} is blocked by the permission rule ${verdict.rule??verdict.reason}.`}}function denySummary(verdict,deps){switch(verdict.source){case"mode":case"default":return`${deps.mode.label}\u30E2\u30FC\u30C9`;case"permission_mode":return`--permission-mode=${deps.permissionMode??""}`;case"indirect_unresolved":case"indirect_self":return"\u5B9F\u884C\u5BFE\u8C61\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044";default:
85
+ if(err instanceof PathDeniedError){deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"denied",bytes:Buffer.byteLength(err.message),mode:deps.mode.id,reasonCode:"path_denied",callId});return{content:err.message,isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF09`}}const message=`${tool.name} failed: ${redactPaths(err.message,deps.ctx.cwd)}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"erro\
86
+ r",bytes:Buffer.byteLength(message),mode:deps.mode.id,callId});return{content:message,isError:true,summary:`${tool.name} \xB7 \u30A8\u30E9\u30FC`}}}function reasonCodeOf(verdict){switch(verdict.source){case"mode":case"default":return"mode_policy";case"permission_mode":return"permission_mode";case"session":return"session_allow";case"broken_settings":return"broken_settings";case"indirect_unresolved":case"indirect_self":return"indirect_unresolved";case"cli":case"local":case"project":case"user_proje\
87
+ ct":case"user":return"settings_rule";default:{const exhaustive=verdict.source;return exhaustive}}}function denyMessage(name,verdict,deps){switch(verdict.source){case"mode":case"default":return`permission denied: ${name} is not available in ${deps.mode.id} mode.`;case"permission_mode":return`permission denied: ${name} is blocked by --permission-mode=${deps.permissionMode??""}.`;case"indirect_unresolved":case"indirect_self":return`permission denied: ${verdict.reason}`;case"project":case"local":return`\
88
+ permission denied: ${name} is blocked by a permission rule in the project settings (.twp/).`;default:return`permission denied: ${name} is blocked by the permission rule ${verdict.rule??verdict.reason}.`}}function denySummary(verdict,deps){switch(verdict.source){case"mode":case"default":return`${deps.mode.label}\u30E2\u30FC\u30C9`;case"permission_mode":return`--permission-mode=${deps.permissionMode??""}`;case"indirect_unresolved":case"indirect_self":return"\u5B9F\u884C\u5BFE\u8C61\u3092\u7279\u5B9A\u3067\u304D\u306A\u3044";default:
89
89
  return`\u30EB\u30FC\u30EB ${verdict.rule??""}`}}function safePreview(tool,input){try{return tool.preview(input)}catch{return tool.name}}function toWireTool(def){return{name:def.name,description:def.description,input_schema:def.inputSchema}}var DEFAULT_MAX_STEPS=24;function buildSystemPrompt(ctx){const tools=ctx.toolNames??[];const capability=tools.length===0?["- **\u30C4\u30FC\u30EB\u5B9F\u884C\u306F\u307E\u3060\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002** \u30D5\u30A1\u30A4\u30EB\u306E\u8AAD\u307F\u66F8\u304D\u30FB\u30B3\u30DE\u30F3\u30C9\u5B9F\u884C\u30FBTWP API \u64CD\u4F5C\u30FBWeb \u691C\u7D22\u306F\u3044\u305A\u308C\u3082\u884C\u3048\u307E\u305B\u3093","- \u5B9F\u884C\u304C\u5FC5\u8981\u306A\u3053\u3068\u306F\u3001\u5229\u7528\u8005\u304C\u81EA\u5206\u3067\u5B9F\u884C\u3067\u304D\u308B\u30B3\u30DE\u30F3\u30C9\u3084\u624B\u9806\u3068\u3057\u3066\u63D0\u793A\u3057\u3066\u304F\u3060\u3055\u3044"]:
90
90
  [`- \u4F7F\u3048\u308B\u30C4\u30FC\u30EB: ${tools.join(" / ")}`,"- **\u63A8\u6E2C\u3067\u7B54\u3048\u305A\u3001\u307E\u305A\u30C4\u30FC\u30EB\u3067\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002** \u30D5\u30A1\u30A4\u30EB\u306E\u5185\u5BB9\u30FB\u30B3\u30DE\u30F3\u30C9\u306E\u7D50\u679C\u30FB\u73FE\u5728\u306E\u72B6\u614B\u306F\u3059\u3079\u3066\u5B9F\u969B\u306B\u8AAD\u3093\u3067\u304B\u3089\u7B54\u3048\u307E\u3059","- \u4E00\u5EA6\u306B1\u3064\u305A\u3064\u78BA\u304B\u3081\u3001\u7D50\u679C\u3092\u898B\u3066\u304B\u3089\u6B21\u3092\u6C7A\u3081\u3066\u304F\u3060\u3055\u3044",
91
91
  "- \u30C4\u30FC\u30EB\u304C\u62D2\u5426\u3055\u308C\u305F\uFF08permission denied\uFF09\u3068\u304D\u306F\u3001\u540C\u3058\u547C\u3073\u51FA\u3057\u3092\u7E70\u308A\u8FD4\u3055\u305A\u3001\u4F55\u3092\u3057\u305F\u3044\u306E\u304B\u3092\u5229\u7528\u8005\u306B\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044\u3002**\u305F\u3060\u3057\u62D2\u5426\u306E\u7D50\u679C\u306B\u5229\u7528\u8005\u306E\u4EE3\u308F\u308A\u306E\u6307\u793A\uFF08asked you to do this instead\uFF09\u304C\u4ED8\u3044\u3066\u3044\u308C\u3070\u3001\u8AAC\u660E\u3067\u306F\u306A\u304F\u305D\u306E\u6307\u793A\u306B\u5F93\u3063\u3066\u304F\u3060\u3055\u3044**"];
@@ -162,44 +162,46 @@ value)))}function runCommand(choice,command,timeoutMs,cwd,signal,env=process.env
162
162
  clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const raw=Buffer.concat(chunks);const kept=keepTailBytes(raw,MAX_OUTPUT_BYTES);const body=kept.text;const head=kept.droppedBytes>0?`[output truncated: dropped the first ${kept.droppedBytes} bytes, showing the last ${Buffer.byteLength(body,"utf8")}]
163
163
  `:"";if(spawnError){resolve4({content:`Failed to start ${choice.command}: ${spawnError.message}`,isError:true,summary:`${choice.toolName} \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093`});return}if(outcome==="timeout"){resolve4({content:`${head}${body}
164
164
  [timed out after ${timeoutMs}ms and was killed]`,isError:true,summary:`${choice.toolName} \xB7 \u30BF\u30A4\u30E0\u30A2\u30A6\u30C8 (${timeoutMs}ms)`});return}if(outcome==="aborted"){resolve4({content:`${head}${body}
165
- [interrupted by the user]`,isError:true,summary:`${choice.toolName} \xB7 \u4E2D\u65AD`});return}resolve4({content:body===""?`(no output, exit code ${exitCode??0})`:`${head}${body}`,...exitCode!==0?{isError:true}:{},summary:`${choice.toolName} \xB7 exit ${exitCode??0}`})};child.on("error",err=>finish(null,err));child.on("close",code=>finish(code))})}import{readFile,writeFile}from"fs/promises";function detectEol(text){let crlf=0;let lf=0;for(let i=0;i<text.length;i++){if(text.charCodeAt(i)!==10)continue;if(i>0&&text.charCodeAt(i-1)===13)crlf++;else lf++}return crlf>lf?"\r\n":"\n"}function toLf(text){return text.replace(/\r\n/g,"\n")}function applyEol(text,eol){if(eol==="\n")return toLf(text);return toLf(text).replace(/\n/g,"\r\n")}var editFileTool={name:"edit_file",domain:"local",risk:"write",description:"Replace an exact string in a file. old_string must match exactly and be unique unless replace_all is true. Read the file first \u2014 the match includes indentation. Line endings of the file are preserved.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},old_string:{type:"string",description:"Exact text to replace (without l\
165
+ [interrupted by the user]`,isError:true,summary:`${choice.toolName} \xB7 \u4E2D\u65AD`});return}resolve4({content:body===""?`(no output, exit code ${exitCode??0})`:`${head}${body}`,...exitCode!==0?{isError:true}:{},summary:`${choice.toolName} \xB7 exit ${exitCode??0}`})};child.on("error",err=>finish(null,err));child.on("close",code=>finish(code))})}function detectEol(text){let crlf=0;let lf=0;for(let i=0;i<text.length;i++){if(text.charCodeAt(i)!==10)continue;if(i>0&&text.charCodeAt(i-1)===13)crlf++;else lf++}return crlf>lf?"\r\n":"\n"}function toLf(text){return text.replace(/\r\n/g,"\n")}function applyEol(text,eol){if(eol==="\n")return toLf(text);return toLf(text).replace(/\n/g,"\r\n")}var editFileTool={name:"edit_file",domain:"local",risk:"write",description:"Replace an exact string in a file. old_string must match exactly and be unique unless replace_all is true. Read the file first \u2014 the match includes indentation. Line endings of the file are preserved.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},old_string:{type:"string",description:"Exact text to replace (without l\
166
166
  ine-number prefixes)"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence instead of requiring uniqueness",default:false}},required:["path","old_string","new_string"]},preview(input){const old=typeof input["old_string"]==="string"?input["old_string"]:"";const head=old.split("\n")[0]??"";return`edit_file \xB7 ${String(input["path"]??"")} \xB7 ${head.slice(0,48)}${head.length>48?"\u2026":""}`},async prepare(input,ctx){const abs=resolveToolPath(
167
- String(input["path"]),ctx.cwd);const before=await readFile(abs,"utf8").catch(()=>null);if(before===null)return null;const applied=apply(before,input);if(!applied.ok)return null;return{path:toolRelative(ctx.cwd,abs),before,after:applied.after}},async run(input,ctx){const abs=resolveToolPath(String(input["path"]),ctx.cwd);const before=await readFile(abs,"utf8").catch(()=>null);if(before===null)return{content:`File not found: ${input["path"]}`,isError:true};const applied=apply(before,input);if(!applied.
168
- ok)return{content:applied.error,isError:true};await writeFile(abs,applied.after,"utf8");const rel=toolRelative(ctx.cwd,abs);return{content:`Edited ${rel} (${applied.count} replacement${applied.count===1?"":"s"}).`,summary:`edit_file \xB7 ${rel}`,diff:{path:rel,before,after:applied.after}}}};function apply(before,input){const eol=detectEol(before);const oldRaw=String(input["old_string"]);const newRaw=String(input["new_string"]);const replaceAll=input["replace_all"]===true;if(oldRaw==="")return{ok:false,
169
- error:"old_string must not be empty"};if(oldRaw===newRaw)return{ok:false,error:"old_string and new_string are identical"};const candidates=eol==="\r\n"?[applyEol(oldRaw,eol),oldRaw]:[oldRaw];for(const needle of candidates){const count=countOccurrences(before,needle);if(count===0)continue;if(count>1&&!replaceAll){return{ok:false,error:`old_string occurs ${count} times. Provide more surrounding context to make it unique, or set replace_all: true.`}}const replacement=applyEol(newRaw,eol);const after=replaceAll?
170
- before.split(needle).join(replacement):replaceOnce(before,needle,replacement);return{ok:true,after,count}}return{ok:false,error:"old_string not found in the file. Read the file again \u2014 whitespace and indentation must match exactly."}}function countOccurrences(haystack,needle){let count=0;let from=0;for(;;){const at=haystack.indexOf(needle,from);if(at===-1)return count;count+=1;from=at+needle.length}}function replaceOnce(haystack,needle,replacement){const at=haystack.indexOf(needle);return haystack.
171
- slice(0,at)+replacement+haystack.slice(at+needle.length)}import{spawn as spawn2}from"child_process";import path7 from"path";var GIT_TIMEOUT_MS=6e4;var MAX_GIT_OUTPUT_BYTES=1e5;var READ_ONLY_SUBCOMMANDS=["blame","branch","describe","diff","log","ls-files","rev-parse","shortlog","show","status","tag"];var DENIED_ARGS=new Set(["--no-index","-c","--config-env","--upload-pack","--receive-pack","--exec","--output","--ext-diff","--textconv"]);var FORCED_ARGS={diff:["--no-ext-diff","--no-textconv"],log:["--no-ext-diff","--no-textconv"],show:["--no-ext-diff","--no-textconv"],blame:["--no-textconv"]};function isStatusVerbose(arg){
167
+ String(input["path"]),ctx.cwd);const before=await readPlain(abs,String(input["path"])).catch(()=>null);if(before===null)return null;const applied=apply(before,input);if(!applied.ok)return null;return{path:toolRelative(ctx.cwd,abs),before,after:applied.after}},async run(input,ctx){const reported=String(input["path"]);const abs=resolveToolPath(reported,ctx.cwd);const handle=await openPlainFile(abs,reported,"update").catch(err=>{const code=err.code;if(code==="ENOTDIR"||code==="EISDIR")return null;throw err});
168
+ if(handle===null)return{content:`File not found: ${reported}`,isError:true};let before;let applied;try{before=await handle.readFile("utf8");applied=apply(before,input);if(applied.ok)await replaceContent(handle,applied.after)}finally{await handle.close()}if(!applied.ok)return{content:applied.error,isError:true};const rel=toolRelative(ctx.cwd,abs);return{content:`Edited ${rel} (${applied.count} replacement${applied.count===1?"":"s"}).`,summary:`edit_file \xB7 ${rel}`,diff:{path:rel,before,after:applied.
169
+ after}}}};async function readPlain(abs,reported){const handle=await openPlainFile(abs,reported,"read");if(handle===null)return null;try{return await handle.readFile("utf8")}finally{await handle.close()}}function apply(before,input){const eol=detectEol(before);const oldRaw=String(input["old_string"]);const newRaw=String(input["new_string"]);const replaceAll=input["replace_all"]===true;if(oldRaw==="")return{ok:false,error:"old_string must not be empty"};if(oldRaw===newRaw)return{ok:false,error:"ol\
170
+ d_string and new_string are identical"};const candidates=eol==="\r\n"?[applyEol(oldRaw,eol),oldRaw]:[oldRaw];for(const needle of candidates){const count=countOccurrences(before,needle);if(count===0)continue;if(count>1&&!replaceAll){return{ok:false,error:`old_string occurs ${count} times. Provide more surrounding context to make it unique, or set replace_all: true.`}}const replacement=applyEol(newRaw,eol);const after=replaceAll?before.split(needle).join(replacement):replaceOnce(before,needle,replacement);
171
+ return{ok:true,after,count}}return{ok:false,error:"old_string not found in the file. Read the file again \u2014 whitespace and indentation must match exactly."}}function countOccurrences(haystack,needle){let count=0;let from=0;for(;;){const at=haystack.indexOf(needle,from);if(at===-1)return count;count+=1;from=at+needle.length}}function replaceOnce(haystack,needle,replacement){const at=haystack.indexOf(needle);return haystack.slice(0,at)+replacement+haystack.slice(at+needle.length)}import{spawn as spawn2}from"child_process";import path7 from"path";var GIT_TIMEOUT_MS=6e4;var MAX_GIT_OUTPUT_BYTES=1e5;var READ_ONLY_SUBCOMMANDS=["blame","branch","describe","diff","log","ls-files","rev-parse","shortlog","show","status","tag"];var DENIED_ARGS=new Set(["--no-index","-c","--config-env","--upload-pack","--receive-pack","--exec","--output","--ext-diff","--textconv"]);var FORCED_ARGS={diff:["--no-ext-diff","--no-textconv"],log:["--no-ext-diff","--no-textconv"],show:["--no-ext-diff","--no-textconv"],blame:["--no-textconv"]};function isStatusVerbose(arg){
172
172
  if(arg.startsWith("--")){const head=arg.split("=")[0]??arg;return head.length>2&&"--verbose".startsWith(head)}return/^-[A-Za-z]*v/.test(arg)}function buildGitArgv(sub,args){const head=LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list"]:[sub];return[...head,...FORCED_ARGS[sub]??[],...args]}var LIST_ONLY_SUBCOMMANDS=new Set(["branch","tag"]);var gitTool={name:"git",domain:"local",risk:"exec",description:`Run a read-only git command. Allowed subcommands: ${READ_ONLY_SUBCOMMANDS.join(", ")}. Writing opera\
173
173
  tions (commit, push, checkout, add, ...) are not available here \u2014 use bash for those, which goes through the permission prompt.`,inputSchema:{type:"object",additionalProperties:false,properties:{subcommand:{type:"string",description:'The git subcommand, e.g. "log"',enum:[...READ_ONLY_SUBCOMMANDS]},args:{type:"array",description:'Arguments, e.g. ["--oneline", "-20"]. Each element is passed as a separate argv entry.',items:{type:"string"}}},required:["subcommand"]},execCommands(input){const sub=String(
174
174
  input["subcommand"]??"");const args=Array.isArray(input["args"])?input["args"].map(String):[];return{argv:[["git",...buildGitArgv(sub,args)]]}},preview(input){const args=Array.isArray(input["args"])?input["args"].map(String):[];return`git \xB7 ${String(input["subcommand"]??"")} ${args.join(" ")}`.trim()},async run(input,ctx){const sub=String(input["subcommand"]);if(!READ_ONLY_SUBCOMMANDS.includes(sub)){return{content:`git ${sub} is not available (read-only subcommands only: ${READ_ONLY_SUBCOMMANDS.
175
175
  join(", ")}). Use bash for write operations.`,isError:true}}const args=Array.isArray(input["args"])?input["args"].map(String):[];for(const arg of args){const head=arg.split("=")[0]??arg;if(DENIED_ARGS.has(head)){return{content:`Argument ${arg} is not allowed for the git tool.`,isError:true}}if(sub==="status"&&isStatusVerbose(arg)){return{content:`Argument ${arg} is not allowed for git status (it renders diffs through the repository's textconv drivers). Use the git tool's diff subcommand with --c\
176
176
  ached instead.`,isError:true}}}const argv=buildGitArgv(sub,args);const env=ctx.env??process.env;const exe=resolveGitExecutable({env});if(exe===null){return{content:'git executable was not found on PATH. On Windows the git tool resolves the executable to an absolute path from PATH (it never runs a bare "git", because Windows searches the current directory before PATH). Install Git for Windows or add its bin directory to PATH.',isError:true,summary:"git \xB7 \u5B9F\u884C\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"}}
177
- return runGit(exe,argv,ctx.cwd,env,ctx.signal)}};function resolveGitExecutable(deps={}){const platform=deps.platform??process.platform;if(platform!=="win32")return"git";const env=deps.env??process.env;const common={platform,...deps.isExecutableFile!==void 0?{isExecutableFile:deps.isExecutableFile}:{}};const spawnable=findExecutable("git",{...common,env:{...env,PATHEXT:".EXE;.COM"}});return spawnable??findExecutable("git",{...common,env})}function runGit(exe,argv,cwd,baseEnv,signal){return new Promise(
178
- resolve4=>{let child;try{child=spawn2(exe,["--no-pager",...argv],{cwd,shell:false,env:{...baseEnv,GIT_PAGER:"cat",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true"},detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch(e){const err=e;const name=path7.basename(exe);resolve4({content:err.code==="EINVAL"?`Failed to start git: the resolved executable (${name}) is a .cmd/.bat shim, which Node refuses to spawn without a shell. Install Git for Windows (which provi\
179
- des git.exe) or put its bin directory earlier on PATH.`:`Failed to start git (${name}): ${err.code??"unknown error"}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_GIT_OUTPUT_BYTES*2&&chunks.length>1){const dropped=chunks.shift();if(!dropped)break;bytes-=dropped.length}};child.stdout?.on("data",collect);child.stderr?.on("data",collect);let timedOut=false;
180
- const timer=setTimeout(()=>{timedOut=true;killProcessTree(child,"SIGKILL")},GIT_TIMEOUT_MS);const onAbort=()=>{killProcessTree(child,"SIGKILL")};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(code,err)=>{clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const kept=keepTailBytes(Buffer.concat(chunks),MAX_GIT_OUTPUT_BYTES);const body=kept.text;const note=kept.droppedBytes>0?`
177
+ const result=await runGit(exe,argv,ctx.cwd,env,ctx.signal);return{...result,content:redactPaths(result.content,ctx.cwd)}}};function resolveGitExecutable(deps={}){const platform=deps.platform??process.platform;if(platform!=="win32")return"git";const env=deps.env??process.env;const common={platform,...deps.isExecutableFile!==void 0?{isExecutableFile:deps.isExecutableFile}:{}};const spawnable=findExecutable("git",{...common,env:{...env,PATHEXT:".EXE;.COM"}});return spawnable??findExecutable("git",{
178
+ ...common,env})}function runGit(exe,argv,cwd,baseEnv,signal){return new Promise(resolve4=>{let child;try{child=spawn2(exe,["--no-pager",...argv],{cwd,shell:false,env:{...baseEnv,GIT_PAGER:"cat",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true"},detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch(e){const err=e;const name=path7.basename(exe);resolve4({content:err.code==="EINVAL"?`Failed to start git: the resolved executable (${name}) is a .cmd/.bat shim, w\
179
+ hich Node refuses to spawn without a shell. Install Git for Windows (which provides git.exe) or put its bin directory earlier on PATH.`:`Failed to start git (${name}): ${err.code??"unknown error"}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_GIT_OUTPUT_BYTES*2&&chunks.length>1){const dropped=chunks.shift();if(!dropped)break;bytes-=dropped.
180
+ length}};child.stdout?.on("data",collect);child.stderr?.on("data",collect);let timedOut=false;const timer=setTimeout(()=>{timedOut=true;killProcessTree(child,"SIGKILL")},GIT_TIMEOUT_MS);const onAbort=()=>{killProcessTree(child,"SIGKILL")};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(code,err)=>{clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const kept=keepTailBytes(Buffer.concat(chunks),MAX_GIT_OUTPUT_BYTES);const body=kept.
181
+ text;const note=kept.droppedBytes>0?`
181
182
  [output truncated: dropped the first ${kept.droppedBytes} bytes]`:"";if(err){resolve4({content:`Failed to run git (${path7.basename(exe)}): ${err.code??err.message}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}if(timedOut){resolve4({content:`${body}${note}
182
183
  [timed out after ${GIT_TIMEOUT_MS}ms]`,isError:true,summary:"git \xB7 \u30BF\u30A4\u30E0\u30A2\u30A6\u30C8"});return}resolve4({content:body===""?`(no output, exit code ${code??0})`:`${body}${note}`,...code!==0?{isError:true}:{},summary:`git ${argv[0]??""} \xB7 exit ${code??0}`})};child.on("error",e=>finish(null,e));child.on("close",code=>finish(code))})}import{glob}from"fs/promises";import{resolve as resolve2}from"path";var MAX_GLOB_RESULTS=500;var DEFAULT_EXCLUDES=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/vendor/**"];var globTool={name:"glob",domain:"local",risk:"read",description:'Find files by glob pattern (e.g. "src/**/*.ts"). Returns paths relative to the working directory, sorted. node_modules, .git, dist, .next and vendor are excluded by default.',inputSchema:{type:"object",additionalProperties:false,properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.test.ts"'},
183
184
  path:{type:"string",description:"Directory to search in (default: the working directory)"},include_ignored:{type:"boolean",description:"Include node_modules / dist / vendor etc.",default:false}},required:["pattern"]},preview(input){return`glob \xB7 ${String(input["pattern"]??"")}`},async run(input,ctx){const root=input["path"]===void 0?resolve2(ctx.cwd):resolveToolPath(String(input["path"]),ctx.cwd);const pattern=String(input["pattern"]);const exclude=input["include_ignored"]===true?[]:DEFAULT_EXCLUDES;
184
- const found=[];let hardStop=false;let skipped=0;try{for await(const entry of glob(pattern,{cwd:root,exclude})){const abs=resolve2(root,typeof entry==="string"?entry:String(entry));if(!isInsideCwd(abs,ctx.cwd)||secretReason(abs)!==null){skipped+=1;continue}found.push(abs);if(found.length>=MAX_GLOB_RESULTS*4){hardStop=true;break}}}catch(err){return{content:`glob failed: ${err.message}`,isError:true}}const sorted=found.map(abs=>toolRelative(ctx.cwd,abs)).sort();const shown=sorted.slice(0,MAX_GLOB_RESULTS);
185
- const note=hardStop?`
185
+ const found=[];let hardStop=false;let skipped=0;try{for await(const entry of glob(pattern,{cwd:root,exclude})){const abs=resolve2(root,typeof entry==="string"?entry:String(entry));if(!isInsideCwd(abs,ctx.cwd)||secretReason(abs)!==null||isGitMetadata(abs,ctx.cwd)){skipped+=1;continue}found.push(abs);if(found.length>=MAX_GLOB_RESULTS*4){hardStop=true;break}}}catch(err){return{content:`glob failed: ${redactPaths(err.message,ctx.cwd)}`,isError:true}}const sorted=found.map(abs=>toolRelative(ctx.cwd,abs)).
186
+ sort();const shown=sorted.slice(0,MAX_GLOB_RESULTS);const note=hardStop?`
186
187
  [stopped scanning after ${found.length} matches \u2014 there may be many more. Narrow the pattern.]`:sorted.length>shown.length?`
187
188
  [${sorted.length-shown.length} more matches not shown \u2014 narrow the pattern]`:"";const denied=skipped>0?`
188
- [${skipped} path(s) outside the working directory or denied were omitted]`:"";return{content:shown.length===0?`No files matched ${pattern}${denied}`:shown.join("\n")+note+denied,summary:`glob \xB7 ${pattern} \u2192 ${shown.length}\u4EF6`}}};import{glob as glob2}from"fs/promises";import{readFile as readFile2}from"fs/promises";import{resolve as resolve3}from"path";var MAX_GREP_MATCHES=200;var MAX_GREP_RESULTS_LIMIT=2e3;var MAX_LINE_LENGTH=2e4;var GREP_DEADLINE_MS=2e4;var MAX_FILE_BYTES2=2e6;var DEFAULT_EXCLUDES2=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/vendor/**"];var grepTool={name:"grep",domain:"local",risk:"read",description:'Search file contents with a JavaScript regular expression. Returns "path:line: text" for each match. Use the glob parameter to limit which files are searched.',inputSchema:{type:"object",additionalProperties:false,
189
+ [${skipped} path(s) outside the working directory or denied were omitted]`:"";return{content:shown.length===0?`No files matched ${pattern}${denied}`:shown.join("\n")+note+denied,summary:`glob \xB7 ${pattern} \u2192 ${shown.length}\u4EF6`}}};import{glob as glob2}from"fs/promises";import{readFile}from"fs/promises";import{resolve as resolve3}from"path";var MAX_GREP_MATCHES=200;var MAX_GREP_RESULTS_LIMIT=2e3;var MAX_LINE_LENGTH=2e4;var GREP_DEADLINE_MS=2e4;var MAX_FILE_BYTES2=2e6;var DEFAULT_EXCLUDES2=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/vendor/**"];var grepTool={name:"grep",domain:"local",risk:"read",description:'Search file contents with a JavaScript regular expression. Returns "path:line: text" for each match. Use the glob parameter to limit which files are searched.',inputSchema:{type:"object",additionalProperties:false,
189
190
  properties:{pattern:{type:"string",description:"JavaScript regular expression"},path:{type:"string",description:"Directory to search in (default: the working directory)"},glob:{type:"string",description:'Limit to files matching this glob, e.g. "**/*.ts"',default:"**/*"},ignore_case:{type:"boolean",description:"Case-insensitive match",default:false},max_results:{type:"integer",description:`Maximum matches (default ${MAX_GREP_MATCHES}, max ${MAX_GREP_RESULTS_LIMIT})`,minimum:1,maximum:MAX_GREP_RESULTS_LIMIT}},
190
191
  required:["pattern"]},preview(input){return`grep \xB7 /${String(input["pattern"]??"")}/ ${String(input["glob"]??"")}`.trim()},async run(input,ctx){let re;try{re=new RegExp(String(input["pattern"]),input["ignore_case"]===true?"i":"")}catch(err){return{content:`Invalid regular expression: ${err.message}`,isError:true}}const root=input["path"]===void 0?resolve3(ctx.cwd):resolveToolPath(String(input["path"]),ctx.cwd);const filePattern=typeof input["glob"]==="string"?input["glob"]:"**/*";const limit=typeof input["\
191
192
  max_results"]==="number"?Math.min(MAX_GREP_RESULTS_LIMIT,Math.max(1,Math.floor(input["max_results"]))):MAX_GREP_MATCHES;const matches=[];let scanned=0;let skipped=0;let longLines=0;let hitLimit=false;let timedOut=false;const deadline=Date.now()+GREP_DEADLINE_MS;const aborted=()=>ctx.signal?.aborted===true;try{for await(const entry of glob2(filePattern,{cwd:root,exclude:DEFAULT_EXCLUDES2})){if(aborted())break;const abs=resolve3(root,typeof entry==="string"?entry:String(entry));if(!isInsideCwd(abs,
192
- ctx.cwd)||secretReason(abs)!==null){skipped+=1;continue}const buf=await readFile2(abs).catch(()=>null);if(buf===null||buf.length>MAX_FILE_BYTES2||buf.includes(0))continue;scanned+=1;const rel=toolRelative(ctx.cwd,abs);const lines=toLf(buf.toString("utf8")).split("\n");for(let i=0;i<lines.length;i++){if(aborted())break;if(Date.now()>deadline){timedOut=true;break}const line=lines[i]??"";if(line.length>MAX_LINE_LENGTH){longLines+=1;continue}if(!re.test(line))continue;matches.push(`${rel}:${i+1}: ${line.
193
- slice(0,400)}`);if(matches.length>=limit){hitLimit=true;break}}if(hitLimit||timedOut||aborted())break}}catch(err){return{content:`grep failed: ${err.message}`,isError:true}}const notes=[hitLimit?`[stopped at ${limit} matches \u2014 narrow the pattern or the glob]`:"",timedOut?`[stopped after ${GREP_DEADLINE_MS}ms \u2014 narrow the glob]`:"",longLines>0?`[${longLines} line(s) longer than ${MAX_LINE_LENGTH} chars were not searched]`:"",skipped>0?`[${skipped} path(s) outside the working directory o\
194
- r denied were omitted]`:""].filter(n=>n!=="");const suffix=notes.length>0?`
195
- ${notes.join("\n")}`:"";return{content:matches.length===0?`No matches in ${scanned} files.${suffix}`:matches.join("\n")+suffix,summary:`grep \xB7 ${matches.length}\u4EF6 / ${scanned}\u30D5\u30A1\u30A4\u30EB`}}};import{readFile as readFile3,stat}from"fs/promises";var MAX_READ_BYTES=2e5;var DEFAULT_LIMIT_LINES=2e3;var readFileTool={name:"read_file",domain:"local",risk:"read",description:"Read a UTF-8 text file from the working directory. Returns the content with 1-based line numbers. Use offset/limit for large files. Binary files are not returned.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},offset:{type:"integer",description:"1-based line to start from",
196
- minimum:1},limit:{type:"integer",description:`Maximum lines to return (default ${DEFAULT_LIMIT_LINES})`,minimum:1}},required:["path"]},preview(input){return`read_file \xB7 ${String(input["path"]??"")}`},async run(input,ctx){const abs=resolveToolPath(String(input["path"]),ctx.cwd);const info=await stat(abs).catch(()=>null);if(info===null)return{content:`File not found: ${input["path"]}`,isError:true};if(info.isDirectory()){return{content:`${input["path"]} is a directory. Use glob to list its cont\
197
- ents.`,isError:true}}const buf=await readFile3(abs);if(buf.includes(0)){return{content:`Binary file (${info.size} bytes) \u2014 not returned. Use bash if you need to inspect it.`,isError:true,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (binary)`}}const raw=buf.toString("utf8");const eol=detectEol(raw);const lines=toLf(raw).split("\n");if(lines[lines.length-1]==="")lines.pop();const offset=typeof input["offset"]==="number"?input["offset"]:1;const limit=typeof input["limit"]==="number"?input["\
198
- limit"]:DEFAULT_LIMIT_LINES;const slice=lines.slice(offset-1,offset-1+limit);let body=slice.map((line,i)=>`${offset+i} ${line}`).join("\n");let truncated=offset-1+slice.length<lines.length;const clipped=keepHeadBytes(body,MAX_READ_BYTES);body=clipped.text;if(clipped.truncated)truncated=true;const note=truncated?`
193
+ ctx.cwd)||secretReason(abs)!==null||isGitMetadata(abs,ctx.cwd)){skipped+=1;continue}if(specialFileReason(abs)!==null){skipped+=1;continue}const buf=await readFile(abs).catch(()=>null);if(buf===null||buf.length>MAX_FILE_BYTES2||buf.includes(0))continue;scanned+=1;const rel=toolRelative(ctx.cwd,abs);const lines=toLf(buf.toString("utf8")).split("\n");for(let i=0;i<lines.length;i++){if(aborted())break;if(Date.now()>deadline){timedOut=true;break}const line=lines[i]??"";if(line.length>MAX_LINE_LENGTH){
194
+ longLines+=1;continue}if(!re.test(line))continue;matches.push(`${rel}:${i+1}: ${line.slice(0,400)}`);if(matches.length>=limit){hitLimit=true;break}}if(hitLimit||timedOut||aborted())break}}catch(err){return{content:`grep failed: ${redactPaths(err.message,ctx.cwd)}`,isError:true}}const notes=[hitLimit?`[stopped at ${limit} matches \u2014 narrow the pattern or the glob]`:"",timedOut?`[stopped after ${GREP_DEADLINE_MS}ms \u2014 narrow the glob]`:"",longLines>0?`[${longLines} line(s) longer than ${MAX_LINE_LENGTH}\
195
+ chars were not searched]`:"",skipped>0?`[${skipped} path(s) outside the working directory or denied were omitted]`:""].filter(n=>n!=="");const suffix=notes.length>0?`
196
+ ${notes.join("\n")}`:"";return{content:matches.length===0?`No matches in ${scanned} files.${suffix}`:matches.join("\n")+suffix,summary:`grep \xB7 ${matches.length}\u4EF6 / ${scanned}\u30D5\u30A1\u30A4\u30EB`}}};var MAX_READ_BYTES=2e5;var DEFAULT_LIMIT_LINES=2e3;var readFileTool={name:"read_file",domain:"local",risk:"read",description:"Read a UTF-8 text file from the working directory. Returns the content with 1-based line numbers. Use offset/limit for large files. Binary files are not returned.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},offset:{type:"integer",description:"1-based line to start from",
197
+ minimum:1},limit:{type:"integer",description:`Maximum lines to return (default ${DEFAULT_LIMIT_LINES})`,minimum:1}},required:["path"]},preview(input){return`read_file \xB7 ${String(input["path"]??"")}`},async run(input,ctx){const reported=String(input["path"]);const abs=resolveToolPath(reported,ctx.cwd);let handle;try{handle=await openPlainFile(abs,reported,"read")}catch(err){if(err.code==="EISDIR"){return{content:`${reported} is a directory. Use glob to list its contents.`,isError:true}}throw err}
198
+ if(handle===null)return{content:`File not found: ${reported}`,isError:true};let buf;let size;try{size=(await handle.stat()).size;buf=await handle.readFile()}finally{await handle.close()}const info={size};if(buf.includes(0)){return{content:`Binary file (${info.size} bytes) \u2014 not returned. Use bash if you need to inspect it.`,isError:true,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (binary)`}}const raw=buf.toString("utf8");const eol=detectEol(raw);const lines=toLf(raw).split("\n");if(lines[lines.
199
+ length-1]==="")lines.pop();const offset=typeof input["offset"]==="number"?input["offset"]:1;const limit=typeof input["limit"]==="number"?input["limit"]:DEFAULT_LIMIT_LINES;const slice=lines.slice(offset-1,offset-1+limit);let body=slice.map((line,i)=>`${offset+i} ${line}`).join("\n");let truncated=offset-1+slice.length<lines.length;const clipped=keepHeadBytes(body,MAX_READ_BYTES);body=clipped.text;if(clipped.truncated)truncated=true;const note=truncated?`
199
200
 
200
- [truncated: file has ${lines.length} lines; re-read with offset/limit for the rest]`:"";if(body===""){const reason=lines.length===0?"(empty file)":`(no lines at offset ${offset}; the file has ${lines.length} lines)`;return{content:reason,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (0 \u884C)`}}return{content:body+note,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (${slice.length} \u884C${eol==="\r\n"?" \xB7 CRLF":""})`}}};import{mkdir,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{dirname as dirname2}from"path";var writeFileTool={name:"write_file",domain:"local",risk:"write",description:"Write the full content of a file, creating it (and parent directories) if needed. Overwrites the whole file \u2014 prefer edit_file for partial changes. The existing line ending style (LF/CRLF) is preserved.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},content:{type:"string",description:"Full new content. Use \\n for li\
201
- 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["\
202
- 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(dirname2(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;
201
+ [truncated: file has ${lines.length} lines; re-read with offset/limit for the rest]`:"";if(body===""){const reason=lines.length===0?"(empty file)":`(no lines at offset ${offset}; the file has ${lines.length} lines)`;return{content:reason,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (0 \u884C)`}}return{content:body+note,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (${slice.length} \u884C${eol==="\r\n"?" \xB7 CRLF":""})`}}};import{mkdir,readFile as readFile2,stat}from"fs/promises";import{dirname as dirname2}from"path";var writeFileTool={name:"write_file",domain:"local",risk:"write",description:"Write the full content of a file, creating it (and parent directories) if needed. Overwrites the whole file \u2014 prefer edit_file for partial changes. The existing line ending style (LF/CRLF) is preserved.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},content:{type:"string",description:"Full new content. Use \\n for li\
202
+ 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 readFile2(abs,"utf8").catch(()=>"");return{path:toolRelative(ctx.cwd,abs),before,after:String(input["content"]??"")}},async run(input,ctx){const reported=String(input["path"]);const abs=resolveToolPath(
203
+ reported,ctx.cwd);const existed=await stat(abs).then(()=>true,()=>false);await mkdir(dirname2(abs),{recursive:true});const handle=await openPlainFile(abs,reported,"write");let existing;let body;let eol;try{existing=existed?await handle.readFile("utf8"):null;eol=existing===null?"\n":detectEol(existing);body=applyEol(String(input["content"]),eol);await replaceContent(handle,body)}finally{await handle.close()}const rel=toolRelative(ctx.cwd,abs);return{content:`Wrote ${rel} (${body.split(eol).length}\
204
+ 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;
203
205
  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,
204
206
  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}
205
207
  ${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\
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __twpCreateRequire } from 'node:module';
3
3
  const require = __twpCreateRequire(import.meta.url);
4
- import{taskLoopHelp}from"./chunk-3AY5P4CN.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-TZL2342W.js";import"./chunk-RMFLTSOV.js";import{parseArgv,quietFromEnv}from"./chunk-P75ML6PX.js";import"./chunk-2LOT54OO.js";import"./chunk-NJL3H2BB.js";import"./chunk-F3UL5POS.js";import"./chunk-MS52L74Z.js";import{formatUnknownArgs}from"./chunk-OKATZ4SN.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.155.0":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
4
+ import{taskLoopHelp}from"./chunk-3AY5P4CN.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-TZL2342W.js";import"./chunk-RMFLTSOV.js";import{parseArgv,quietFromEnv}from"./chunk-P75ML6PX.js";import"./chunk-2LOT54OO.js";import"./chunk-NJL3H2BB.js";import"./chunk-F3UL5POS.js";import"./chunk-MS52L74Z.js";import{formatUnknownArgs}from"./chunk-OKATZ4SN.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.155.1":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
5
5
 
6
6
  \u4F7F\u3044\u65B9:
7
7
  twp \u5BFE\u8A71 TUI \u3092\u8D77\u52D5
@@ -1997,18 +1997,18 @@ TUI \u5185:
1997
1997
  \u4F1A\u8A71\u30FB\u30ED\u30FC\u30AB\u30EB\u30C4\u30FC\u30EB\uFF08\u30D5\u30A1\u30A4\u30EB\u30FB\u30B3\u30DE\u30F3\u30C9\u30FBgit\uFF09\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u3067\u5B9F\u969B\u306B\u52D5\u304D\u307E\u3059\u3002
1998
1998
  `;function ignoreEpipe(stream){stream.on("error",err=>{if(err.code==="EPIPE")process.exit(0);throw err})}async function main(){const nodeMajor=Number(process.versions.node.split(".")[0]);if(nodeMajor<22){process.stderr.write(`twp-cli \u306B\u306F Node.js 22 \u4EE5\u4E0A\u304C\u5FC5\u8981\u3067\u3059\uFF08\u73FE\u5728: ${process.versions.node}\uFF09
1999
1999
  `);process.exit(1)}ignoreEpipe(process.stdout);ignoreEpipe(process.stderr);if(process.env["TWP_AUTO_UPDATE_WORKER"]==="1"){const{runAutoUpdateWorker}=await import("./auto-update-worker-TN322W34.js");await runAutoUpdateWorker().catch(()=>void 0);return}const[first,...rest]=process.argv.slice(2);if(first==="__complete"||first==="completion"){const completion=await import("./completion-EJ4OQYE2.js");if(first==="completion"){process.exitCode=completion.runCompletion(rest,process.stdout,process.stderr);return}
2000
- const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-IQJK4252.js"),import("./config-XYWRBIC6.js")]);process.exitCode=await completion.runComplete(rest,process.stdout,{loadDomain,profileNames:()=>Object.keys(loadUserConfig().profiles??{})});return}if(first==="local-loop"){process.env["TWP_NO_AUTO_UPDATE"]="1";const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();const{runLocalLoopCommand}=await import("./commands-2KPZQ5YY.js");process.
2001
- exitCode=await runLocalLoopCommand(rest);return}if(first==="github"&&(rest[0]==="git-credential"||rest[0]==="git-remote")){const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();const{runGithubGit}=await import("./github-git-CO36AUEV.js");process.exitCode=await runGithubGit(rest[0],rest.slice(1),{version:VERSION});return}if(first==="configure"){const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();autoUpdate2.onStartup(VERSION);
2000
+ const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-2SFZPFCO.js"),import("./config-XYWRBIC6.js")]);process.exitCode=await completion.runComplete(rest,process.stdout,{loadDomain,profileNames:()=>Object.keys(loadUserConfig().profiles??{})});return}if(first==="local-loop"){process.env["TWP_NO_AUTO_UPDATE"]="1";const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();const{runLocalLoopCommand}=await import("./commands-I7UXJVNC.js");process.
2001
+ exitCode=await runLocalLoopCommand(rest);return}if(first==="github"&&(rest[0]==="git-credential"||rest[0]==="git-remote")){const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();const{runGithubGit}=await import("./github-git-BFY5LRO4.js");process.exitCode=await runGithubGit(rest[0],rest.slice(1),{version:VERSION});return}if(first==="configure"){const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();autoUpdate2.onStartup(VERSION);
2002
2002
  const{runConfigure}=await import("./configure-BJGPASNG.js");process.exitCode=await runConfigure(rest);return}const args=parseArgv(process.argv.slice(2));if(args.command==="version"){process.stdout.write(`${VERSION}
2003
2003
  `);return}if(args.command==="help"){process.stdout.write(HELP);return}if(args.command==="task-loop"&&args.taskLoopHelp===true){process.stdout.write(taskLoopHelp(HELP,args.taskLoopActionExplicit===true?args.taskLoopAction:void 0));return}if(args.movedCommand!==void 0){const{MOVED_QUEUE_COMMAND_MESSAGE}=await import("./dispatch-2PH4GTLS.js");process.stderr.write(MOVED_QUEUE_COMMAND_MESSAGE);process.exitCode=2;return}if(args.unknown.length>0){process.stderr.write(`\u4E0D\u660E\u306A\u5F15\u6570: ${formatUnknownArgs(
2004
2004
  args.unknown)}
2005
2005
 
2006
- ${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-FXXQHBV5.js");autoUpdate.registerRunning();if(args.command==="task-loop"&&args.taskLoopAction!=="capacity"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-X5DTRFHA.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:
2007
- {},argv:args.domainArgv,help:args.domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-RMUNRSOF.js");process.exitCode=await runApiCommand({argv:args.domainArgv,help:args.domainHelp,
2006
+ ${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-FXXQHBV5.js");autoUpdate.registerRunning();if(args.command==="task-loop"&&args.taskLoopAction!=="capacity"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-GIXUKZEL.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:
2007
+ {},argv:args.domainArgv,help:args.domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-P4PDKC6C.js");process.exitCode=await runApiCommand({argv:args.domainArgv,help:args.domainHelp,
2008
2008
  globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="update"){const{runUpdate}=await import("./update-76KTMGPX.js");process.exitCode=await runUpdate({...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}if(args.command==="login"||args.
2009
2009
  command==="logout"||args.command==="whoami"){const{runLogin,runLogout,runWhoami}=await import("./commands-CS3NQGRL.js");const options={profile:args.profile,method:args.loginMethod,tenant:args.tenant,noBrowser:args.loginNoBrowser,start:args.loginStart,...args.loginCode!==void 0?{code:args.loginCode}:{},...args.loginCodeFile!==void 0?{codeFile:args.loginCodeFile}:{},cliVersion:VERSION,force:args.logoutForce,...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:
2010
2010
  {}};const runner=args.command==="login"?runLogin:args.command==="logout"?runLogout:runWhoami;process.exitCode=await runner(options);return}if(args.command==="task-loop"){const{runTaskLoop}=await import("./commands-XSYIAAWN.js");process.exitCode=await runTaskLoop({action:args.taskLoopAction??"run",project:args.project,profile:args.profile,safe:args.safe,daemon:args.daemon,interval:args.interval,maxCycles:args.maxCycles,forceRunner:args.forceRunner,force:args.stopForce,drain:args.stopDrain,engine:args.
2011
2011
  engine,version:VERSION,verbose:args.verbose,scheduleNow:args.scheduleNow,scheduleCounts:args.scheduleCounts,scheduleGate:args.scheduleGate,scheduleOp:args.scheduleOp,scheduleConfigOp:args.scheduleConfigOp,scheduleId:args.scheduleId,charterOp:args.charterOp,charterInput:args.charterFile,charterOutput:args.charterOut,charterRevision:args.charterRevision,settingsOp:args.settingsOp,orientationOp:args.orientationOp,orientationArgs:args.orientationArgs,skillOp:args.skillOp,skillName:args.skillName,skillAll:args.
2012
2012
  skillAll,skillDir:args.skillDir,skillConfig:args.skillConfig,output:args.output,query:args.query,revisionFrom:args.revisionFrom,revisionTo:args.revisionTo,planOp:args.planOp,capacityOp:args.capacityOp,includeStopped:args.includeStopped,runnerOp:args.runnerOp,runnerId:args.runnerTargetId,triggerOp:args.triggerOp,triggerId:args.triggerId,triggerKey:args.triggerKey,triggerLimit:args.triggerLimit,planEmpty:args.planEmpty,planCheck:args.planCheck,yes:args.yes,ais:args.ais,workspace:args.workspace,aiConfigFile:args.
2013
- aiConfigFile,noAiConfigFile:args.noAiConfigFile});return}if(args.command==="print"){const{runOneShot}=await import("./oneshot-JD72XG7S.js");process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.permissionMode}:{},allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,...args.inputFormat!==void 0?{inputFormat:args.inputFormat}:{},...args.outputFormat!==void 0?{outputFormat:args.
2014
- outputFormat}:{},...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-BPPQZMJP.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();
2013
+ aiConfigFile,noAiConfigFile:args.noAiConfigFile});return}if(args.command==="print"){const{runOneShot}=await import("./oneshot-5ZPBHIPU.js");process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.permissionMode}:{},allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,...args.inputFormat!==void 0?{inputFormat:args.inputFormat}:{},...args.outputFormat!==void 0?{outputFormat:args.
2014
+ outputFormat}:{},...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-YQF7Y2WF.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();
@@ -304,7 +304,7 @@ flags}}function numberFlag(p,name){const v=p.flags.get(name);if(v===void 0)retur
304
304
  \u3066\u304F\u3060\u3055\u3044"}return n}async function buildPublicOptions(p,env){const str=n=>{const v=p.flags.get(n);return typeof v==="string"?v:void 0};const publicUrl=str("--public-url");if(publicUrl===void 0)return"\u516C\u958B\u30E2\u30FC\u30C9\u306B\u306F --public-url\uFF08\u5916\u304B\u3089\u958B\u304F https:// \u306E URL\uFF09\u304C\u5FC5\u8981\u3067\u3059";const certPath=str("--tls-cert");const keyPath=str("--tls-key");if(certPath===void 0!==(keyPath===void 0))return"--tls-cert \u3068 --tl\
305
305
  s-key \u306F\u4E21\u65B9\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044";let tls;if(certPath!==void 0&&keyPath!==void 0){try{tls={cert:fs5.readFileSync(certPath,"utf8"),key:fs5.readFileSync(keyPath,"utf8")}}catch(e){return`\u8A3C\u660E\u66F8\u30FB\u9375\u3092\u8AAD\u3081\u307E\u305B\u3093\uFF08${e.message}\uFF09`}}const reauthRaw=str("--reauth-minutes");const reauth=reauthRaw===void 0?null:Number(reauthRaw);if(reauth!==null&&(!/^\d+$/.test(reauthRaw??"")||reauth<1||reauth>720))return"--reauth-m\
306
306
  inutes \u306F 1\u301C720 \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044";const allow=str("--allow-ip");const profile=str("--profile");const bind=str("--bind");const allowIps=allow!==void 0?allow.split(",").map(x=>x.trim()).filter(x=>x!==""):void 0;if(allowIps!==void 0&&allowIps.length===0)return"--allow-ip \u306B IP \u30A2\u30C9\u30EC\u30B9\u304C1\u3064\u3082\u3042\u308A\u307E\u305B\u3093";const opts={publicUrl,...tls?{tls}:{},behindTlsProxy:p.flags.get("--behind-tls-pr\
307
- oxy")===true,trustedProxy:p.flags.get("--trusted-proxy")===true,...allowIps!==void 0?{allowIps}:{},...bind!==void 0?{bindHost:bind}:{},...profile!==void 0?{profile}:{},...reauth!==null?{reauthWindowMs:reauth*6e4}:{},env,cliVersion:true?"0.155.0":"0.0.0-dev"};const{validatePublicOptions}=await import("./console-public-UWTESPQR.js");return validatePublicOptions(opts)??opts}function waitForSignal(){return new Promise(resolve=>{const done=()=>{process.removeListener("SIGINT",done);process.removeListener(
307
+ oxy")===true,trustedProxy:p.flags.get("--trusted-proxy")===true,...allowIps!==void 0?{allowIps}:{},...bind!==void 0?{bindHost:bind}:{},...profile!==void 0?{profile}:{},...reauth!==null?{reauthWindowMs:reauth*6e4}:{},env,cliVersion:true?"0.155.1":"0.0.0-dev"};const{validatePublicOptions}=await import("./console-public-UWTESPQR.js");return validatePublicOptions(opts)??opts}function waitForSignal(){return new Promise(resolve=>{const done=()=>{process.removeListener("SIGINT",done);process.removeListener(
308
308
  "SIGTERM",done);resolve()};process.once("SIGINT",done);process.once("SIGTERM",done)})}function lockDirOf(dir){return path5.join(dir,"lock")}function runningPid2(dir,isLoop){let pid;try{pid=Number.parseInt(fs5.readFileSync(path5.join(lockDirOf(dir),"pid"),"utf8").trim(),10)}catch{return null}if(!Number.isInteger(pid)||pid<=0)return null;return isLoop(pid)?pid:null}function protectedDeny(twpHome,cwd,home=os.homedir(),claudeConfigDir){const readWrite=[absPathRule(twpHome),absPathRule(path5.join(home,
309
309
  ".ssh")),absPathRule(path5.join(home,".claude")),absPathRule(path5.join(home,".claude.json"),""),...claudeConfigDir!==void 0&&claudeConfigDir.trim()!==""?[absPathRule(claudeConfigDir)]:[]];const writeOnly=[...cwd!==void 0?[absPathRule(path5.join(cwd,".claude")),absPathRule(path5.join(cwd,".git")),absPathRule(path5.join(cwd,".git"),""),absPathRule(path5.join(cwd,".mcp.json"),"")]:[],...SHELL_RC_FILES.map(f=>absPathRule(path5.join(home,f),""))];return[...readWrite.flatMap(p=>[`Read(${p})`,`Edit(${p}\
310
310
  )`]),...writeOnly.map(p=>`Edit(${p})`)]}var SHELL_RC_FILES=[".bashrc",".bash_profile",".bash_login",".bash_logout",".profile",".zshrc",".zprofile",".zshenv",".zlogin",".zlogout"];function unscopedWriteRules(allow){return allow.filter(r=>r==="Edit"||r==="Write"||r==="MultiEdit"||r==="Edit(*)"||r==="Edit(**)")}var STRIPPED_ENV_KEYS=["TWP_TOKEN","TWP_API_KEY","TWP_API_KEY_VALUE","TWP_LOOP_PLAN_TOKEN"];function aiEnv(env){const out={...env};for(const k of STRIPPED_ENV_KEYS)delete out[k];return out}async function defaultEngine(config,log,env){
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{secretReason}from"./chunk-XCU3PDQV.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{containsRedactedMarker,readBody}from"./chunk-V5WDGX4S.js";import{ALLOW_REDACTED_FLAG}from"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import{GITHUB_BASE_PATH,githubAccountPath,githubRepoPath,isExactNumericId,parseRepoRef}from"./chunk-QLH5IJQV.js";import{ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";
3
+ import{secretReason}from"./chunk-UQP47QOV.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{containsRedactedMarker,readBody}from"./chunk-V5WDGX4S.js";import{ALLOW_REDACTED_FLAG}from"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import{GITHUB_BASE_PATH,githubAccountPath,githubRepoPath,isExactNumericId,parseRepoRef}from"./chunk-QLH5IJQV.js";import{ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";
4
4
  import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-TDO6V3ZW.js";import{requireResolved,singleRef,withResolved}from"./chunk-7DCWZ2NF.js";import{isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiResponseError,ConflictError,UsageError}from"./chunk-STILP3Z6.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";
5
5
  import"./chunk-VSJBJXZO.js";import fs from"fs";import path from"path";var MAX_NUMBER_DIGITS=18;var ACCOUNT_COLUMNS=["id","host","username"];var REPO_COLUMNS=["full_name","private","language","open_issues_count","updated_at","description"];var ISSUE_LIST_COLUMNS=["repository","number","title","state","user","is_pull_request","draft","comments","labels","updated_at"];var ISSUE_GET_COLUMNS=["repository","number","title","state","user","is_pull_request","draft","labels","comments","created_at","updated_at","closed_at","html_url","body"];var PR_LIST_COLUMNS=["number","\
6
6
  title","state","draft","user","requested_reviewers","merged_at","labels","updated_at"];var PR_GET_COLUMNS=["number","title","state","draft","merged","user","requested_reviewers","head","base","additions","deletions","changed_files","labels","created_at","updated_at","merged_at","html_url","body"];var USER_COLUMNS=["login","id","name","type","html_url"];var ORG_COLUMNS=["login","id","description"];var COMMENT_COLUMNS=["id","user","created_at","updated_at","body"];var REVIEW_COLUMNS=["id","user","\
@@ -37,4 +37,4 @@ REMOTE_USAGE)}const account=args.account!==void 0?await resolver.githubAccount(a
37
37
  `);if(deps.hint??process.stderr.isTTY===true){const origin=new URL(ctx.apiUrl).origin;err(`\u8A8D\u8A3C\u306F credential helper \u3067\u6E21\u3057\u307E\u3059\uFF08\u672A\u8A2D\u5B9A\u306A\u30891\u56DE\u3060\u3051\u30021\u884C\u76EE\u306F\u65E2\u5B58\u306E\u6C4E\u7528 helper \u3092\u5916\u3059\uFF09:
38
38
  git config --global credential.${origin}.helper ''
39
39
  git config --global --add credential.${origin}.helper '!twp github git-credential${args.profile!==void 0?` --profile ${args.profile}`:""}'
40
- `)}return EXIT_OK}async function runGithubGit(sub,argv,deps={}){try{return sub==="git-remote"?await runRemote(argv,deps):await runCredential(argv,deps)}catch(e){const{exitCodeFor,reportError}=await import("./run-X5DTRFHA.js");const code=exitCodeFor(e);reportError(e,null,code,deps.err??writeStderr);return code}}export{GIT_TOKEN_MARGIN_MS,GIT_USERNAME,isRelayTarget,parseCredentialInput,runGithubGit};
40
+ `)}return EXIT_OK}async function runGithubGit(sub,argv,deps={}){try{return sub==="git-remote"?await runRemote(argv,deps):await runCredential(argv,deps)}catch(e){const{exitCodeFor,reportError}=await import("./run-GIXUKZEL.js");const code=exitCodeFor(e);reportError(e,null,code,deps.err??writeStderr);return code}}export{GIT_TOKEN_MARGIN_MS,GIT_USERNAME,isRelayTarget,parseCredentialInput,runGithubGit};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{checkOutTarget}from"./chunk-RJV2VT2X.js";import"./chunk-GIFOJFVU.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{contentTypeFor,inspectLocalFile}from"./chunk-ITTQEOIF.js";import{checkUploadQuota}from"./chunk-GNSZOYBQ.js";import{parseWaitOptions,waitUntilTerminal}from"./chunk-3EFJQDC4.js";import{readBody}from"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";
3
+ import{checkOutTarget}from"./chunk-6NJSB2SM.js";import"./chunk-XYCZIUWI.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{contentTypeFor,inspectLocalFile}from"./chunk-ITTQEOIF.js";import{checkUploadQuota}from"./chunk-GNSZOYBQ.js";import{parseWaitOptions,waitUntilTerminal}from"./chunk-3EFJQDC4.js";import{readBody}from"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";
4
4
  import{repeatedValues}from"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import{ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import{collapsesInUrlPath,isSafePathSegment}from"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger,readEnvelopeCursor,shellQuote}from"./chunk-TDO6V3ZW.js";import{requireResolved,singleRef,withResolved}from"./chunk-7DCWZ2NF.js";
5
5
  import{acknowledgement,isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiRejectedError,ApiResponseError,NetworkError,UsageError,WaitTimeoutError}from"./chunk-STILP3Z6.js";import"./chunk-TZL2342W.js";import"./chunk-RMFLTSOV.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-F3UL5POS.js";import"./chunk-OKATZ4SN.js";import"./chunk-RKBUJKI5.js";
6
6
  import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import crypto2 from"crypto";import fs2 from"fs";import path from"path";var SCOPE_PERSONAL="personal";var SCOPE_PROJECT="project";var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var FORBIDDEN_NAME=/[/\\:*?"<>|]/;var NAME_MAX=255;var ROW_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","updated_at"];var TRASH_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","deleted_at"];function folderRows(raw){return raw.map(row=>{const id=row["id"];const name=row["name"];const parentId=row["parent_id"];if(typeof id!==
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,createTwpToolkit,currentBranch,displayCwd,residentInputs,runTurn}from"./chunk-Q5DW75AO.js";import"./chunk-DEIIS7JP.js";import"./chunk-XCU3PDQV.js";import"./chunk-N2UVRM3Z.js";import"./chunk-BD7O73GK.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";
3
+ import{activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,createTwpToolkit,currentBranch,displayCwd,residentInputs,runTurn}from"./chunk-XYLJSSKY.js";import"./chunk-DEIIS7JP.js";import"./chunk-UQP47QOV.js";import"./chunk-N2UVRM3Z.js";import"./chunk-BD7O73GK.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";
4
4
  import"./chunk-SBRTBKEZ.js";import"./chunk-STILP3Z6.js";import{RelayError,createRuntime,emptyUsage,pickModel,specFor}from"./chunk-CASLLD23.js";import"./chunk-D233KKXW.js";import"./chunk-PMOUHEJQ.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import{checkMinSupportedVersion,enforceMinSupportedVersion,floorNeedsRefresh}from"./chunk-DXXFUNYN.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";
5
5
  import{getMode}from"./chunk-2LOT54OO.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var STREAM_JSON_VERSION=1;var fail=reason=>({ok:false,reason});var INPUT_PARSERS={user:obj=>{const content=obj.content;if(typeof content==="string"){return content.trim()===""?fail("user.content \u304C\u7A7A\u3067\u3059"):{ok:true,line:{type:"user",text:content}}}if(!Array.isArray(content)||content.length===0){return fail("user.content \u306F\u6587\u5B57\u5217\u304B\u3001\u30D6\u30ED\u30C3\u30AF\u306E\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}const texts=[];for(const block of content){
6
6
  if(typeof block!=="object"||block===null)return fail("user.content \u306E\u8981\u7D20\u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");const b=block;if(b.type!=="text"){return fail(`user.content \u306E\u30D6\u30ED\u30C3\u30AF\u7A2E\u5225 ${JSON.stringify(b.type)} \u306B\u306F\u672A\u5BFE\u5FDC\u3067\u3059\uFF08\u5BFE\u5FDC: text\uFF09`)}if(typeof b.text!=="string")return fail("text \u30D6\u30ED\u30C3\u30AF\u306E text \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{loadDomain}from"./chunk-GIFOJFVU.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
3
+ import{loadDomain}from"./chunk-XYCZIUWI.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-RJV2VT2X.js";import"./chunk-GIFOJFVU.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
3
+ import{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-6NJSB2SM.js";import"./chunk-XYCZIUWI.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
4
4
  import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-TZL2342W.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-F3UL5POS.js";import"./chunk-OKATZ4SN.js";
5
5
  import"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tocca-systems/twp-cli",
3
- "version": "0.155.0",
3
+ "version": "0.155.1",
4
4
  "description": "TWP CLI — Tocca Working Platform の CLI 型統合インターフェース(AIエージェントハーネス)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,9 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{configReadDirs}from"./chunk-RZVI6PMW.js";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!==
4
- 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=[];
5
- 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.
6
- 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\
7
- ed";if(parent===".aws"&&(base==="credentials"||base==="config"))return"AWS credentials are denied";for(const dir of configReadDirs(env)){if(lower===resolve(dir,"credentials.json").toLowerCase()){return"TWP credentials are denied (design \xA77)"}}if(parent===".twp"&&base==="credentials.json")return"TWP credentials are denied (design \xA77)";if(parent==="logs"&&base.startsWith("session-")&&base.endsWith(".jsonl")){const grandparent=segments[segments.length-3]??"";if(grandparent===".twp")return"TWP\
8
- audit logs are denied (design \xA77)";for(const dir of configReadDirs(env)){if(lower.startsWith(resolve(dir,"logs").toLowerCase()+sep)){return"TWP audit logs are denied (design \xA77)"}}}return null}function toolRelative(cwd,absPath){const rel=relative(cwd,absPath);return sep==="\\"?rel.split("\\").join("/"):rel}function isInsideCwd(absPath,cwd){const root=resolve(cwd);if(!withinLexically(absPath,root))return false;const real=realOrSelf(absPath);return real===absPath||withinLexically(real,realOrSelf(
9
- root))}function withinLexically(target,root){const rel=relative(root,target);return!(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))}function expandHome(input,home){if(input==="~")return home;if(input.startsWith("~/")||input.startsWith(`~${sep}`))return resolve(home,input.slice(2));return input}export{PathDeniedError,resolveToolPath,realToolPath,realOrSelf,secretReason,toolRelative,isInsideCwd};