@tocca-systems/twp-cli 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,53 @@
11
11
  `CHANGELOG.md` に残してあります。顧客向けの履歴は public 公開以降を対象とします。
12
12
  -->
13
13
 
14
+ ## 0.14.0
15
+
16
+ ループが計画を立てるかどうかを設定で切り替えられるようになりました(`plan_enabled` / 環境変数 `PLAN_ENABLED`・既定は従来どおり計画します)。
17
+
18
+ - 無効にすると、キューが空のサイクルでも計画のための AI を起動しません。積まれた仕事の実行だけを行います。
19
+ - 積まれた仕事・定期スケジュールの扱いは変わりません。
20
+ - キューが空のまま待ち続けてもループは終了しません(仕事が積まれ次第そのまま実行します)。
21
+
22
+ `twp task create` / `twp task update` で指定できる項目が増えました。
23
+
24
+ - `--category` / `--milestone` / `--label` … 名前でも ID でも指定できます(`--label` は複数指定でき、指定したものが全体になります)
25
+ - `--estimated-hours` … 見積工数(0〜9999・小数可)
26
+ - `--custom-field <フィールド名>=<値>` … カスタムフィールド(複数指定可・編集には管理者またはマネージャー権限が要ります)
27
+ - `--parent <キー|ID>` … 親タスクを指定してサブタスクとして作成します
28
+ - `--clear <項目>`(`twp task update` のみ)… 担当者・期日・開始日・優先度・カテゴリ・マイルストーン・ラベル・見積工数・本文・親タスクを空にします。指定しなかった項目は変わりません
29
+
30
+ 指定できる項目名は `twp task update help` に一覧があります。
31
+
32
+ codex のレートリミット検知で、特定の形をした長いログ行を処理するときにループが固まることがある問題を修正しました。
33
+
34
+ - 検知する内容は変わりません(従来どおりのログ行を同じように検知します)。
35
+ - 設定の変更は不要です。
36
+
37
+ AI が1ターンも実行しないまま終わった実行を「完了」ではなく「失敗」として記録するようになりました。
38
+
39
+ - 失敗として記録されるため、そのアイテムは次のサイクルで再度実行されます。
40
+ - 対象は「実行ターン数が 0 と計測でき、かつ最終報告に出力契約行が無い」実行だけです。ターン数を計測できない CLI(claude 以外)の実行は従来どおり完了として記録します。
41
+
42
+ ## 0.13.0
43
+
44
+ `--status` や `--type` に渡せる値を、エラーを踏まずに調べられるようになりました。
45
+
46
+ ```
47
+ twp task status list [--project <コード>]
48
+ twp task type list [--project <コード>]
49
+ twp task category list [--project <コード>]
50
+ twp task milestone list [--project <コード>]
51
+ twp task label list [--project <コード>]
52
+ ```
53
+
54
+ - `name` 列の値はそのまま `twp task list --status <名前>` / `twp task create --type <名前>` へ渡せます(ID でも渡せます)。
55
+ - `is_default` が立っているものが、`twp task create` で `--status` / `--type` を省いたときに使われる値です。
56
+ - `--output json` は API が返す全フィールド(色・表示順など)を出します。`--output table` は主要な列だけです。
57
+ - 結果は名前解決と同じキャッシュ(既定10分)から返るので、続けてコマンドを打っても通信は増えません。
58
+ 最新を取り直すときは `--refresh` を付けてください。
59
+ - 個人タスク(`--project __private__`)ではステータス・種別・カテゴリ・ラベルを一覧できます(マイルストーンはありません)。
60
+
14
61
  ## 0.12.0
15
62
 
16
63
  `twp task comment create` で、クリックで回答できる質問を投稿できるようになりました。
package/README.md CHANGED
@@ -79,10 +79,18 @@ twp task comment delete <コメントID> --yes
79
79
  twp task comment create <キー|ID> --body-file <背景.md> \
80
80
  --ask-question --question "<質問文>" --option ok=このまま進める --option back=差し戻す
81
81
  twp task comment create <キー|ID> --body-file <回答.md> --answer-to <コメントID> --select ok
82
+
83
+ # --status / --type などに渡せる値を調べる
84
+ twp task status list [--project <コード>]
85
+ twp task type list [--project <コード>]
86
+ twp task category list [--project <コード>]
87
+ twp task milestone list [--project <コード>]
88
+ twp task label list [--project <コード>]
82
89
  ```
83
90
 
84
91
  - **個人タスク(プロジェクトに属さない自分だけのタスク)は `--project __private__` で操作します**(`twp task list --project __private__`)。キーは `PRIVATE-<番号>` です。担当者(`--assignee`)とコメント(`twp task comment`)は個人タスクにはありません
85
92
  - **`--status` / `--type` / `--assignee` は名前で指定できます**(`--assignee me` は自分)。候補が絞れないときは候補を出して止まります
93
+ - **渡せる名前は `twp task status list` / `type list` / `category list` / `milestone list` / `label list` で確認できます**(`name` 列の値をそのまま `--status` 等へ渡せます)。`is_default` が立っているものが、`twp task create` で省略したときに使われる値です。結果は名前解決と同じキャッシュ(既定10分)から返るので続けて打っても往復は増えません(最新にするなら `--refresh`)。個人タスク(`--project __private__`)にマイルストーンはありません
86
94
  - **`delete` には `--yes` が必要です。** 対話中でも確認プロンプトには落ちません(自動実行と手動実行で必要な引数を変えないため)
87
95
  - **本文は `--body-file` / `--description-file` を主経路にしてください**(`-` で標準入力)。引数に直接書くと改行と Markdown が壊れます
88
96
  - 一覧は `--limit <件数>` / `--all` / `--cursor` で辿れます(`task subtasks` と `project members` はページングがありません)
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{failureHint,isAuthError,isCliFatalText,isRateLimited,isServerAiType,isUntrusted,maxTurnsReached,rateLimitWaitSeconds,tailForScan}from"./chunk-NAQ7OCUV.js";import{DEFAULT_CLAUDE_LAUNCHER,activeSlotPath,detectAiClis,detectClaudeAutoSwitch,isClaudeAi,isUsableModelId,modelFitsRoute,resolveSpawnTarget,usesBedrock,wrapWithAutoSwitch}from"./chunk-3WJHTPOZ.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";
3
+ import{failureHint,isAuthError,isCliFatalText,isRateLimited,isServerAiType,isUntrusted,maxTurnsReached,rateLimitWaitSeconds,tailForScan}from"./chunk-ZOOEH7ZE.js";import{DEFAULT_CLAUDE_LAUNCHER,activeSlotPath,detectAiClis,detectClaudeAutoSwitch,isClaudeAi,isUsableModelId,modelFitsRoute,resolveSpawnTarget,usesBedrock,wrapWithAutoSwitch}from"./chunk-3WJHTPOZ.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";
4
4
  import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import{spawnSync}from"child_process";import fs2 from"fs";import path2 from"path";import{spawn}from"child_process";import fs from"fs";import path from"path";var FINAL_REPORT_BEGIN="<<<AI_FINAL_REPORT>>>";var FINAL_REPORT_END="<<<END_AI_FINAL_REPORT>>>";var ClaudeStreamRenderer=class{constructor(now=()=>new Date){this.now=now}now;toolNames=new Map;toolCount=0;result={subtype:null,isError:null,numTurns:null,costUsd:null,durationMs:null,tokensIn:null,tokensOut:null,rateLimited:false,resetsAt:null,finalText:""};push(line){const trimmed=line.trim();if(trimmed==="")return[];let event;try{const parsed=JSON.parse(trimmed);if(parsed===null||typeof parsed!=="\
5
5
  object"||Array.isArray(parsed)){return[line]}event=parsed}catch{return[line]}switch(event["type"]){case"rate_limit_event":return this.onRateLimit(event);case"assistant":return this.onAssistant(event);case"user":return this.onUser(event);case"result":return this.onResult(event);default:return event["type"]==="system"?[]:[line]}}sawRateLimit(){return this.result.rateLimited}lastRateLimitNote="";onRateLimit(event){const info=event["rate_limit_info"];if(info===null||typeof info!=="object")return[];const rec=info;
6
6
  const status=typeof rec["status"]==="string"?rec["status"]:"";const resets=typeof rec["resetsAt"]==="number"?rec["resetsAt"]:null;if(status==="")return[];const at=isSaneEpochSec(resets)?` resets=${new Date(resets*1e3).toISOString()}`:"";if(status.startsWith("allowed")){if(status==="allowed")return[];const seen=`${status}|${resets??""}`;if(seen===this.lastRateLimitNote)return[];this.lastRateLimitNote=seen;return[this.line(`\u2139\uFE0F \u4E0A\u9650\u306B\u63A5\u8FD1\uFF08status=${status}${at}\uFF09\u2014 \u5B9F\
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{RESIDENT_TOKEN_CAP,buildResidentSet,buildSystemPrompt,createAuditLogger,currentBranch,displayCwd,runTurn}from"./chunk-R7T4VOIN.js";import"./chunk-N2UVRM3Z.js";import{applyPermissionMode,checkPermission,getMode,isModeId,nextMode}from"./chunk-NNOYO67O.js";import{require_fuzzysort}from"./chunk-DIMZRTLE.js";import{isFullWidth,isWide,stringWidth,stripAnsi}from"./chunk-WVS4W5FY.js";import{RelayError,builtinCatalog,createRuntime,loadCachedCatalog,modelLabel,pickModel,
3
+ import{RESIDENT_TOKEN_CAP,buildResidentSet,buildSystemPrompt,createAuditLogger,currentBranch,displayCwd,runTurn}from"./chunk-KIOMZ2ZU.js";import"./chunk-N2UVRM3Z.js";import{applyPermissionMode,checkPermission,getMode,isModeId,nextMode}from"./chunk-NNOYO67O.js";import{require_fuzzysort}from"./chunk-DIMZRTLE.js";import{isFullWidth,isWide,stringWidth,stripAnsi}from"./chunk-WVS4W5FY.js";import{RelayError,builtinCatalog,createRuntime,loadCachedCatalog,modelLabel,pickModel,
4
4
  toModelInfos}from"./chunk-RQFG3OUL.js";import{checkMinSupportedVersion,isBelowMinSupported,minSupportedBlockMessage}from"./chunk-DXXFUNYN.js";import"./chunk-PMOUHEJQ.js";import"./chunk-63LDNYGW.js";import"./chunk-NERYSBA4.js";import"./chunk-RZVI6PMW.js";import{proxyDiagnostics}from"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{__commonJS,__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.
5
5
  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]||
6
6
  maybeIterable["@@iterator"];return"function"===typeof maybeIterable?maybeIterable:null}var ReactNoopUpdateQueue={isMounted:function(){return false},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}};var assign=Object.assign;var emptyObject={};function Component(props,context,updater){this.props=props;this.context=context;this.refs=emptyObject;this.updater=updater||ReactNoopUpdateQueue}Component.prototype.isReactComponent={};Component.prototype.setState=
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{readBody}from"./chunk-QVXZEUKN.js";import{isRecord,pick,requireResolved,singleRef,withResolved}from"./chunk-GFC2ASHE.js";import{BACKLOG_BASE_PATH,BACKLOG_PROJECT_SCOPE_LABEL,BACKLOG_SCOPE_LABEL,backlogSpacePath,resolveNamed}from"./chunk-MZHTRHZS.js";import"./chunk-JKSXUBND.js";import"./chunk-II5RVJQN.js";import{ApiResponseError,UsageError}from"./chunk-M3GWY6NT.js";import"./chunk-5QCAIKFE.js";import"./chunk-NERYSBA4.js";import"./chunk-RZVI6PMW.js";
3
+ import{readBody}from"./chunk-QVXZEUKN.js";import{isRecord,pick,requireResolved,singleRef,withResolved}from"./chunk-GFC2ASHE.js";import{BACKLOG_BASE_PATH,BACKLOG_PROJECT_SCOPE_LABEL,BACKLOG_SCOPE_LABEL,backlogSpacePath,resolveNamed}from"./chunk-V4VHRASG.js";import"./chunk-JKSXUBND.js";import"./chunk-II5RVJQN.js";import{ApiResponseError,UsageError}from"./chunk-M3GWY6NT.js";import"./chunk-5QCAIKFE.js";import"./chunk-NERYSBA4.js";import"./chunk-RZVI6PMW.js";
4
4
  import"./chunk-J7QYPKVK.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var DEFAULT_COUNT=20;var MAX_COUNT=100;var NUMERIC=/^[0-9]+$/;function isExactNumericId(value){return NUMERIC.test(value)&&String(Number(value))===value}var ISSUE_REF=/^(?:[A-Za-z0-9_]+-[0-9]+|[0-9]+)$/;var DATE=/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;var SPACE_COLUMNS=["id","space_url"];var PROJECT_COLUMNS=["id","projectKey","name"];var ISSUE_LIST_COLUMNS=["issueKey","summary","status","assignee","priority","dueDate","updated","descriptionTruncated"];var ISSUE_GET_COLUMNS=["id","issueKey","projectId","s\
5
5
  ummary","description","descriptionTruncated","status","issueType","priority","assignee","createdUser","parentIssueId","startDate","dueDate","estimatedHours","actualHours","created","updated"];var COMMENT_COLUMNS=["id","created","createdUserId","createdUser","content","changeLog"];function commentRow(row){const source=isRecord(row)?row:{};const user=isRecord(source["createdUser"])?source["createdUser"]:{};return pick({...source,createdUserId:user["id"]??null,createdUser:user["name"]??null},COMMENT_COLUMNS)}
6
6
  var ATTACHMENT_COLUMNS=["id","name","size","contentType","createdUserId","createdUser","created"];var STATUS_COLUMNS=["id","name","color"];var USER_COLUMNS=["id","userId","name","mailAddress","roleType"];var SPACE_FLAG={name:"--space",summary:"Backlog \u30B9\u30DA\u30FC\u30B9\uFF08ID / \u30B9\u30DA\u30FC\u30B9URL / \u30B5\u30D6\u30C9\u30E1\u30A4\u30F3\uFF09\u3002\u767B\u9332\u304C1\u4EF6\u306A\u3089\u7701\u7565\u3067\u304D\u307E\u3059",takesValue:true,placeholder:"<ID|URL>"};var BODY_MAX_CHARS=1e5;
@@ -37,10 +37,10 @@ if(exclusiveSkills.size===0&&statusEndpoint!==null){warnings.push("operations.st
37
37
  stringArray(o["high_risk_skills"],"high_risk_skills",warnings)),preflightHosts:stringArray(o["preflight_hosts"],"preflight_hosts",warnings),releaseRecoverySkill,postSuccessEnqueue:stringMap(o["post_success_enqueue"],"post_success_enqueue",warnings),contractSkills:new Set(stringArray(o["contract_skills"],"contract_skills",warnings)),zeroTargetGates:parseZeroTargetGates(o["zero_target_gates"],warnings)},warnings}}function describeOperations(ops){if(ops===NO_OPERATIONS||ops.exclusiveSkills.size===0&&
38
38
  ops.highRiskSkills.size===0){return"\u904B\u7528\u8A2D\u5B9A: \u306A\u3057\uFF08\u30B9\u30AD\u30EB\u540D\u306B\u3088\u308B\u7279\u5225\u6271\u3044\u306F\u884C\u3044\u307E\u305B\u3093\uFF09"}const parts=[];if(ops.exclusiveSkills.size>0&&ops.statusEndpoint){parts.push(`\u6392\u4ED6 ${[...ops.exclusiveSkills].join(",")} \u2190 ${ops.statusEndpoint.url}`)}else if(ops.exclusiveSkills.size>0){parts.push(`\u6392\u4ED6 ${[...ops.exclusiveSkills].join(",")}\uFF08\u554F\u3044\u5408\u308F\u305B\u5148\u304C\u7121\u3044\u305F\u3081\u7121\u52B9\uFF09`)}
39
39
  if(ops.highRiskSkills.size>0)parts.push(`\u9AD8\u30EA\u30B9\u30AF ${ops.highRiskSkills.size}\u4EF6`);if(ops.releaseRecoverySkill)parts.push(`\u56DE\u53CE ${ops.releaseRecoverySkill}`);return`\u904B\u7528\u8A2D\u5B9A: ${parts.join(" / ")}`}function sanitizeInt(value,fallback,min=1){const n=typeof value==="number"?value:Number.parseInt(String(value??""),10);if(Number.isInteger(n)&&n>=min)return{value:n,warning:null};if(value===void 0||value===null||value==="")return{value:fallback,warning:null};return{value:fallback,warning:`'${String(value)}' \u306F${min}\u4EE5\u4E0A\u306E\u6574\u6570\u3067\u306F\u3042\u308A\u307E\u305B\u3093 \u2192 \u65E2\u5B9A ${fallback} \u3092\u4F7F\u3044\u307E\u3059`}}function nonEmpty(value){const t=value?.trim();
40
- return t===void 0||t===""?void 0:value}function resolveCharterEnabled(raw,local,warn){const v=(raw??"").trim();if(v!=="")return isBoolishTrue(v);if(local===void 0)return true;if(typeof local==="boolean")return local;if(typeof local==="string")return isBoolishTrue(local.trim()===""?"true":local);warn(`charter_enabled \u306F\u771F\u507D\u5024\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u89E3\u91C8\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u61B2\u7AE0\u3092\u524D\u7F6E\u3057\u307E\u3059\uFF09`);
41
- return true}function charterWrapper(raw,local,key,warn){if(raw!==void 0)return raw;if(local===void 0)return null;if(typeof local==="string")return local;warn(`${key} \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u7121\u8996\u3057\u3001\u65E2\u5B9A\u306E\u56F2\u307F\u6587\u3092\u4F7F\u3044\u307E\u3059\uFF09`);return null}function loopStateDir(env=process.env){const explicit=env.TWP_OPS_STATE_DIR?.trim();if(explicit)return explicit;return path.
42
- join(os.homedir(),".twp-ops")}function releaseOutcomeLogPath(env=process.env){const explicit=env.RELEASE_OUTCOME_LOG?.trim();if(explicit)return explicit;return path.join(loopStateDir(env),"release-outcomes.tsv")}function localConfigPath(projectId,env=process.env){return path.join(twpHomeDir(env),"loops",`${projectFileKey(projectId)}.json`)}function loadLocalConfig(projectId,env=process.env){const file=localConfigPath(projectId,env);try{const parsed=JSON.parse(fs.readFileSync(file,"utf8"));return parsed!==
43
- null&&typeof parsed==="object"?parsed:{}}catch(err){if(err.code==="ENOENT")return{};throw new Error(`\u30EB\u30FC\u30D7\u8A2D\u5B9A\u306E\u8AAD\u307F\u53D6\u308A\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${file}
40
+ return t===void 0||t===""?void 0:value}function resolveCharterEnabled(raw,local,warn){return resolveBoolSetting(raw,local,"charter_enabled",true,"\u61B2\u7AE0\u3092\u524D\u7F6E\u3057\u307E\u3059",warn)}function resolveBoolSetting(raw,local,key,fallback,fallbackNote,warn){const v=(raw??"").trim();if(v!=="")return isBoolishTrue(v);if(local===void 0)return fallback;if(typeof local==="boolean")return local;if(typeof local==="string")return isBoolishTrue(local.trim()===""?String(fallback):local);warn(
41
+ `${key} \u306F\u771F\u507D\u5024\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u89E3\u91C8\u3067\u304D\u306A\u3044\u305F\u3081\u3001${fallbackNote}\uFF09`);return fallback}function charterWrapper(raw,local,key,warn){if(raw!==void 0)return raw;if(local===void 0)return null;if(typeof local==="string")return local;warn(`${key} \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08'${String(local)}' \u306F\u7121\u8996\u3057\u3001\u65E2\u5B9A\u306E\u56F2\u307F\u6587\u3092\u4F7F\u3044\u307E\u3059\uFF09`);
42
+ return null}function loopStateDir(env=process.env){const explicit=env.TWP_OPS_STATE_DIR?.trim();if(explicit)return explicit;return path.join(os.homedir(),".twp-ops")}function releaseOutcomeLogPath(env=process.env){const explicit=env.RELEASE_OUTCOME_LOG?.trim();if(explicit)return explicit;return path.join(loopStateDir(env),"release-outcomes.tsv")}function localConfigPath(projectId,env=process.env){return path.join(twpHomeDir(env),"loops",`${projectFileKey(projectId)}.json`)}function loadLocalConfig(projectId,env=process.
43
+ env){const file=localConfigPath(projectId,env);try{const parsed=JSON.parse(fs.readFileSync(file,"utf8"));return parsed!==null&&typeof parsed==="object"?parsed:{}}catch(err){if(err.code==="ENOENT")return{};throw new Error(`\u30EB\u30FC\u30D7\u8A2D\u5B9A\u306E\u8AAD\u307F\u53D6\u308A\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${file}
44
44
  ${err.message}`,{cause:err})}}function resolveRunnerId(stateDir,env=process.env){const file=env.RUNNER_ID_FILE&&env.RUNNER_ID_FILE.trim()!==""?env.RUNNER_ID_FILE:path.join(stateDir,"runner-id");let candidate=env.RUNNER_ID?.trim()??"";if(!candidate){try{candidate=fs.readFileSync(file,"utf8").split("\n")[0]?.trim()??""}catch{candidate=""}}let warning=null;if(candidate&&!/^[A-Za-z0-9._-]+$/.test(candidate)){warning=`runner_id '${candidate}' \u306B\u4F7F\u3048\u306A\u3044\u6587\u5B57\u304C\u542B\u307E\u308C\u308B\u305F\u3081\u63A1\u756A\u3057\u76F4\u3057\u307E\u3057\u305F\uFF08[A-Za-z0-9._-] \u306E\u307F\uFF09`;
45
45
  candidate=""}if(!candidate){const host=(os.hostname()||"host").split(".")[0]??"host";const hostPart=host.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,32)||"host";candidate=`${hostPart}-${randomBytes(4).toString("hex")}`;try{fs.mkdirSync(path.dirname(file),{recursive:true,mode:448});fs.writeFileSync(file,`${candidate}
46
46
  `,{mode:384})}catch{warning=`runner_id \u3092 ${file} \u3078\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u8D77\u52D5\u306E\u305F\u3073\u306B\u5225\u30E9\u30F3\u30CA\u30FC\u3068\u3057\u3066\u767B\u9332\u3055\u308C\u3001\u53F0\u6570\u4E0A\u9650\u306B\u9054\u3057\u307E\u3059`}}return{runnerId:candidate,warning}}function buildRunId(runnerId,now=new Date){const stamp=now.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");return`${runnerId}#${stamp}#${process.pid}`}function buildLoopConfig(input){
@@ -53,5 +53,5 @@ projectId:input.projectId,projectRef:input.projectRef,apiUrl:input.apiUrl,runner
53
53
  NT_LOOP_CONTENDED_MAX="),queueUndeterminedMax:num(env.QUEUE_UNDETERMINED_MAX,5,1,"QUEUE_UNDETERMINED_MAX="),staleReclaimHours:num(env.STALE_RECLAIM_HOURS,3,0,"STALE_RECLAIM_HOURS="),planLockTtlSec,planLockWaitMaxSec:num(env.PLAN_LOCK_WAIT_MAX,planLockTtlSec,0,"PLAN_LOCK_WAIT_MAX="),planLockPollIntervalSec:num(env.PLAN_LOCK_POLL_INTERVAL,60,1,"PLAN_LOCK_POLL_INTERVAL="),planLockRenewIntervalSec:num(env.PLAN_LOCK_RENEW_INTERVAL,Math.trunc(planLockTtlSec/3),1,"PLAN_LOCK_RENEW_INTERVAL="),planLockStealAttempts:num(
54
54
  env.PLAN_LOCK_STEAL_ATTEMPTS,3,0,"PLAN_LOCK_STEAL_ATTEMPTS="),planLockPermanentMax:num(env.PLAN_LOCK_PERMANENT_MAX,3,1,"PLAN_LOCK_PERMANENT_MAX="),scheduleMidcycleMax:num(env.SCHEDULE_MIDCYCLE_MAX,6,1,"SCHEDULE_MIDCYCLE_MAX="),blockerRecoveryMaxPerDay:num(env.BLOCKER_RECOVERY_MAX_PER_DAY,2,1,"BLOCKER_RECOVERY_MAX_PER_DAY="),releaseRerunAutoEnqueue:env.RELEASE_RERUN_AUTOENQUEUE_ENABLED!=="false",releaseRerunMaxPerCause:num(env.RELEASE_RERUN_MAX_PER_CAUSE,2,1,"RELEASE_RERUN_MAX_PER_CAUSE="),writebackMaxAgeDays:num(
55
55
  env.AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS,7,1,"AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS="),scheduleTimezone:nonEmpty(env.AGENT_LOOP_SCHEDULE_TZ)??"Asia/Tokyo",counterTimezone:nonEmpty(env.AGENT_LOOP_COUNTER_TZ)??"Asia/Tokyo",compileCommand:local.compile_command!==void 0&&local.compile_command.length>0?local.compile_command:null,charterFile:nonEmpty(env.CHARTER_FILE)??nonEmpty(local.charter_file)??"CONSTITUTION.md",charterEnabled:resolveCharterEnabled(env.CHARTER_ENABLED,local.charter_enabled,m=>warnings.push(
56
- m)),charterPrefix:charterWrapper(env.CHARTER_PREFIX,local.charter_prefix,"charter_prefix",m=>warnings.push(m)),charterSuffix:charterWrapper(env.CHARTER_SUFFIX,local.charter_suffix,"charter_suffix",m=>warnings.push(m)),ai:ai.config,operations:operations.operations,claudeLauncher:claudeLauncher.launcher,prefetch:prefetch.hooks,preflight:preflight.hooks,configHash:ai.config.hash(),version:input.version,warnings,releaseOutcomeLogPath:releaseOutcomeLogPath(env)}}function localDate(timezone,now=new Date){
57
- const fmt=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});return fmt.format(now)}export{parseClaudeLauncher,evaluateOwnership,runPrefetch,runPreflight,formatHookWiring,formatHookIds,describeOperations,loopStateDir,localConfigPath,buildLoopConfig,localDate};
56
+ m)),charterPrefix:charterWrapper(env.CHARTER_PREFIX,local.charter_prefix,"charter_prefix",m=>warnings.push(m)),charterSuffix:charterWrapper(env.CHARTER_SUFFIX,local.charter_suffix,"charter_suffix",m=>warnings.push(m)),planEnabled:resolveBoolSetting(env.PLAN_ENABLED,local.plan_enabled,"plan_enabled",true,"\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u5B9F\u884C\u3057\u307E\u3059",m=>warnings.push(m)),ai:ai.config,operations:operations.operations,claudeLauncher:claudeLauncher.launcher,prefetch:prefetch.
57
+ hooks,preflight:preflight.hooks,configHash:ai.config.hash(),version:input.version,warnings,releaseOutcomeLogPath:releaseOutcomeLogPath(env)}}function localDate(timezone,now=new Date){const fmt=new Intl.DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});return fmt.format(now)}export{parseClaudeLauncher,evaluateOwnership,runPrefetch,runPreflight,formatHookWiring,formatHookIds,describeOperations,loopStateDir,localConfigPath,buildLoopConfig,localDate};
@@ -8,7 +8,8 @@ ed";if(parent===".aws"&&(base==="credentials"||base==="config"))return"AWS crede
8
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
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}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;continue;default:
10
10
  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==="--recursive")recursive=true;if(flag==="--force")force=true;if(!flag.startsWith("--")){if(flag.includes("r")||
11
- flag.includes("R"))recursive=true;if(flag.includes("f"))force=true}}if(recursive&&force)return true}}function neverAutoAllowReason(toolName,input){if(toolName!=="bash"&&toolName!=="shell")return null;const command=typeof input["command"]==="string"?input["command"]:"";if(isRecursiveForceRemove(command))return"rm -rf \u3092\u542B\u3080\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059";if(!isSingleCommand(command)){return"\u8907\u6570\u306E\u30B3\u30DE\u30F3\u30C9\u306B\u5206\u5C90\u3057\u3066\u3044\u308B\u305F\u3081\uFF08&& ; | $() \u306A\u3069\uFF09\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059"}
11
+ 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.isArray(entry)?entry.join(" "):"").filter(command=>command!=="");if(shell.length===0&&argv.length===0){return`${tool.
12
+ 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)){return"\u8907\u6570\u306E\u30B3\u30DE\u30F3\u30C9\u306B\u5206\u5C90\u3057\u3066\u3044\u308B\u305F\u3081\uFF08&& ; | $() \u306A\u3069\uFF09\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059"}}
12
13
  return null}function autoApproveExemptReason(tool,input,cwd){if(tool.risk!=="write")return null;const raw=input["path"]??input["file_path"]??input["dest"]??input["target"]??input["filename"];if(typeof raw!=="string"||raw==="")return"\u66F8\u304D\u8FBC\u307F\u5148\u3092\u5224\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059";let absolute;try{absolute=realToolPath(raw,cwd)}catch{return"\u66F8\u304D\u8FBC\u307F\u5148\u3092\u89E3\u6C7A\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059"}
13
14
  const segments=absolute.toLowerCase().split(sep2);const base=segments[segments.length-1]??"";if(segments.includes(".git"))return".git/ \u914D\u4E0B\u306F\u6B21\u306E git \u64CD\u4F5C\u3067\u5B9F\u884C\u3055\u308C\u308B\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059";if(segments.includes(".github"))return".github/ \u914D\u4E0B\u306F CI \u304C\u5B9F\u884C\u3059\u308B\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059";if(segments.includes(".claude"))return".claude/ \u914D\u4E0B\u306F\u30D5\u30C3\u30AF\u5B9A\u7FA9\u3092\u542B\
14
15
  \u3080\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059";if(segments.includes(".husky")||segments.includes(".githooks")){return"git hook \u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306A\u306E\u3067\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059"}if(base==="package.json"||base==="makefile"||base===".envrc"||base===".mcp.json"){return`${base} \u306F\u5F8C\u7D9A\u306E\u5B9F\u884C\u306B\u5F71\u97FF\u3059\u308B\u305F\u3081\u3001\u6BCE\u56DE\u78BA\u8A8D\u3057\u307E\u3059`}return null}function validateInput(schema,input){const errors=[];if(typeof input!=="object"||input===null||Array.isArray(input)){return{ok:false,errors:["input must be a JSON object"],value:{}}}const value={...input};const props=schema.properties??{};for(const key of schema.required??[]){if(value[key]===void 0||value[key]===null)errors.push(`missing required property: ${key}`)}if(schema.additionalProperties===false){for(const key of Object.keys(value)){if(!(key in props))errors.push(`unknown property: ${key}`)}}
@@ -17,8 +18,8 @@ isInteger(value))errors.push(`${path4} must be an integer`);break;case"number":i
17
18
  if(schema.enum&&!schema.enum.some(v=>v===value)){errors.push(`${path4} must be one of: ${schema.enum.join(", ")}`)}if(typeof value==="number"){if(schema.minimum!==void 0&&value<schema.minimum)errors.push(`${path4} must be >= ${schema.minimum}`);if(schema.maximum!==void 0&&value>schema.maximum)errors.push(`${path4} must be <= ${schema.maximum}`)}}async function executeTool(tool,rawInput,deps){const validated=validateInput(tool.inputSchema,rawInput);if(!validated.ok){const content=`Invalid input for ${tool.name}:
18
19
  - ${validated.errors.join("\n- ")}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"error",bytes:Buffer.byteLength(content),mode:deps.mode.id,reasonCode:"invalid_input"});return{content,isError:true,summary:`${tool.name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}const input=validated.value;const recordDecision=(decision,reasonCode,reason)=>{deps.audit.record({event:"decision",tool:tool.name,risk:tool.risk,decision,reasonCode,reason,mode:deps.mode.id,rawInput:input})};const modePolicy=checkPermission(
19
20
  tool.name,deps.mode);const overlay=applyPermissionMode(modePolicy,tool.risk,deps.permissionMode);const policy=overlay.decision;if(policy==="deny"){recordDecision("deny",overlay.reason===null?"mode_policy":"permission_mode",overlay.reason??`mode=${deps.mode.id} \u306E\u65B9\u91DD`);return{content:overlay.reason===null?`permission denied: ${tool.name} is not available in ${deps.mode.id} mode.`:`permission denied: ${tool.name} is blocked by --permission-mode=${deps.permissionMode??""}.`,isError:true,
20
- denied:true,summary:overlay.reason===null?`${tool.name} \xB7 deny\uFF08${deps.mode.label}\u30E2\u30FC\u30C9\uFF09`:`${tool.name} \xB7 deny\uFF08--permission-mode=${deps.permissionMode??""}\uFF09`}}const preview=safePreview(tool,input);const noAlwaysReason=neverAutoAllowReason(tool.name,input)??autoApproveExemptReason(tool,input,deps.ctx.cwd);const needsAsk=policy==="ask"||noAlwaysReason!==null;if(needsAsk){const skip=noAlwaysReason===null&&deps.sessionAllow.has(tool.name);if(skip)recordDecision(
21
- "allow","session_allow","\u30BB\u30C3\u30B7\u30E7\u30F3\u5185\u306E\u300C\u4ECA\u5F8C\u805E\u304B\u306A\u3044\u300D");if(!skip){if(!deps.askPermission){recordDecision("deny",noAlwaysReason===null?"non_interactive":"guard",noAlwaysReason??"\u975E\u5BFE\u8A71\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u627F\u8A8D\u304C\u5FC5\u8981\uFF08deny-and-continue\uFF09");return{content:`permission denied: ${tool.name} requires approval, and this session is non-interactive. `+(noAlwaysReason===null?"":`Reason: ${noAlwaysReason}\
21
+ denied:true,summary:overlay.reason===null?`${tool.name} \xB7 deny\uFF08${deps.mode.label}\u30E2\u30FC\u30C9\uFF09`:`${tool.name} \xB7 deny\uFF08--permission-mode=${deps.permissionMode??""}\uFF09`}}const preview=safePreview(tool,input);const noAlwaysReason=neverAutoAllowReason(tool,input)??autoApproveExemptReason(tool,input,deps.ctx.cwd);const needsAsk=policy==="ask"||noAlwaysReason!==null;if(needsAsk){const skip=noAlwaysReason===null&&deps.sessionAllow.has(tool.name);if(skip)recordDecision("allo\
22
+ w","session_allow","\u30BB\u30C3\u30B7\u30E7\u30F3\u5185\u306E\u300C\u4ECA\u5F8C\u805E\u304B\u306A\u3044\u300D");if(!skip){if(!deps.askPermission){recordDecision("deny",noAlwaysReason===null?"non_interactive":"guard",noAlwaysReason??"\u975E\u5BFE\u8A71\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u627F\u8A8D\u304C\u5FC5\u8981\uFF08deny-and-continue\uFF09");return{content:`permission denied: ${tool.name} requires approval, and this session is non-interactive. `+(noAlwaysReason===null?"":`Reason: ${noAlwaysReason}\
22
23
  `)+"Explain what you would run instead of running it.",isError:true,denied:true,summary:`${tool.name} \xB7 \u975E\u5BFE\u8A71\u306E\u305F\u3081\u62D2\u5426`}}let diff;try{diff=await tool.prepare?.(input,deps.ctx)??void 0}catch(err){diff=void 0;if(err instanceof PathDeniedError){recordDecision("deny","path_denied","\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF08paths.ts\uFF09");return{content:err.message,isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF09`}}}
23
24
  const answer=await deps.askPermission({tool,input,preview,...diff?{diff}:{},noAlwaysReason});if(answer==="no"){recordDecision("deny","user_declined","\u5229\u7528\u8005\u304C\u62D2\u5426");return{content:`permission denied: the user declined to run ${tool.name}.`,isError:true,denied:true,summary:`${tool.name} \xB7 \u5229\u7528\u8005\u304C\u62D2\u5426`}}if(answer==="always"&&noAlwaysReason===null)deps.sessionAllow.add(tool.name);recordDecision("allow","user_approved",answer==="always"?"\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u4ECA\u5F8C\u805E\
24
25
  \u304B\u306A\u3044\uFF09":"\u5229\u7528\u8005\u304C\u627F\u8A8D")}}else{recordDecision("allow",overlay.reason===null?"mode_policy":"permission_mode",overlay.reason??`mode=${deps.mode.id} \u306E\u65B9\u91DD`)}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});return{summary:preview,...result}}catch(err){if(err instanceof
@@ -62,11 +63,11 @@ const pwsh=pwshPath(probe,env);if(pwsh!==null){return{toolName:"shell",command:p
62
63
  if(probe(sys.powershell)){return{toolName:"shell",command:sys.powershell,args:["-NoProfile","-NonInteractive","-Command"],kind:"powershell",note:"\u3053\u306E\u74B0\u5883\u306B bash \u304C\u306A\u3044\u305F\u3081 Windows PowerShell 5.1 \u3067\u5B9F\u884C\u3057\u307E\u3059\u3002**bash \u69CB\u6587\u306F\u4F7F\u3048\u307E\u305B\u3093**\uFF08`&&` \u306F\u4F7F\u3048\u305A `;` \u306B\u306A\u308A\u307E\u3059\uFF09"}}return{toolName:"shell",command:sys.cmd,args:["/d","/s","/c"],kind:"cmd",note:"\u3053\u306E\u74B0\u5883\u306B b\
63
64
  ash \u3082 PowerShell \u3082\u306A\u3044\u305F\u3081 cmd.exe \u3067\u5B9F\u884C\u3057\u307E\u3059\u3002**bash \u69CB\u6587\u306F\u4F7F\u3048\u307E\u305B\u3093**\uFF08cmd \u306E\u30D0\u30C3\u30C1\u69CB\u6587\u3067\u66F8\u3044\u3066\u304F\u3060\u3055\u3044\uFF09"}}function trustedBase(base){return typeof base==="string"&&isWindowsDriveAbsolute(base)}function gitBashCandidates(env){const fromEnv=[];for(const key of["ProgramFiles","ProgramFiles(x86)","ProgramW6432"]){const base=env[key];if(trustedBase(
64
65
  base))fromEnv.push(`${base}\\Git\\bin\\bash.exe`,`${base}\\Git\\usr\\bin\\bash.exe`)}return[...fromEnv,...GIT_BASH_CANDIDATES]}function pwshPath(probe,env){const bases=[env["ProgramFiles"],env["ProgramW6432"],"C:\\Program Files"].filter(trustedBase);for(const base of bases){for(const major of["7","6"]){const candidate=`${base}\\PowerShell\\${major}\\pwsh.exe`;if(probe(candidate))return candidate}}return null}var DEFAULT_TIMEOUT_MS=12e4;var MAX_TIMEOUT_MS=6e5;var MAX_OUTPUT_BYTES=1e5;function createBashTool(choice=selectShell()){const base=choice.toolName==="bash"?"Run a shell command with bash. Prefer specific tools (read_file / glob / grep) when they fit \u2014 they are cheaper and safer.":"Run a shell command. NOTE: bash is not available in this environment.";return{name:choice.toolName,domain:"local",risk:"exec",description:choice.note===null?base:`${base}
65
- ${choice.note}`,inputSchema:{type:"object",additionalProperties:false,properties:{command:{type:"string",description:"The command line to run"},timeout_ms:{type:"integer",description:`Timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}, max ${MAX_TIMEOUT_MS})`,minimum:1e3,maximum:MAX_TIMEOUT_MS}},required:["command"]},preview(input){const command=typeof input["command"]==="string"?input["command"]:"";const line=command.split("\n")[0]??"";return`${choice.toolName} \xB7 ${line.slice(0,80)}${line.
66
- length>80||command.includes("\n")?"\u2026":""}`},async run(input,ctx){const command=String(input["command"]);const timeout=clampTimeout(input["timeout_ms"]);return runCommand(choice,command,timeout,ctx.cwd,ctx.signal,ctx.env)}}}function clampTimeout(value){if(typeof value!=="number"||!Number.isFinite(value))return DEFAULT_TIMEOUT_MS;return Math.min(MAX_TIMEOUT_MS,Math.max(1e3,Math.floor(value)))}function runCommand(choice,command,timeoutMs,cwd,signal,env=process.env){return new Promise(resolve5=>{
67
- const child=spawn(choice.command,[...choice.args,command],{cwd,env,shell:false,detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]});const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_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 outcome="ok";const kill=()=>{if(child.killed||child.exitCode!==
68
- null)return;if(isForceOnly()){killProcessTree(child,"SIGKILL");return}killProcessTree(child,"SIGTERM");setTimeout(()=>killProcessTree(child,"SIGKILL"),2e3).unref()};const timer=setTimeout(()=>{outcome="timeout";kill()},timeoutMs);const onAbort=()=>{outcome="aborted";kill()};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(exitCode,spawnError)=>{clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const raw=Buffer.concat(chunks);
69
- 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")}]
66
+ ${choice.note}`,inputSchema:{type:"object",additionalProperties:false,properties:{command:{type:"string",description:"The command line to run"},timeout_ms:{type:"integer",description:`Timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}, max ${MAX_TIMEOUT_MS})`,minimum:1e3,maximum:MAX_TIMEOUT_MS}},required:["command"]},execCommands(input){const command=typeof input["command"]==="string"?input["command"]:"";return{shell:[command]}},preview(input){const command=typeof input["command"]==="string"?
67
+ input["command"]:"";const line=command.split("\n")[0]??"";return`${choice.toolName} \xB7 ${line.slice(0,80)}${line.length>80||command.includes("\n")?"\u2026":""}`},async run(input,ctx){const command=String(input["command"]);const timeout=clampTimeout(input["timeout_ms"]);return runCommand(choice,command,timeout,ctx.cwd,ctx.signal,ctx.env)}}}function clampTimeout(value){if(typeof value!=="number"||!Number.isFinite(value))return DEFAULT_TIMEOUT_MS;return Math.min(MAX_TIMEOUT_MS,Math.max(1e3,Math.floor(
68
+ value)))}function runCommand(choice,command,timeoutMs,cwd,signal,env=process.env){return new Promise(resolve5=>{const child=spawn(choice.command,[...choice.args,command],{cwd,env,shell:false,detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]});const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_OUTPUT_BYTES*2&&chunks.length>1){const dropped=chunks.shift();if(!dropped)break;bytes-=dropped.length}};child.stdout.on(
69
+ "data",collect);child.stderr.on("data",collect);let outcome="ok";const kill=()=>{if(child.killed||child.exitCode!==null)return;if(isForceOnly()){killProcessTree(child,"SIGKILL");return}killProcessTree(child,"SIGTERM");setTimeout(()=>killProcessTree(child,"SIGKILL"),2e3).unref()};const timer=setTimeout(()=>{outcome="timeout";kill()},timeoutMs);const onAbort=()=>{outcome="aborted";kill()};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(exitCode,spawnError)=>{
70
+ 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")}]
70
71
  `:"";if(spawnError){resolve5({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"){resolve5({content:`${head}${body}
71
72
  [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"){resolve5({content:`${head}${body}
72
73
  [interrupted by the user]`,isError:true,summary:`${choice.toolName} \xB7 \u4E2D\u65AD`});return}resolve5({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\
@@ -76,14 +77,14 @@ ok)return{content:applied.error,isError:true};await writeFile(abs,applied.after,
76
77
  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?
77
78
  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.
78
79
  slice(0,at)+replacement+haystack.slice(at+needle.length)}import{spawn as spawn2}from"child_process";import path3 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"]);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\
79
- operations (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"]},preview(input){const args=Array.
80
- 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.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(
81
- "=")[0]??arg;if(DENIED_ARGS.has(head)){return{content:`Argument ${arg} is not allowed for the git tool.`,isError:true}}}const argv=LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list",...args]:[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 PA\
82
- TH). 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"}}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(
83
- "git",{...common,env:{...env,PATHEXT:".EXE;.COM"}});return spawnable??findExecutable("git",{...common,env})}function runGit(exe,argv,cwd,baseEnv,signal){return new Promise(resolve5=>{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=path3.basename(exe);resolve5({content:err.code===
84
- "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 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*
85
- 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;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",
86
- onAbort);const kept=keepTailBytes(Buffer.concat(chunks),MAX_GIT_OUTPUT_BYTES);const body=kept.text;const note=kept.droppedBytes>0?`
80
+ operations (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(
81
+ input["subcommand"]??"");const args=Array.isArray(input["args"])?input["args"].map(String):[];return{argv:[["git",...LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list"]:[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 su\
82
+ bcommands only: ${READ_ONLY_SUBCOMMANDS.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}}}const argv=LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list",...args]:[sub,...args];const env=ctx.env??process.env;const exe=resolveGitExecutable({env});if(exe===null){return{
83
+ 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"}}return runGit(exe,argv,ctx.cwd,env,ctx.signal)}};function resolveGitExecutable(deps={}){const platform=deps.
84
+ 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(resolve5=>{let child;try{child=spawn2(exe,["--no-pager",...argv],{cwd,shell:false,env:{...baseEnv,GIT_PAGER:"\
85
+ 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=path3.basename(exe);resolve5({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 provides git.exe) or put its bin directory earlier on PATH.`:`Failed to start git (${name}): ${err.code??"unknown \
86
+ 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;const timer=setTimeout(()=>{timedOut=true;killProcessTree(child,"SIGKILL")},GIT_TIMEOUT_MS);
87
+ 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?`
87
88
  [output truncated: dropped the first ${kept.droppedBytes} bytes]`:"";if(err){resolve5({content:`Failed to run git (${path3.basename(exe)}): ${err.code??err.message}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}if(timedOut){resolve5({content:`${body}${note}
88
89
  [timed out after ${GIT_TIMEOUT_MS}ms]`,isError:true,summary:"git \xB7 \u30BF\u30A4\u30E0\u30A2\u30A6\u30C8"});return}resolve5({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 resolve3}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"'},
89
90
  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?resolve3(ctx.cwd):resolveToolPath(String(input["path"]),ctx.cwd);const pattern=String(input["pattern"]);const exclude=input["include_ignored"]===true?[]:DEFAULT_EXCLUDES;
@@ -9,32 +9,35 @@ throw new UsageError(`${ctx.flag} \u306B\u7A7A\u306E\u5024\u306F\u6307\u5B9A\u30
9
9
  length>1){throw new UsageError(`${ctx.flag} \u306E\u300C${input}\u300D\u304C${ctx.label}${distinct.length}\u4EF6\u306B\u4E00\u81F4\u3057\u307E\u3059: ${listCandidates(distinct)}`,`\u3069\u308C\u304B1\u3064\u306B\u6C7A\u307E\u308B\u5024\uFF08ID \u304B\u30B3\u30FC\u30C9\uFF09\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}const near=await suggest(input,candidates);throw new UsageError(`${ctx.flag} \u306E\u300C${input}\u300D\u306B\u4E00\u81F4\u3059\u308B${ctx.label}\u304C\u3042\u308A\u307E\u305B\u3093`,
10
10
  near.length>0?`\u3082\u3057\u304B\u3057\u3066: ${listCandidates(near,5)}\uFF08\u5168 ${candidates.length} \u4EF6\uFF09`:`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${listCandidates(candidates)}`)}function usable(value){return typeof value==="string"&&value.trim()!==""?value.trim():null}function resolveDefaultProject(explicit,profileName,env=process.env,cwd=process.cwd()){const fromFlag=usable(explicit);if(fromFlag!==null)return{ref:fromFlag,source:"flag"};const fromEnv=usable(env.TWP_PROJECT);if(fromEnv!==null)return{ref:fromEnv,source:"env"};const fromProjectConfig=usable(loadProjectConfig(cwd).project);if(fromProjectConfig!==null)return{ref:fromProjectConfig,source:"project-config"};const user=loadUserConfig(
11
11
  env);const fromProfile=usable(user.profiles?.[profileName]?.project);if(fromProfile!==null)return{ref:fromProfile,source:"user-config"};const fromUser=usable(user.project);if(fromUser!==null)return{ref:fromUser,source:"user-config"};return null}function requireDefaultProject(explicit,profileName,env=process.env,cwd=process.cwd()){const resolved=resolveDefaultProject(explicit,profileName,env,cwd);if(resolved!==null)return resolved;throw new UsageError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
12
- '--project <\u30B3\u30FC\u30C9|ID> \u3092\u4ED8\u3051\u308B\u304B\u3001TWP_PROJECT / .twp/config.json / ~/.twp/config.json \u306E "project" \u306B\u65E2\u5B9A\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002')}import crypto from"crypto";import fs from"fs";import path from"path";var DEFAULT_TTL_MS=10*60*1e3;var CACHE_VERSION=2;function cacheDir(env=process.env){return path.join(twpHomeDir(env),"cache")}function cacheFilePath(key,env=process.env){const digest=crypto.createHash("sha256").update(JSON.stringify([key.profile,key.scope,key.project??""])).digest("hex").slice(0,12);const label=key.scope.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,40);return path.join(cacheDir(env),`${label}-${digest}.json`)}function sameKey(a,b){return a.profile===b.profile&&a.scope===b.scope&&(a.project??
12
+ '--project <\u30B3\u30FC\u30C9|ID> \u3092\u4ED8\u3051\u308B\u304B\u3001TWP_PROJECT / .twp/config.json / ~/.twp/config.json \u306E "project" \u306B\u65E2\u5B9A\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002')}import crypto from"crypto";import fs from"fs";import path from"path";var DEFAULT_TTL_MS=10*60*1e3;var CACHE_VERSION=3;function cacheDir(env=process.env){return path.join(twpHomeDir(env),"cache")}function cacheFilePath(key,env=process.env){const digest=crypto.createHash("sha256").update(JSON.stringify([key.profile,key.scope,key.project??""])).digest("hex").slice(0,12);const label=key.scope.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,40);return path.join(cacheDir(env),`${label}-${digest}.json`)}function sameKey(a,b){return a.profile===b.profile&&a.scope===b.scope&&(a.project??
13
13
  "")===(b.project??"")}function isOursAndPrivate(target,check){if(process.platform==="win32")return true;try{const st=fs.lstatSync(target);if(st.isSymbolicLink())return false;const uid=process.getuid?.();if(uid!==void 0&&st.uid!==uid)return false;const forbidden=check==="file"?54:18;return(st.mode&forbidden)===0}catch{return false}}function isCacheLocationTrusted(env){const home=twpHomeDir(env);const dir=cacheDir(env);for(const target of[home,dir]){if(fs.existsSync(target)&&!isOursAndPrivate(target,
14
14
  "dir"))return false}return true}function readCache(key,options={}){if(options.refresh===true)return null;const env=options.env??process.env;const file=cacheFilePath(key,env);if(!isCacheLocationTrusted(env)||!isOursAndPrivate(file,"file"))return null;let parsed;try{parsed=JSON.parse(fs.readFileSync(file,"utf8"))}catch{return null}if(parsed?.version!==CACHE_VERSION||!parsed.key||!sameKey(parsed.key,key))return null;const fetchedAt=Date.parse(parsed.fetched_at);if(!Number.isFinite(fetchedAt))return null;
15
15
  const ttl=options.ttlMs??DEFAULT_TTL_MS;const now=(options.now??Date.now)();if(Math.abs(now-fetchedAt)>ttl)return null;return parsed.value}function writeCache(key,value,options={}){const env=options.env??process.env;const dir=cacheDir(env);const file=cacheFilePath(key,env);const body={version:CACHE_VERSION,key:{profile:key.profile,scope:key.scope,...key.project!==void 0?{project:key.project}:{}},fetched_at:new Date((options.now??Date.now)()).toISOString(),value};if(!isCacheLocationTrusted(env))return;
16
16
  const tmp=`${file}.${process.pid}.tmp`;try{fs.mkdirSync(dir,{recursive:true,mode:448});fs.writeFileSync(tmp,`${JSON.stringify(body)}
17
17
  `,{mode:384});fs.renameSync(tmp,file)}catch{try{fs.rmSync(tmp,{force:true})}catch{}}}var SELF_REF="me";var PRIVATE_TASKS_PATH="/api/v2/tasks/private";var PRIVATE_MASTERS_CACHE_KEY="__private__";var BACKLOG_SPACES_CACHE_KEY="__backlog__";var BACKLOG_SCOPE_LABEL="\u3053\u306E\u63A5\u7D9A\u5148";var BACKLOG_PROJECT_SCOPE_LABEL="\u3053\u306E Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8";var PRIVATE_SCOPE_LABEL="\u500B\u4EBA\u30BF\u30B9\u30AF";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function str(value){return typeof value==="string"&&
18
- value.trim()!==""?value:null}function truthyFlag(value){return value===true||value===1}function rawGetVia(client){return async path2=>{try{return{ok:true,status:200,json:await client.request("GET",path2),error:null}}catch(err){if(err instanceof ApiError){return{ok:false,status:err.status,json:err.body,error:err.message}}throw err}}}var Resolver=class{constructor(client,options){this.client=client;this.options=options;this.get=rawGetVia(client)}client;options;get;privateMastersInFlight=null;async project(ref){
18
+ value.trim()!==""?value:null}function truthyFlag(value){return value===true||value===1}function rawGetVia(client){return async path2=>{try{return{ok:true,status:200,json:await client.request("GET",path2),error:null}}catch(err){if(err instanceof ApiError){return{ok:false,status:err.status,json:err.body,error:err.message}}throw err}}}var TASK_MASTERS={status:{path:"task-statuses",envelope:"data",scope:"task-statuses",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"},type:{path:"task-types",envelope:"data",scope:"\
19
+ task-types",label:"\u7A2E\u5225"},category:{path:"task-categories",envelope:"data",scope:"task-categories",label:"\u30AB\u30C6\u30B4\u30EA"},milestone:{path:"task-milestones",envelope:"data",scope:"task-milestones",label:"\u30DE\u30A4\u30EB\u30B9\u30C8\u30FC\u30F3"},label:{path:"task-labels",envelope:"items",scope:"task-labels",label:"\u30E9\u30D9\u30EB"}};var Resolver=class{constructor(client,options){this.client=client;this.options=options;this.get=rawGetVia(client)}client;options;get;privateMastersInFlight=null;async project(ref){
19
20
  const trimmed=ref.trim();if(trimmed==="")throw new UsageError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30B3\u30FC\u30C9\u304B ID \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");return resolveProjectRef(trimmed,this.get,safeProjectIdPolicy)}async taskByKey(key){const trimmed=key.trim();if(!isTaskKey(trimmed)){throw new UsageError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u306E\u5F62\u5F0F\u3067\u306F\u3042\u308A\u307E\u305B\u3093: ${key}`,"\u30AD\u30FC\u306F\u300C\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30FC\u30C9-\u756A\u53F7\u300D\u306E\u5F62\u3067\u3059\uFF08\u4F8B: ABC-123\uFF09\u3002")}
20
21
  const res=await this.get(`/api/v2/tasks/resolve-by-key/${encodeURIComponent(trimmed)}`);if(res.status===404){throw new ResolveError(`\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${trimmed}\uFF08\u5B58\u5728\u3057\u306A\u3044\u304B\u3001\u95B2\u89A7\u3067\u304D\u308B\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306B\u3042\u308A\u307E\u305B\u3093\uFF09`,404)}if(!res.ok){throw new ResolveError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u3092\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: ${trimmed}\
21
22
  \uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const body=isRecord(res.json)?res.json:{};const projectId=str(body["project_id"]);const task=body["task"];if(projectId===null||!isRecord(task)){throw new ResolveError("\u30BF\u30B9\u30AF\u30AD\u30FC\u89E3\u6C7A\u306E\u5FDC\u7B54\u306B project_id / task \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
22
23
  res.status)}safeProjectIdPolicy.assertId(projectId);return{projectId,task}}async currentUser(){const res=await this.get("/api/v2/user");if(!res.ok){throw new ResolveError(`\u30ED\u30B0\u30A4\u30F3\u4E2D\u306E\u30E6\u30FC\u30B6\u30FC\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}\uFF09\u3002twp login \u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const user=isRecord(res.json)?res.json["user"]:void 0;if(!isRecord(user)||str(user["\
23
24
  id"])===null){throw new ResolveError("\u30E6\u30FC\u30B6\u30FC\u53D6\u5F97\u306E\u5FDC\u7B54\u306B user.id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",res.status)}return{id:user["id"],name:str(user["name"])??user["id"],email:str(user["email"])}}async status(projectId,input){return resolveNamed(this.applyAlias("status",input),await this.statuses(projectId),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"})}async taskType(projectId,input){
24
25
  return resolveNamed(this.applyAlias("type",input),await this.taskTypes(projectId),{flag:"--type",label:"\u7A2E\u5225"})}async assignee(projectId,input,flag="--assignee"){if(input.trim().toLowerCase()===SELF_REF)return this.self();const value=this.applyAlias("assignee",input);if(value.trim().toLowerCase()===SELF_REF)return this.self();return resolveNamed(value,await this.members(projectId),{flag,label:"\u30E1\u30F3\u30D0\u30FC"})}async self(){const me=await this.currentUser();return{id:me.id,name:me.
25
- name,...me.email!==null?{aliases:[me.email]}:{}}}async defaultStatus(projectId){return requireDefault(await this.statuses(projectId),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"})}async defaultTaskType(projectId){return requireDefault(await this.taskTypes(projectId),{flag:"--type",label:"\u7A2E\u5225"})}async statuses(projectId){return this.cached("task-statuses",projectId,()=>this.namedList(`/api/v2/projects/${encodeURIComponent(projectId)}/task-statuses`,"data","\u30B9\u30C6\u30FC\u30BF\u30B9",
26
- row=>({id:str(row["id"]),name:str(row["name"]),code:str(row["code"]),isDefault:truthyFlag(row["is_default"])})))}async taskTypes(projectId){return this.cached("task-types",projectId,()=>this.namedList(`/api/v2/projects/${encodeURIComponent(projectId)}/task-types`,"data","\u7A2E\u5225",row=>({id:str(row["id"]),name:str(row["name"]),code:str(row["code"]),isDefault:truthyFlag(row["is_default"])})))}async privateStatuses(){return this.privateMasters("statuses","\u30B9\u30C6\u30FC\u30BF\u30B9")}async privateTaskTypes(){
27
- return this.privateMasters("types","\u7A2E\u5225")}async privateStatus(input){return resolveNamed(this.applyAlias("status",input),await this.privateStatuses(),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateTaskType(input){return resolveNamed(this.applyAlias("type",input),await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultStatus(){return requireDefault(await this.privateStatuses(),{flag:"\
28
- --status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultTaskType(){return requireDefault(await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateTask(ref){const trimmed=ref.trim();const res=await this.get(`${PRIVATE_TASKS_PATH}/${encodeURIComponent(trimmed)}`);if(res.status===404){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${trimmed}`,404)}if(!res.
29
- ok){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: ${trimmed}\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const task=isRecord(res.json)?res.json["task"]:void 0;if(!isRecord(task)){throw new ResolveError("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u5FDC\u7B54\u306B task \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
30
- res.status)}return task}async privateMasters(envelope,label){return this.cached(`private-${envelope}`,PRIVATE_MASTERS_CACHE_KEY,async()=>namedListFrom(await this.privateMastersResponse(),envelope,label,row=>({id:str(row["id"]),name:str(row["name"]),code:str(row["code"]),isDefault:truthyFlag(row["is_default"])})))}privateMastersResponse(){this.privateMastersInFlight??=this.get(`${PRIVATE_TASKS_PATH}/masters`);return this.privateMastersInFlight}async members(projectId){return this.cached("members",
31
- projectId,()=>this.namedList(`/api/v2/projects/${encodeURIComponent(projectId)}/members`,"list","\u30E1\u30F3\u30D0\u30FC",row=>({id:str(row["user_id"]),name:str(row["user_name"]),code:null,aliases:[str(row["alias"]),str(row["user_email"])].filter(v=>v!==null)})))}async namedList(path2,envelope,label,map){return namedListFrom(await this.get(path2),envelope,label,map)}async cached(scope,projectId,load){const key={profile:this.options.profile,scope,project:projectId};const options={...this.options.
32
- env!==void 0?{env:this.options.env}:{},refresh:this.options.refresh,...this.options.ttlMs!==void 0?{ttlMs:this.options.ttlMs}:{},...this.options.now!==void 0?{now:this.options.now}:{}};const hit=readCache(key,options);if(hit!==null&&Array.isArray(hit))return hit;const fresh=await load();writeCache(key,fresh,options);return fresh}applyAlias(kind,input){const table=this.options.aliases?.[kind];if(table===void 0)return input;const needle=input.trim().toLowerCase();for(const[from,to]of Object.entries(
33
- table)){if(from.trim().toLowerCase()===needle&&typeof to==="string"&&to.trim()!=="")return to}return input}async backlogSpaces(){return this.cached("backlog-spaces",BACKLOG_SPACES_CACHE_KEY,()=>this.namedList(`${BACKLOG_BASE_PATH}/spaces`,"spaces","Backlog \u30B9\u30DA\u30FC\u30B9",backlogSpaceRow))}async backlogSpace(ref){return resolveNamed(ref,await this.backlogSpaces(),{flag:"--space",label:"Backlog \u30B9\u30DA\u30FC\u30B9",scope:BACKLOG_SCOPE_LABEL})}async backlogDefaultSpace(){const spaces=await this.
34
- backlogSpaces();if(spaces.length===1)return spaces[0];if(spaces.length===0){throw new UsageError("Backlog \u30B9\u30DA\u30FC\u30B9\u304C1\u4EF6\u3082\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093","TWP \u306E\u5916\u90E8\u9023\u643A\u8A2D\u5B9A\u3067 Backlog \u30B9\u30DA\u30FC\u30B9\u3092\u767B\u9332\u3057\u3066\u304F\u3060\u3055\u3044\uFF08twp backlog space list \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059\uFF09\u3002")}throw new UsageError(`Backlog \u30B9\u30DA\u30FC\u30B9\u304C ${spaces.
35
- length} \u4EF6\u767B\u9332\u3055\u308C\u3066\u3044\u308B\u305F\u3081\u3001--space \u30671\u3064\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,`twp backlog space list \u3067 ID \u3068\u30B9\u30DA\u30FC\u30B9URL\u3092\u78BA\u8A8D\u3067\u304D\u307E\u3059\u3002`)}async backlogProjects(spaceId){return this.cached("backlog-projects",spaceId,()=>this.namedList(backlogSpacePath(spaceId,"/projects"),"projects","Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",backlogProjectRow))}async backlogStatuses(spaceId,projectId){
36
- return this.cached("backlog-statuses",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/statuses`),"statuses","Backlog \u30B9\u30C6\u30FC\u30BF\u30B9",backlogStatusRow))}async backlogUsers(spaceId,projectId){return this.cached("backlog-users",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(
37
- projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/users`),"users","Backlog \u30E6\u30FC\u30B6\u30FC",backlogUserRow))}get apiClient(){return this.client}};function namedListFrom(res,envelope,label,map){if(!res.ok){throw new ResolveError(`${label}\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,
38
- res.status)}const list=isRecord(res.json)?res.json[envelope]:void 0;if(!Array.isArray(list)){throw new ResolveError(`${label}\u4E00\u89A7\u306E\u5FDC\u7B54\u306B ${envelope} \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return list.map((row,index)=>{const mapped=map(isRecord(row)?row:{});if(mapped.id===null||mapped.name===null){throw new ResolveError(`${label}\u4E00\u89A7\u306E ${index+1} \u4EF6\u76EE\u306B id /\
39
- \u540D\u524D\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return{id:mapped.id,name:mapped.name,...mapped.code!==void 0?{code:mapped.code}:{},...mapped.aliases!==void 0&&mapped.aliases.length>0?{aliases:mapped.aliases}:{},...mapped.isDefault!==void 0?{isDefault:mapped.isDefault}:{}}})}function requireDefault(candidates,ctx){const hit=candidates.find(ref=>ref.isDefault===true);if(hit!==void 0)return hit;throw new UsageError(
40
- `${ctx.flag} \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${ctx.scope??DEFAULT_LOOKUP_SCOPE}\u306B\u306F\u65E2\u5B9A\u306E${ctx.label}\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF09`,`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${candidates.map(ref=>ref.name).join(" / ")}\uFF08\u53E4\u3044\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u6B8B\u3063\u3066\u3044\u308B\u5834\u5408\u306F --refresh \u3067\u53D6\u308A\u76F4\u305B\u307E\u3059\uFF09`)}export{BACKLOG_BASE_PATH,backlogSpacePath,resolveNamed,requireDefaultProject,PRIVATE_TASKS_PATH,BACKLOG_SCOPE_LABEL,BACKLOG_PROJECT_SCOPE_LABEL,Resolver};
26
+ name,...me.email!==null?{aliases:[me.email]}:{}}}async defaultStatus(projectId){return requireDefault(await this.statuses(projectId),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"})}async defaultTaskType(projectId){return requireDefault(await this.taskTypes(projectId),{flag:"--type",label:"\u7A2E\u5225"})}async statuses(projectId){return namedFromRows(await this.taskMasterRows("status",projectId),"\u30B9\u30C6\u30FC\u30BF\u30B9",codedMasterRow)}async taskTypes(projectId){return namedFromRows(
27
+ await this.taskMasterRows("type",projectId),"\u7A2E\u5225",codedMasterRow)}async taskMaster(kind,projectId,input,flag){const spec=TASK_MASTERS[kind];return resolveNamed(input,await this.taskMasterRefs(kind,projectId),{flag,label:spec.label})}async taskMasterRefs(kind,projectId){const spec=TASK_MASTERS[kind];return namedFromRows(await this.taskMasterRows(kind,projectId),spec.label,codedMasterRow)}async privateTaskMaster(envelope,input,flag,label){return resolveNamed(input,await this.privateMasters(
28
+ envelope,label),{flag,label,scope:PRIVATE_SCOPE_LABEL})}async taskMasterRows(kind,projectId){const spec=TASK_MASTERS[kind];return this.cached(spec.scope,projectId,async()=>rawListFrom(await this.get(`/api/v2/projects/${encodeURIComponent(projectId)}/${spec.path}`),spec.envelope,spec.label))}async privateStatuses(){return this.privateMasters("statuses","\u30B9\u30C6\u30FC\u30BF\u30B9")}async privateTaskTypes(){return this.privateMasters("types","\u7A2E\u5225")}async privateStatus(input){return resolveNamed(
29
+ this.applyAlias("status",input),await this.privateStatuses(),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateTaskType(input){return resolveNamed(this.applyAlias("type",input),await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultStatus(){return requireDefault(await this.privateStatuses(),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultTaskType(){
30
+ return requireDefault(await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateTask(ref){const trimmed=ref.trim();const res=await this.get(`${PRIVATE_TASKS_PATH}/${encodeURIComponent(trimmed)}`);if(res.status===404){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${trimmed}`,404)}if(!res.ok){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: ${trimmed}\
31
+ \uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const task=isRecord(res.json)?res.json["task"]:void 0;if(!isRecord(task)){throw new ResolveError("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u5FDC\u7B54\u306B task \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",res.status)}return task}async privateMasters(envelope,label){
32
+ return namedFromRows(await this.privateMasterRows(envelope,label),label,codedMasterRow)}async privateMasterRows(envelope,label){return this.cached(`private-${envelope}`,PRIVATE_MASTERS_CACHE_KEY,async()=>rawListFrom(await this.privateMastersResponse(),envelope,label))}privateMastersResponse(){this.privateMastersInFlight??=this.get(`${PRIVATE_TASKS_PATH}/masters`);return this.privateMastersInFlight}async members(projectId){return this.cached("members",projectId,()=>this.namedList(`/api/v2/project\
33
+ s/${encodeURIComponent(projectId)}/members`,"list","\u30E1\u30F3\u30D0\u30FC",row=>({id:str(row["user_id"]),name:str(row["user_name"]),code:null,aliases:[str(row["alias"]),str(row["user_email"])].filter(v=>v!==null)})))}async namedList(path2,envelope,label,map){return namedListFrom(await this.get(path2),envelope,label,map)}async cached(scope,projectId,load){const key={profile:this.options.profile,scope,project:projectId};const options={...this.options.env!==void 0?{env:this.options.env}:{},refresh:this.
34
+ options.refresh,...this.options.ttlMs!==void 0?{ttlMs:this.options.ttlMs}:{},...this.options.now!==void 0?{now:this.options.now}:{}};const hit=readCache(key,options);if(hit!==null&&Array.isArray(hit))return hit;const fresh=await load();writeCache(key,fresh,options);return fresh}applyAlias(kind,input){const table=this.options.aliases?.[kind];if(table===void 0)return input;const needle=input.trim().toLowerCase();for(const[from,to]of Object.entries(table)){if(from.trim().toLowerCase()===needle&&typeof to===
35
+ "string"&&to.trim()!=="")return to}return input}async backlogSpaces(){return this.cached("backlog-spaces",BACKLOG_SPACES_CACHE_KEY,()=>this.namedList(`${BACKLOG_BASE_PATH}/spaces`,"spaces","Backlog \u30B9\u30DA\u30FC\u30B9",backlogSpaceRow))}async backlogSpace(ref){return resolveNamed(ref,await this.backlogSpaces(),{flag:"--space",label:"Backlog \u30B9\u30DA\u30FC\u30B9",scope:BACKLOG_SCOPE_LABEL})}async backlogDefaultSpace(){const spaces=await this.backlogSpaces();if(spaces.length===1)return spaces[0];
36
+ if(spaces.length===0){throw new UsageError("Backlog \u30B9\u30DA\u30FC\u30B9\u304C1\u4EF6\u3082\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093","TWP \u306E\u5916\u90E8\u9023\u643A\u8A2D\u5B9A\u3067 Backlog \u30B9\u30DA\u30FC\u30B9\u3092\u767B\u9332\u3057\u3066\u304F\u3060\u3055\u3044\uFF08twp backlog space list \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059\uFF09\u3002")}throw new UsageError(`Backlog \u30B9\u30DA\u30FC\u30B9\u304C ${spaces.length} \u4EF6\u767B\u9332\u3055\u308C\u3066\u3044\u308B\u305F\u3081\u3001--space \u30671\u3064\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,
37
+ `twp backlog space list \u3067 ID \u3068\u30B9\u30DA\u30FC\u30B9URL\u3092\u78BA\u8A8D\u3067\u304D\u307E\u3059\u3002`)}async backlogProjects(spaceId){return this.cached("backlog-projects",spaceId,()=>this.namedList(backlogSpacePath(spaceId,"/projects"),"projects","Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",backlogProjectRow))}async backlogStatuses(spaceId,projectId){return this.cached("backlog-statuses",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(
38
+ assertBacklogPathSegment(projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/statuses`),"statuses","Backlog \u30B9\u30C6\u30FC\u30BF\u30B9",backlogStatusRow))}async backlogUsers(spaceId,projectId){return this.cached("backlog-users",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/users`),"users","Backlog \u30E6\u30FC\u30B6\u30FC",backlogUserRow))}get apiClient(){
39
+ return this.client}};function rawListFrom(res,envelope,label){if(!res.ok){throw new ResolveError(`${label}\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const list=isRecord(res.json)?res.json[envelope]:void 0;if(!Array.isArray(list)){throw new ResolveError(`${label}\u4E00\u89A7\u306E\u5FDC\u7B54\u306B ${envelope}\
40
+ \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return list.map((row,index)=>{if(!isRecord(row)){throw new ResolveError(`${label}\u4E00\u89A7\u306E ${index+1} \u4EF6\u76EE\u304C\u60F3\u5B9A\u306E\u5F62\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return row})}function codedMasterRow(row){return{id:str(row["\
41
+ id"]),name:str(row["name"]),code:str(row["code"]),isDefault:truthyFlag(row["is_default"])}}function namedListFrom(res,envelope,label,map){return namedFromRows(rawListFrom(res,envelope,label),label,map,res.status??void 0)}function namedFromRows(rows,label,map,status=200){return rows.map((row,index)=>{const mapped=map(row);if(mapped.id===null||mapped.name===null){throw new ResolveError(`${label}\u4E00\u89A7\u306E ${index+1} \u4EF6\u76EE\u306B id / \u540D\u524D\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,
42
+ status)}return{id:mapped.id,name:mapped.name,...mapped.code!==void 0?{code:mapped.code}:{},...mapped.aliases!==void 0&&mapped.aliases.length>0?{aliases:mapped.aliases}:{},...mapped.isDefault!==void 0?{isDefault:mapped.isDefault}:{}}})}function requireDefault(candidates,ctx){const hit=candidates.find(ref=>ref.isDefault===true);if(hit!==void 0)return hit;throw new UsageError(`${ctx.flag} \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${ctx.scope??DEFAULT_LOOKUP_SCOPE}\u306B\u306F\u65E2\u5B9A\u306E${ctx.
43
+ label}\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF09`,`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${candidates.map(ref=>ref.name).join(" / ")}\uFF08\u53E4\u3044\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u6B8B\u3063\u3066\u3044\u308B\u5834\u5408\u306F --refresh \u3067\u53D6\u308A\u76F4\u305B\u307E\u3059\uFF09`)}export{BACKLOG_BASE_PATH,backlogSpacePath,resolveNamed,requireDefaultProject,PRIVATE_TASKS_PATH,BACKLOG_SCOPE_LABEL,BACKLOG_PROJECT_SCOPE_LABEL,TASK_MASTERS,Resolver};
@@ -6,7 +6,7 @@ this.note].join("\n");return Promise.resolve({outcome:"ok",usedAi:"noop",serverA
6
6
  super('\u5B9F\u884C\u30A8\u30F3\u30B8\u30F3\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\n \u5B9F AI \u3092\u8D77\u52D5\u3059\u308B\u306A\u3089 --engine cli\uFF08\u8A2D\u5B9A\u306A\u3089 "engine": "cli"\uFF09\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n \u9AA8\u683C\u3060\u3051\u3092\u691C\u8A3C\u3057\u305F\u3044\u5834\u5408\u306F --engine noop \u3092**\u660E\u793A**\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n \u26A0\uFE0F noop \u306F AI \u30921\u3064\u3082\u8D77\u52D5\u305B\u305A\u30A2\u30A4\u30C6\u30E0\u3092 completed \u306B\u3057\u307E\u3059\u3002**\u5B9F\u30AD\u30E5\u30FC\uFF08\u672C\u756A\u306E TWP \u7B49\uFF09\u3078\u5411\u3051\u306A\u3044\u3053\u3068**\n \u5B9A\u671F\u7531\u6765\u306E\u30A2\u30A4\u30C6\u30E0\u306A\u3089\u67A0\u307E\u3067\u6D88\u5316\u3055\u308C\u3001\u305D\u306E\u7A93\u306E release-deploy / develop-merge \u304C\u767A\u706B\u3057\u306A\u304F\u306A\u308A\u307E\u3059\u3002')}};var MAX_SCAN_BYTES=512*1024;var PROGRESS_PREFIX=/^\s*\[\d{2}:\d{2}:\d{2}\]\s*/;var FINAL_REPORT_BEGIN="<<<AI_FINAL_REPORT>>>";var FINAL_REPORT_END="<<<END_AI_FINAL_REPORT>>>";var TRANSCRIPT_MARKER=/^(>>|<<|⛔|!!)\s/;function stripProgressPrefix(line){return line.replace(PROGRESS_PREFIX,"").trim()}function stripTranscript(raw){return filterLines(raw,true)}function stripModelProse(raw){return filterLines(raw,false)}function filterLines(raw,dropToolLines){const out=[];let inReport=false;for(const line of raw.
7
7
  split("\n")){if(line.includes(FINAL_REPORT_BEGIN)){inReport=true;continue}if(line.includes(FINAL_REPORT_END)){inReport=false;continue}if(inReport||line.includes("\u{1F4AC}"))continue;if(dropToolLines&&TRANSCRIPT_MARKER.test(stripProgressPrefix(line)))continue;out.push(line)}return out.join("\n")}var UNTRUSTED_PATTERNS=[/has not been trusted/i,/Ignoring [0-9]+ permissions\.allow entries/i];function isUntrusted(raw){const text=stripTranscript(raw);return UNTRUSTED_PATTERNS.some(p=>p.test(text))}var CLI_FATAL_TEXT_PATTERNS=[
8
8
  /^api error\b/i,/^failed to authenticate\b/i];function isCliFatalText(text){const head=text.trim();return CLI_FATAL_TEXT_PATTERNS.some(p=>p.test(head))}var CODEX_PLAIN_LIMIT_PATTERNS=[/^(?:error\s*:\s*)?you(?:'ve| have)? hit (?:your|the) (?:usage|session|weekly|rate|quota|spend) (?:limit|cap)\b.*$/i,/^(?:error\s*:\s*)?(?:your|the) (?:usage|rate|session|quota) limit (?:has been )?(?:reached|exceeded)\b.*$/i,/^(?:error\s*:\s*)?(?:usage|rate|session|quota) limit (?:reached|exceeded)\b.*$/i,/^try again at\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{1,2}(?:st|nd|rd|th)?\b.*$/i];
9
- var CODEX_RUST_LIMIT_PATTERN=/^(?:\d{4}-\d{2}-\d{2}T\S+\s+)?(?:ERROR|WARN)\s+codex(?:[_:][a-z0-9_:-]+)*\s*:\s*.*(?:\b(?:429|529)\b|(?:usage|rate|session)[ ._-]*limit|quota[_ -]?(?:exhausted|exceeded))/i;var COMMON_LIMIT_PATTERNS=[/(?:status|code|http)[^a-z0-9]{0,10}429/i,/429[^0-9].{0,15}(?:too many|rate|throttl)/i,/(?:status|code|http)[^a-z0-9]{0,10}529/i,/529[^0-9].{0,15}overloaded/i,/too many requests/i,/max.?spend.?(?:limit|reached|exceeded)/i,/spending.?limit/i,/resets?\s+\d+(?::\d+)?\s*(?:am|pm)/i];
9
+ var CODEX_RUST_LIMIT_PATTERN=/^(?:\d{4}-\d{2}-\d{2}T\S+\s+)?(?:ERROR|WARN)\s+codex(?:[_:]+[a-z0-9-]+){0,8}\s*:\s*.*(?:\b(?:429|529)\b|(?:usage|rate|session)[ ._-]*limit|quota[_ -]?(?:exhausted|exceeded))/i;var COMMON_LIMIT_PATTERNS=[/(?:status|code|http)[^a-z0-9]{0,10}429/i,/429[^0-9].{0,15}(?:too many|rate|throttl)/i,/(?:status|code|http)[^a-z0-9]{0,10}529/i,/529[^0-9].{0,15}overloaded/i,/too many requests/i,/max.?spend.?(?:limit|reached|exceeded)/i,/spending.?limit/i,/resets?\s+\d+(?::\d+)?\s*(?:am|pm)/i];
10
10
  var GEMINI_LIMIT_PATTERNS=[/terminalquotaerror/i,/retryablequotaerror/i,/quota_exhausted/i,/model_capacity_exhausted/i,/exhausted your capacity/i,/no capacity available/i,/ratelimitexceeded/i];var CLAUDE_LIMIT_PATTERNS=[/rate.?limit/i,/usage.?limit/i,/session.?limit/i,/quota.?(?:exceeded|reached|limit)/i,/(?:api|server|model).{0,20}overloaded/i,/hit.{0,10}(?:your|the).{0,20}limit/i];function isRateLimited(raw,ai){const text=stripTranscript(raw);if(ai==="codex"){for(const line of text.split("\n")){
11
11
  const normalized=stripProgressPrefix(line);if(CODEX_RUST_LIMIT_PATTERN.test(normalized))return true;if(CODEX_PLAIN_LIMIT_PATTERNS.some(p=>fullMatch(p,normalized)))return true}return false}const patterns=[...COMMON_LIMIT_PATTERNS,...ai==="gemini"?GEMINI_LIMIT_PATTERNS:[],...ai==="claude"?CLAUDE_LIMIT_PATTERNS:[]];return patterns.some(p=>p.test(text))}function fullMatch(pattern,value){const m=pattern.exec(value);return m!==null&&m[0]===value}var AUTH_ERROR_PATTERNS=[/(?:status|code|http)[^a-z0-9]{0,10}401/i,
12
12
  /(?:status|code|http)[^a-z0-9]{0,10}403/i,/401\s+unauthorized/i,/403\s+forbidden/i,/invalid.{0,10}(?:api.?key|token|credential)/i,/authentication.{0,10}(?:failed|error|invalid)/i,/(?:api.?key|token).{0,10}(?:invalid|expired|missing|rejected)/i,/not logged in/i,/please (?:run )?login/i,/(?:codex|gemini|copilot|claude)\s+login/i,/failed to authenticate/i,/oauth (?:session|token).{0,30}(?:expired|invalid|revoked)/i];function isAuthError(raw){const text=stripModelProse(raw);return AUTH_ERROR_PATTERNS.
@@ -14,4 +14,4 @@ some(p=>p.test(text))}function rateLimitWaitSeconds(raw,now=new Date){const clau
14
14
  hour,minute,0,0);if(reset.getTime()<=now.getTime())reset.setDate(reset.getDate()+1);const wait=Math.trunc((reset.getTime()-now.getTime())/1e3);if(wait>0&&wait<=21600)return wait+30}}const gemini=/reset\s+after\s+(\d+)h(\d+)m(?:(\d+)s)?/i.exec(raw);if(gemini){const wait=Number(gemini[1])*3600+Number(gemini[2])*60+Number(gemini[3]??0);if(wait>0&&wait<=86400)return wait+30}const codex=/try again at\s+(\w+)\s+(\d+)(?:st|nd|rd|th)?,?\s*(\d{4})?\s+(\d{1,2}):(\d{2})\s*(AM|PM)/i.exec(raw);if(codex){const months={
15
15
  jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};const mon=months[(codex[1]??"").slice(0,3).toLowerCase()];if(mon!==void 0){let hour=Number(codex[4]);const ampm=(codex[6]??"").toLowerCase();if(ampm==="pm"&&hour!==12)hour+=12;else if(ampm==="am"&&hour===12)hour=0;const year=codex[3]?Number(codex[3]):now.getFullYear();const reset=new Date(year,mon,Number(codex[2]),hour,Number(codex[5]),0,0);const wait=Math.trunc((reset.getTime()-now.getTime())/1e3);if(wait>0)return wait+30}}
16
16
  return null}function maxTurnsReached(raw,maxTurns){if(!Number.isFinite(maxTurns)||maxTurns<=0)return false;const matches=raw.match(/完了 \(turns: (\d+)/g);const last=matches?.[matches.length-1];if(last===void 0)return false;const turns=Number.parseInt(/(\d+)$/.exec(last)?.[1]??"",10);return Number.isInteger(turns)&&turns>=maxTurns}function tailForScan(text){return text.length<=MAX_SCAN_BYTES?text:text.slice(text.length-MAX_SCAN_BYTES)}var HINT_MAX_CHARS=200;var HINT_ALLOWED=[/^(?:error|fatal|panic|exception|warn(?:ing)?)\b\s*[:!-]?\s/i,
17
- /^(?:\d{4}-\d{2}-\d{2}T\S+\s+)?(?:ERROR|WARN)\s+codex(?:[_:][a-z0-9_-]+)*\s*:/i,/^api error\b/i,/^failed to authenticate\b/i];function failureHint(raw){const text=stripTranscript(tailForScan(raw));const lines=text.split("\n");for(let i=lines.length-1;i>=0;i-=1){const line=stripProgressPrefix(lines[i]??"");if(line===""||!HINT_ALLOWED.some(p=>p.test(line)))continue;const points=Array.from(line);return points.length<=HINT_MAX_CHARS?line:`${points.slice(0,HINT_MAX_CHARS).join("")}\u2026`}return""}export{isAiUnavailable,needsHumanToRestoreAi,aiUnavailableLabel,isServerAiType,NoopEngine,UnknownEngineError,assertKnownEngine,EngineNotConfiguredError,isUntrusted,isCliFatalText,isRateLimited,isAuthError,rateLimitWaitSeconds,maxTurnsReached,tailForScan,failureHint};
17
+ /^(?:\d{4}-\d{2}-\d{2}T\S+\s+)?(?:ERROR|WARN)\s+codex(?:[_:]+[a-z0-9-]+){0,8}\s*:/i,/^api error\b/i,/^failed to authenticate\b/i];function failureHint(raw){const text=stripTranscript(tailForScan(raw));const lines=text.split("\n");for(let i=lines.length-1;i>=0;i-=1){const line=stripProgressPrefix(lines[i]??"");if(line===""||!HINT_ALLOWED.some(p=>p.test(line)))continue;const points=Array.from(line);return points.length<=HINT_MAX_CHARS?line:`${points.slice(0,HINT_MAX_CHARS).join("")}\u2026`}return""}export{isAiUnavailable,needsHumanToRestoreAi,aiUnavailableLabel,isServerAiType,NoopEngine,UnknownEngineError,assertKnownEngine,EngineNotConfiguredError,isUntrusted,isCliFatalText,isRateLimited,isAuthError,rateLimitWaitSeconds,maxTurnsReached,tailForScan,failureHint};
package/dist/cli.js CHANGED
@@ -23,7 +23,7 @@ fig-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file")}if(out.
23
23
  --verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopForce){out.unknown.push("--force")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopDrain){out.unknown.push("--drain")}if(out.command==="task-loop"&&out.taskLoopAction==="stop"&&out.stopForce&&out.stopDrain){out.unknown.push("--force\
24
24
  \u3068 --drain \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");out.stopForce=false;out.stopDrain=false}if(out.command==="task-loop"&&out.taskLoopAction!=="setup"){if(out.yes)out.unknown.push("--yes");if(out.ais!==void 0)out.unknown.push("--ai");if(out.workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file")}if(out.command==="task-loop"&&(out.taskLoopAction===
25
25
  "stop"||out.taskLoopAction==="status")){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="setup"){if(out.engine!==void 0)out.unknown.push("--engine");if(out.safe)out.unknown.push("--safe");if(out.
26
- daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}return out}var VERSION=true?"0.12.0":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
26
+ daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}return out}var VERSION=true?"0.14.0":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
27
27
 
28
28
  \u4F7F\u3044\u65B9:
29
29
  twp \u5BFE\u8A71 TUI \u3092\u8D77\u52D5
@@ -94,6 +94,11 @@ daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force
94
94
  \u30B3\u30E1\u30F3\u30C8\u306E\u672C\u6587\u3092\u66F8\u304D\u63DB\u3048\u308B\uFF08--task \u304C\u8981\u308B\uFF09
95
95
  twp task comment delete <\u30B3\u30E1\u30F3\u30C8ID>
96
96
  \u30B3\u30E1\u30F3\u30C8\u3092\u524A\u9664\u3059\u308B\uFF08--task \u3068 --yes \u304C\u8981\u308B\uFF09
97
+ twp task status list --status \u306B\u6E21\u305B\u308B\u30B9\u30C6\u30FC\u30BF\u30B9\u3092\u4E00\u89A7\u3059\u308B\uFF08\u65E2\u5B9A\u306F is_default\uFF09
98
+ twp task type list --type \u306B\u6E21\u305B\u308B\u7A2E\u5225\u3092\u4E00\u89A7\u3059\u308B
99
+ twp task category list \u30BF\u30B9\u30AF\u306E\u30AB\u30C6\u30B4\u30EA\u3092\u4E00\u89A7\u3059\u308B
100
+ twp task milestone list \u30BF\u30B9\u30AF\u306E\u30DE\u30A4\u30EB\u30B9\u30C8\u30FC\u30F3\u3092\u4E00\u89A7\u3059\u308B
101
+ twp task label list \u30BF\u30B9\u30AF\u306E\u30E9\u30D9\u30EB\u3092\u4E00\u89A7\u3059\u308B
97
102
  twp backlog space list \u9023\u643A\u6E08\u307F\u306E Backlog \u30B9\u30DA\u30FC\u30B9\u3092\u4E00\u89A7\u3059\u308B
98
103
  twp backlog project list
99
104
  Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u4E00\u89A7\u3059\u308B
@@ -143,8 +148,8 @@ TUI \u5185:
143
148
  `);process.exit(1)}ignoreEpipe(process.stdout);ignoreEpipe(process.stderr);const args=parseArgv(process.argv.slice(2));if(args.command==="version"){process.stdout.write(`${VERSION}
144
149
  `);return}if(args.command==="help"){process.stdout.write(HELP);return}if(args.unknown.length>0){process.stderr.write(`\u4E0D\u660E\u306A\u5F15\u6570: ${args.unknown.join(" ")}
145
150
 
146
- ${HELP}`);process.exitCode=2;return}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-TCAJZMNJ.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:{},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.
151
+ ${HELP}`);process.exitCode=2;return}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-6FWRZNZR.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:{},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.
147
152
  refresh},version:VERSION});return}if(args.command==="update"){const{runUpdate}=await import("./update-WDWUECN7.js");process.exitCode=await runUpdate({...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}if(args.command==="login"||args.command==="logout"||args.command==="whoami"){const{runLogin,runLogout,runWhoami}=await import("./commands-YPT6RK74.js");const options={profile:args.profile,method:args.loginMethod,tenant:args.tenant,noBrowser:args.loginNoBrowser,cliVersion:VERSION};
148
- 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-HYHUXQZT.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.
149
- engine,version:VERSION,verbose:args.verbose,scheduleNow:args.scheduleNow,scheduleCounts:args.scheduleCounts,scheduleGate:args.scheduleGate,yes:args.yes,ais:args.ais,workspace:args.workspace,aiConfigFile:args.aiConfigFile,noAiConfigFile:args.noAiConfigFile});return}if(args.command==="print"){const{runOneShot}=await import("./oneshot-MRU4IY7W.js");process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.
150
- permissionMode}:{},...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-XMSO3KWO.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();
153
+ 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-MQ32SI5I.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.
154
+ engine,version:VERSION,verbose:args.verbose,scheduleNow:args.scheduleNow,scheduleCounts:args.scheduleCounts,scheduleGate:args.scheduleGate,yes:args.yes,ais:args.ais,workspace:args.workspace,aiConfigFile:args.aiConfigFile,noAiConfigFile:args.noAiConfigFile});return}if(args.command==="print"){const{runOneShot}=await import("./oneshot-4RW7KWY5.js");process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.
155
+ permissionMode}:{},...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-OOHRCRTG.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();