@tocca-systems/twp-cli 0.61.1 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.public.md +6 -0
- package/dist/{agent-loop-DFTHXSGN.js → agent-loop-SWXPY3OD.js} +2 -2
- package/dist/{ai-dispatch-M42S3SLX.js → ai-dispatch-EEX3FOFD.js} +3 -12
- package/dist/{api-command-4WOUH5PL.js → api-command-G2TNSWKE.js} +1 -1
- package/dist/{app-UJE2OSRN.js → app-AOB26ORS.js} +1 -1
- package/dist/{chunk-HAA3YDV2.js → chunk-2B7A3OY7.js} +26 -18
- package/dist/{chunk-OIC5Z6M3.js → chunk-3YG7EN3Y.js} +1 -1
- package/dist/chunk-DXUFECE7.js +13 -0
- package/dist/{chunk-27BLHO7A.js → chunk-NXWXTUU6.js} +1 -1
- package/dist/chunk-QEWCTKPV.js +15 -0
- package/dist/{chunk-OPRRLLVH.js → chunk-YNRONUTZ.js} +2 -2
- package/dist/cli.js +7 -7
- package/dist/{commands-5E6DNXCQ.js → commands-RCCF5ZRU.js} +37 -34
- package/dist/{commands-EYEMPZJX.js → commands-WIQVCMQE.js} +1 -1
- package/dist/{logout-guard-HZLNYFXC.js → logout-guard-GQBF3GQH.js} +1 -1
- package/dist/{media-YU4GJOH2.js → media-GAL5WENN.js} +1 -1
- package/dist/{registry-664USKMN.js → registry-JABWR2GZ.js} +1 -1
- package/dist/{run-F2MRZYJO.js → run-5COXNYKX.js} +1 -1
- package/dist/{server-settings-EINXR7SK.js → server-settings-3YD7RR3A.js} +1 -1
- package/dist/{setup-QJAHEDFF.js → setup-U22KITRG.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-OLASZWF5.js +0 -13
package/CHANGELOG.public.md
CHANGED
|
@@ -11,6 +11,12 @@
|
|
|
11
11
|
`CHANGELOG.md` に残してあります。顧客向けの履歴は public 公開以降を対象とします。
|
|
12
12
|
-->
|
|
13
13
|
|
|
14
|
+
## 0.62.0
|
|
15
|
+
|
|
16
|
+
`twp task-loop` のループ設定に `operations.plan_gate` を追加しました。計画の前に指定したコマンドで入力の指紋を取り、前回の計画から変化が無ければ計画の AI を起動しません(コマンドが失敗したときや、`max_skip_sec` を過ぎたときは計画します)。
|
|
17
|
+
|
|
18
|
+
エージェントループで、計画のラベルに角括弧([ ])が含まれていると計画が読み取れず、何も実行されないまま終了することがある不具合を修正しました。
|
|
19
|
+
|
|
14
20
|
## 0.61.1
|
|
15
21
|
|
|
16
22
|
Microsoft 365 系のコマンドで、組織のデバイスポリシー(条件付きアクセス)によりアクセスが拒否された場合に、再ログインの案内ではなく原因とテナント管理者への確認を促すメッセージを表示するようにしました。
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{stepToItem}from"./chunk-
|
|
4
|
-
isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiResponseError,UsageError}from"./chunk-VFPY2A23.js";import"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var LABEL="\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30EB\u30FC\u30D7\u306E\u30A2\u30A4\u30C6\u30E0";var STATUSES=["pending","processing","completed","failed"];var AI_TYPES=["claude","gemini","codex","copilot"];var EFFORTS=["low","medium","high","xhigh","max"];var PRIORITIES=["P0","P1","P2","P3"];var LIST_COLUMNS=["item_id","status","task_key","label","ai_type","ai_effort","runner_id","created_at"];var GET_COLUMNS=["item_id","status","task_key","label","prompt","ai_type","ai_model","ai_effort","runn\
|
|
3
|
+
import{stepToItem}from"./chunk-QEWCTKPV.js";import{loadLocalConfig}from"./chunk-2B7A3OY7.js";import"./chunk-DXUFECE7.js";import{loadAiConfig}from"./chunk-AEJHDFXB.js";import"./chunk-N2UVRM3Z.js";import"./chunk-AT432SCP.js";import"./chunk-GY7KI5E5.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";import"./chunk-II5RVJQN.js";
|
|
4
|
+
import{acknowledgement,isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiResponseError,UsageError}from"./chunk-VFPY2A23.js";import"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var LABEL="\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30EB\u30FC\u30D7\u306E\u30A2\u30A4\u30C6\u30E0";var STATUSES=["pending","processing","completed","failed"];var AI_TYPES=["claude","gemini","codex","copilot"];var EFFORTS=["low","medium","high","xhigh","max"];var PRIORITIES=["P0","P1","P2","P3"];var LIST_COLUMNS=["item_id","status","task_key","label","ai_type","ai_effort","runner_id","created_at"];var GET_COLUMNS=["item_id","status","task_key","label","prompt","ai_type","ai_model","ai_effort","runn\
|
|
5
5
|
er_id","attempt_count","reclaim_count","error_message","created_by_name","created_at","started_at","completed_at"];var HISTORY_COLUMNS=["item_id","status","task_key","skill","ai_type","runner_id","duration_ms","cost_usd","created_at"];var PROJECT_FLAG={name:"--project",summary:"\u30AD\u30E5\u30FC\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF08\u30B3\u30FC\u30C9\u307E\u305F\u306F ID\u3002\u7701\u7565\u6642\u306F TWP_PROJECT / .twp/config.json / ~/.twp/config.json\uFF09",takesValue:true,placeholder:"\
|
|
6
6
|
<\u30B3\u30FC\u30C9|ID>"};var ITEM_FLAG={name:"--item",summary:"\u30A2\u30A4\u30C6\u30E0\u306E ID\uFF08item_id\uFF09\u3002\u4F4D\u7F6E\u5F15\u6570\u3068\u540C\u3058\u610F\u5473\uFF08\u4E21\u65B9\u6307\u5B9A\u306F\u30A8\u30E9\u30FC\uFF09",takesValue:true,placeholder:"<\u30A2\u30A4\u30C6\u30E0ID>"};var FORBIDDEN_CORE="\u30C6\u30CA\u30F3\u30C8\u306E\u7BA1\u7406\u8005\uFF08admin \u30ED\u30FC\u30EB\uFF09\u306E\u6A29\u9650\u304C\u5FC5\u8981\u3067\u3059\uFF08\u500B\u4EBA\u30AD\u30E5\u30FC\u3092\u9664\u304F\uFF09";
|
|
7
7
|
var CREATE_HINT="\u30A2\u30A4\u30C6\u30E0\u306E\u6295\u5165\uFF08twp agent-loop create\uFF09\u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30E1\u30F3\u30D0\u30FC\u306A\u3089\u7BA1\u7406\u8005\u3067\u306A\u304F\u3066\u3082\u884C\u3048\u307E\u3059";var FORBIDDEN_UPDATE=`\u30AD\u30E5\u30FC\u306E\u30A2\u30A4\u30C6\u30E0\u306E\u66F4\u65B0\u306B\u306F${FORBIDDEN_CORE}\u3002\u5B9F\u884C\u4E2D\u306E\u30A2\u30A4\u30C6\u30E0\u3078\u306E\u66F8\u304D\u623B\u3057\u3060\u3051\u306F\u3001\u305D\u306E\u30A2\u30A4\u30C6\u30E0\u3092 claim \u3057\u305F\u30EB\u30FC\u30D7\u81EA\u8EAB\u304C run_id \u3092\u6DFB\u3048\u3066\u884C\u3048\u307E\u3059\u3002`+
|
|
@@ -1,17 +1,8 @@
|
|
|
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-ZOOEH7ZE.js";import{detectAiClis}from"./chunk-T4QZO6RQ.js";import{expandServerSkills,prepareSkillOverlay}from"./chunk-MPEHKAAL.js";import"./chunk-YJZT3UD3.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import{DEFAULT_CLAUDE_LAUNCHER,activeSlotPath,
|
|
4
|
-
resolveSpawnTarget,usesBedrock,wrapWithAutoSwitch}from"./chunk-AEJHDFXB.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import"./chunk-AT432SCP.js";import"./chunk-GY7KI5E5.js";import"./chunk-VFPY2A23.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";
|
|
5
|
-
|
|
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\
|
|
7
|
-
\u884C\u306F\u7D99\u7D9A\u3057\u307E\u3059`)]}if(resets!==null)this.result.resetsAt=resets;this.result.rateLimited=true;return[this.line(`\u26A0\uFE0F \u30EC\u30FC\u30C8\u30EA\u30DF\u30C3\u30C8\u901A\u77E5: status=${status}${at}`)]}onAssistant(event){const out=[];for(const block of contentBlocks(event)){if(block.type==="tool_use"){const name=typeof block.name==="string"?block.name:"tool";if(typeof block.id==="string")this.toolNames.set(block.id,name);this.toolCount+=1;out.push(this.line(`>> ${name}${toolDetail(
|
|
8
|
-
name,block.input)}`))}else if(block.type==="text"&&typeof block.text==="string"&&block.text.trim()!==""){for(const l of block.text.trim().split("\n"))out.push(this.line(` \u{1F4AC} ${l}`))}}return out}onUser(event){const out=[];for(const block of contentBlocks(event)){if(block.type!=="tool_result")continue;const id=typeof block.id==="string"?block.id:"";const useId=typeof block.tool_use_id==="string"?block.tool_use_id:id;const name=this.toolNames.get(useId)??"tool";this.toolNames.delete(useId);
|
|
9
|
-
const isError=block.is_error===true;const detail=isError?firstErrorLine(block):"";out.push(this.line(`${isError?"!!":"<<"} ${name}${detail}`))}return out}onResult(event){const r=this.result;r.subtype=typeof event["subtype"]==="string"?event["subtype"]:null;r.isError=typeof event["is_error"]==="boolean"?event["is_error"]:null;r.numTurns=typeof event["num_turns"]==="number"?event["num_turns"]:null;r.costUsd=typeof event["total_cost_usd"]==="number"?event["total_cost_usd"]:null;r.durationMs=typeof event["\
|
|
10
|
-
duration_ms"]==="number"?event["duration_ms"]:null;const usage=event["usage"];if(usage!==null&&typeof usage==="object"&&!Array.isArray(usage)){const u=usage;const num=key=>typeof u[key]==="number"?u[key]:0;const hasIn=["input_tokens","cache_creation_input_tokens","cache_read_input_tokens"].some(k=>typeof u[k]==="number");r.tokensIn=hasIn?num("input_tokens")+num("cache_creation_input_tokens")+num("cache_read_input_tokens"):null;r.tokensOut=typeof u["output_tokens"]==="number"?u["output_tokens"]:null}
|
|
11
|
-
const out=[this.line(`\u5B8C\u4E86 (turns: ${r.numTurns??0}, tools: ${this.toolCount}, ${Math.round((r.durationMs??0)/1e3)}s, $${(r.costUsd??0).toFixed(3)})`)];const text=typeof event["result"]==="string"?event["result"]:"";r.finalText=text;if(text!==""){out.push(FINAL_REPORT_BEGIN,text,FINAL_REPORT_END)}return out}line(msg){const d=this.now();const ts=`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;return` [${ts}] ${msg}`}};function firstErrorLine(block){const content=block.
|
|
12
|
-
content;const text=typeof content==="string"?content:Array.isArray(content)?content.map(c=>c!==null&&typeof c==="object"&&typeof c.text==="string"?c.text:"").join(" "):"";const first=text.trim().split("\n")[0]??"";return first===""?"":` | ${first.slice(0,120)}`}function contentBlocks(event){const message=event["message"];if(message===null||typeof message!=="object")return[];const content=message["content"];if(!Array.isArray(content))return[];return content.filter(b=>b!==null&&typeof b==="object")}
|
|
13
|
-
function toolDetail(name,input){if(input===void 0||input===null)return"";const str=k=>typeof input[k]==="string"?input[k]:"";if(name==="Bash"){const cmd=str("command");return cmd===""?"":` $ ${cmd.slice(0,80)}${cmd.length>80?"...":""}`}if(name==="Read"||name==="Write"||name==="Edit"){const p=str("file_path");return p===""?"":` ${p}`}if(name==="Grep"||name==="Glob"){const p=str("pattern");return p===""?"":` '${p}'`}if(name==="Skill"){const s=str("skill");return s===""?"":` /${s}`}if(name.includes(
|
|
14
|
-
"mcp__")){const args=[];for(const k of["task_id","project_id","status_id","issue_id"]){const v=str(k);if(v!=="")args.push(`${k}=${v.slice(0,16)}`)}return args.length===0?"":` (${args.slice(0,2).join(", ")})`}return""}function pad(n){return String(n).padStart(2,"0")}function isSaneEpochSec(v){return v!==null&&Number.isFinite(v)&&Math.abs(v)<864e10}var DEFAULT_AI_TIMING={abortGraceMs:5e3,abortReapMs:2e3,pollIntervalMs:5e3};function resolveTiming(over){return{abortGraceMs:over?.abortGraceMs??DEFAULT_AI_TIMING.abortGraceMs,abortReapMs:over?.abortReapMs??DEFAULT_AI_TIMING.abortReapMs,pollIntervalMs:over?.pollIntervalMs??DEFAULT_AI_TIMING.pollIntervalMs}}var MAX_RETAINED_BYTES=4*1024*1024;function closeStream(stream){return new Promise(resolve=>{if(stream===null)return resolve();stream.once("error",()=>resolve());stream.end(()=>resolve())})}function buildArgs(req,cfg,env,workspace){
|
|
3
|
+
import{failureHint,isAuthError,isCliFatalText,isRateLimited,isServerAiType,isUntrusted,maxTurnsReached,rateLimitWaitSeconds,tailForScan}from"./chunk-ZOOEH7ZE.js";import{detectAiClis}from"./chunk-T4QZO6RQ.js";import{expandServerSkills,prepareSkillOverlay}from"./chunk-MPEHKAAL.js";import"./chunk-YJZT3UD3.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import{ClaudeStreamRenderer}from"./chunk-DXUFECE7.js";import{DEFAULT_CLAUDE_LAUNCHER,activeSlotPath,
|
|
4
|
+
detectClaudeAutoSwitch,isClaudeAi,isUsableModelId,modelFitsRoute,resolveSpawnTarget,usesBedrock,wrapWithAutoSwitch}from"./chunk-AEJHDFXB.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import"./chunk-AT432SCP.js";import"./chunk-GY7KI5E5.js";import"./chunk-VFPY2A23.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";
|
|
5
|
+
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 DEFAULT_AI_TIMING={abortGraceMs:5e3,abortReapMs:2e3,pollIntervalMs:5e3};function resolveTiming(over){return{abortGraceMs:over?.abortGraceMs??DEFAULT_AI_TIMING.abortGraceMs,abortReapMs:over?.abortReapMs??DEFAULT_AI_TIMING.abortReapMs,pollIntervalMs:over?.pollIntervalMs??DEFAULT_AI_TIMING.pollIntervalMs}}var MAX_RETAINED_BYTES=4*1024*1024;function closeStream(stream){return new Promise(resolve=>{if(stream===null)return resolve();stream.once("error",()=>resolve());stream.end(()=>resolve())})}function buildArgs(req,cfg,env,workspace){
|
|
15
6
|
const warnings=[];const requested=(req.model??"").trim();const usable=requested!==""&&isUsableModelId(requested);if(requested!==""&&!usable){warnings.push(`ai_model '${requested}' \u306F\u4F7F\u3048\u306A\u3044\u5F62\u3067\u3059 \u2192 \u30AB\u30C6\u30B4\u30EA\u65E2\u5B9A\u306E\u30E2\u30C7\u30EB\u3092\u4F7F\u3044\u307E\u3059`)}const fitsRoute=!usable||!isClaudeAi(req.ai)||modelFitsRoute(requested,env);if(usable&&!fitsRoute){warnings.push(`ai_model '${requested}' \u306F\u73FE\u5728\u306E\u5B9F\u884C\u7D4C\u8DEF\u3067\u306F\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\uFF08\u3053\u306E\u6A5F\u4F53\u306F ${usesBedrock(
|
|
16
7
|
env)?"Bedrock":"Anthropic \u76F4"}\uFF09 \u2192 \u30AB\u30C6\u30B4\u30EA\u65E2\u5B9A\u306E\u30E2\u30C7\u30EB\u3092\u4F7F\u3044\u307E\u3059`)}const fallback=cfg.modelFor(req.ai,req.category,env);const safeFallback=fallback===""||!isClaudeAi(req.ai)||modelFitsRoute(fallback,env)?fallback:"";if(fallback!==""&&safeFallback===""){warnings.push(`CLAUDE_MODEL '${fallback}' \u3082\u73FE\u5728\u306E\u5B9F\u884C\u7D4C\u8DEF\u3067\u306F\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093 \u2192 \u30E2\u30C7\u30EB\u3092\u6307\u5B9A\u3057\u307E\u305B\u3093`)}
|
|
17
8
|
const model=usable&&fitsRoute?requested:safeFallback;const maxTurns=cfg.maxTurnsFor(req.category,env);let effort="";switch(req.ai){case"gemini":return{file:"gemini",args:["--yolo",...model?["--model",model]:[]],env:{GEMINI_CLI_TRUST_WORKSPACE:"true"},model,effort,maxTurns,warnings};case"codex":return{file:"codex",args:["exec","-s","danger-full-access",...model?["--model",model]:[]],env:{},model,effort,maxTurns,warnings};case"copilot":{const mcp=path.join(workspace,".copilot","mcp-config.json");const args=[
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{describeWaitResult,parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";import{NO_REDACT_FLAG,NO_REDACT_NOTICE,exitCodeFor,fetchAllPages,reportError}from"./chunk-
|
|
3
|
+
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{describeWaitResult,parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";import{NO_REDACT_FLAG,NO_REDACT_NOTICE,exitCodeFor,fetchAllPages,reportError}from"./chunk-3YG7EN3Y.js";import"./chunk-YNRONUTZ.js";import{evaluateQuery}from"./chunk-GFLGXGWE.js";import{renderOutput}from"./chunk-YXVN6OCH.js";
|
|
4
4
|
import{redactSecretValues,redactSecrets,withDebug}from"./chunk-UFGJSWKU.js";import"./chunk-Q3B65OFC.js";import{parseOperationArgs,repeatedValues}from"./chunk-RX5HWI4L.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,envelopePaging,isPageNumberEnvelope,pageRangeNotes,positiveInteger,readEnvelopeCursor,readPageNumberCursor,shellQuote}from"./chunk-MI6HVYR2.js";import{readBody}from"./chunk-6LSQCOCJ.js";import"./chunk-MYWDL3WX.js";import"./chunk-HVZUXLQ4.js";import{
|
|
5
5
|
ApiError,TwpApiClient,appendQuery}from"./chunk-JA5A6UJ2.js";import"./chunk-H4CDX4TX.js";import"./chunk-II5RVJQN.js";import"./chunk-3ZRMMBP5.js";import{ApiResponseError,EXIT_OK,EXIT_WAIT_TIMEOUT,NetworkError,UsageError}from"./chunk-VFPY2A23.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-PECIBNFD.js";import{AuthSession,NotLoggedInError,SessionExpiredError,loadCredentials}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,
|
|
6
6
|
resolveConfiguredOutput,resolveProfile}from"./chunk-4VZKNEVN.js";import"./chunk-RZVI6PMW.js";import{HELP_TOKEN}from"./chunk-QZBE4KC2.js";import"./chunk-QQRJLH6B.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-74BPZOKU.js";import"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var MIN_SEGMENT_CHARS=3;var parsedCache=new WeakMap;function splitSegments(path){return path.split("/").filter(segment=>segment!=="")}function parseRoutes(routes){const cached=parsedCache.get(routes);if(cached!==void 0)return cached;const parsed=[];for(const[key,domain]of Object.entries(routes.routes)){const space=key.indexOf(" ");if(space<=0)continue;const template=key.slice(space+1);parsed.push({method:key.slice(0,space),template,domain,segments:splitSegments(template).map(segment=>/^\{[^/{}]+\}$/.
|
|
@@ -1212,7 +1212,7 @@ cwd()){const listed=await gitListFiles(cwd2);const raw=listed??await walkFiles(c
|
|
|
1212
1212
|
1;const after=/^[^\s]*/.exec(text.slice(cursor))?.[0]??"";return{query,start,end:cursor+after.length}}var TWP_SLASH_ROUTES={"/tasks":{domain:"task",operation:"list"},"/task":{domain:"task",operation:"get"},"/projects":{domain:"project",operation:"list"}};function isTwpSlashCommand(name){return Object.hasOwn(TWP_SLASH_ROUTES,name)}async function runTwpSlashCommand(name,args,deps){const route=TWP_SLASH_ROUTES[name];if(!Object.hasOwn(TWP_SLASH_ROUTES,name)||route===void 0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u30B3\u30DE\u30F3\u30C9: ${name}
|
|
1213
1213
|
`}}const parsed=parseArgv([route.domain,route.operation,...args]);if(parsed.command!=="domain"||parsed.domain!==route.domain){return{code:2,out:"",err:`${name}: \u3053\u306E\u5F15\u6570\u306F\u4F7F\u3048\u307E\u305B\u3093\uFF08${args.join(" ")}\uFF09
|
|
1214
1214
|
`}}if(parsed.unknown.length>0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u5F15\u6570: ${parsed.unknown.join(" ")}
|
|
1215
|
-
`}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-
|
|
1215
|
+
`}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-5COXNYKX.js");try{const code=await runDomain({domain:route.domain,...parsed.operation!==void 0?{operation:parsed.operation}:
|
|
1216
1216
|
{},argv:parsed.domainArgv,help:parsed.domainHelp,globals,version:deps.version,io,...deps.fetchImpl!==void 0?{fetchImpl:deps.fetchImpl}:{}});return{code,out,err}}catch(e){return{code:1,out,err:`${err}${e.message}
|
|
1217
1217
|
`}}}var GIT_LOG_OUTPUT=["9f3c1a2 feat(ui): \u4E00\u89A7\u306E\u30D5\u30A3\u30EB\u30BF\u3092 URL \u30AF\u30A8\u30EA\u3068\u540C\u671F\u3059\u308B","4b8e0d7 fix(ui): \u4EEE\u60F3\u30B9\u30AF\u30ED\u30FC\u30EB\u306E\u884C\u9AD8\u3055\u3092\u5B9F\u6E2C\u5024\u306B\u5408\u308F\u305B\u308B","c15a99e refactor(api): \u4E00\u89A7\u53D6\u5F97\u306E\u30DA\u30FC\u30B8\u30F3\u30B0\u51E6\u7406\u3092\u5171\u901A\u5316\u3059\u308B","2d70f4b test: \u4E00\u89A7\u30D5\u30A3\u30EB\u30BF\u306E\u56DE\u5E30\u30C6\u30B9\u30C8\u3092\u8FFD\u52A0\u3059\u308B",
|
|
1218
1218
|
"a6e2b38 fix(api): \u7A7A\u306E\u691C\u7D22\u6761\u4EF6\u3067\u5168\u4EF6\u8FD4\u3089\u306A\u3044\u3088\u3046\u306B\u3059\u308B","7c40d51 chore(deps): \u958B\u767A\u4F9D\u5B58\u3092\u6700\u65B0\u3078\u66F4\u65B0\u3059\u308B","e83b1c6 docs: \u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u624B\u9806\u306B Node 22 \u306E\u524D\u63D0\u3092\u8FFD\u8A18\u3059\u308B","b91f7a4 fix(ui): \u30E2\u30FC\u30C0\u30EB\u306E\u91CD\u306A\u308A\u9806\u3092\u6307\u5B9A\u3059\u308B","5a2c8e0 perf(api): \u4E00\u89A7\u306E N+1 \u3092\u89E3\u6D88\u3059\u308B",
|
|
@@ -6,7 +6,7 @@ join(", ")}] \u3092\u4F7F\u3044\u307E\u3059\uFF09`);return fallback}}if(value.le
|
|
|
6
6
|
warnings.push(`claude_launcher.probe_match \u306F\u6B63\u898F\u8868\u73FE\u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\uFF08${err.message}\uFF09\u3002\u65E2\u5B9A '${DEFAULT_CLAUDE_LAUNCHER.probeMatch}' \u3092\u4F7F\u3044\u307E\u3059`);return DEFAULT_CLAUDE_LAUNCHER.probeMatch}return raw}var NOT_YET_APPLIED=[{key:"probe",get:c=>c.probe},{key:"probe_match",get:c=>c.probeMatch},{key:"exec_args",get:c=>c.execArgs},{key:"active_args",get:c=>c.activeArgs}];function sameAsDefault(key,parsed){
|
|
7
7
|
const entry=NOT_YET_APPLIED.find(e=>e.key===key);if(entry===void 0)return true;const a=entry.get(parsed);const b=entry.get(DEFAULT_CLAUDE_LAUNCHER);return typeof a==="string"||typeof b==="string"?a===b:a.length===b.length&&a.every((v,i)=>v===b[i])}function parseClaudeLauncher(value){const warnings=[];if(value===void 0||value===null){return{launcher:DEFAULT_CLAUDE_LAUNCHER,warnings}}if(typeof value!=="object"||Array.isArray(value)){warnings.push("claude_launcher \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A\u306E\u8D77\u52D5\u65B9\u6CD5\u3092\u4F7F\u3044\u307E\u3059\uFF09");
|
|
8
8
|
return{launcher:DEFAULT_CLAUDE_LAUNCHER,warnings}}const v=value;const launcher={bin:stringField(v["bin"],"bin",DEFAULT_CLAUDE_LAUNCHER.bin,warnings),probe:argvField(v["probe"],"probe",DEFAULT_CLAUDE_LAUNCHER.probe,warnings,true),probeMatch:probeMatchField(v["probe_match"],warnings),execArgs:argvField(v["exec_args"],"exec_args",DEFAULT_CLAUDE_LAUNCHER.execArgs,warnings,false),activeArgs:argvField(v["active_args"],"active_args",DEFAULT_CLAUDE_LAUNCHER.activeArgs,warnings,false)};for(const{key}of NOT_YET_APPLIED){
|
|
9
|
-
if(!sameAsDefault(key,launcher)){warnings.push(`claude_launcher.${key} \u306F\u307E\u3060\u9069\u7528\u3055\u308C\u307E\u305B\u3093\uFF08\u3053\u306E\u7248\u3067\u52B9\u304F\u306E\u306F bin \u3060\u3051\u3067\u3059\uFF09`)}}return{launcher,warnings}}import{randomBytes}from"crypto";import
|
|
9
|
+
if(!sameAsDefault(key,launcher)){warnings.push(`claude_launcher.${key} \u306F\u307E\u3060\u9069\u7528\u3055\u308C\u307E\u305B\u3093\uFF08\u3053\u306E\u7248\u3067\u52B9\u304F\u306E\u306F bin \u3060\u3051\u3067\u3059\uFF09`)}}return{launcher,warnings}}import{randomBytes}from"crypto";import fs2 from"fs";import os from"os";import path2 from"path";import{createHash}from"crypto";import{spawn}from"child_process";function resolveHookCommand(file,env){if(process.platform!=="win32")return file;if(isWindowsDriveAbsolute(file))return file;return findExecutable(file,{env,platform:"win32"})}var DEFAULT_TIMEOUT_SEC=120;var MAX_OUTPUT_BYTES=512*1024;var HOOK_ID_RE=/^[A-Za-z0-9._:-]{1,64}$/;function validateHooks(raw,configKey="prefetch"){const warnings=[];if(raw===void 0||raw===null)return{hooks:[],warnings};if(!Array.isArray(raw)){return{hooks:[],warnings:[`${configKey} \u306F\u914D\u5217\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\u30D5\u30C3\u30AF\u306F1\u3064\u3082\u5B9F\u884C\u3057\u307E\u305B\u3093`]}}
|
|
10
10
|
const hooks=[];const seen=new Set;for(const[i,entry]of raw.entries()){if(entry===null||typeof entry!=="object"||Array.isArray(entry)){warnings.push(`${configKey}[${i}] \u304C\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u3053\u306E\u30D5\u30C3\u30AF\u306F\u5B9F\u884C\u3057\u307E\u305B\u3093`);continue}const e=entry;const id=typeof e["id"]==="string"?e["id"].trim():"";const command=e["command"];if(id===""){warnings.push(`${configKey}[${i}] \u306B id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u3053\u306E\u30D5\u30C3\u30AF\u306F\
|
|
11
11
|
\u5B9F\u884C\u3057\u307E\u305B\u3093`);continue}if(!HOOK_ID_RE.test(id)){warnings.push(`${configKey}[${i}] \u306E id '${id}' \u306F64\u6587\u5B57\u4EE5\u4E0B\u306E\u82F1\u6570\u5B57\u3068 . _ : - \u3060\u3051\u3092\u4F7F\u3048\u307E\u3059\u3002\u3053\u306E\u30D5\u30C3\u30AF\u306F\u5B9F\u884C\u3057\u307E\u305B\u3093`);continue}if(seen.has(id)){warnings.push(`${configKey}[${i}] \u306E id '${id}' \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059\u3002\u3053\u306E\u30D5\u30C3\u30AF\u306F\u5B9F\u884C\u3057\u307E\u305B\u3093`);
|
|
12
12
|
continue}if(!Array.isArray(command)||command.length===0||!command.every(c=>typeof c==="string")){warnings.push(`${configKey}[${i}]\uFF08${id}\uFF09\u306E command \u304C\u6587\u5B57\u5217\u306E\u914D\u5217\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u3053\u306E\u30D5\u30C3\u30AF\u306F\u5B9F\u884C\u3057\u307E\u305B\u3093`);continue}const timeout=typeof e["timeout"]==="number"&&Number.isFinite(e["timeout"])&&e["timeout"]>0?Math.trunc(e["timeout"]):DEFAULT_TIMEOUT_SEC;seen.add(id);hooks.push({id,
|
|
@@ -46,8 +46,15 @@ env,now=()=>Date.now()){this.probe=probe;this.cwd=cwd;this.log=log;this.env=env;
|
|
|
46
46
|
if(outcome.ok){this.lastSuccess=outcome.payload;this.lastSuccessAt=at}const reuse=!outcome.ok&&this.lastSuccess!==null&&at-this.lastSuccessAt<REUSE_LAST_SUCCESS_MS;this.cached=reuse?this.lastSuccess:outcome.payload;if(reuse){this.log(" \u76F4\u524D\u306B\u53D6\u5F97\u3067\u304D\u305F\u67A0\u60C5\u5831\u3092\u9001\u308A\u307E\u3059\uFF08\u4E00\u6642\u7684\u306A\u5931\u6557\u3068\u3057\u3066\u6271\u3044\u307E\u3059\uFF09")}this.lastProbedAt=this.now();this.pending=true}finally{this.running=false}}take(){
|
|
47
47
|
if(!this.pending||this.cached===null)return null;this.pending=false;return this.cached}rearm(){if(this.cached!==null)this.pending=true}};function evaluateOwnership(item,runnerId,runId){if(!item){return{verdict:"unknown",reason:"\u30A2\u30A4\u30C6\u30E0\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"}}if(runnerId===""||runId===""){return{verdict:"unknown",reason:"\u81EA\u5206\u306E runner_id / run_id \u304C\u7A7A\u3067\u3059"}}const status=(item.status??"").trim();if(status===""){return{verdict:"unknown",reason:"\u5FDC\u7B54\u306B status \u304C\u3042\u308A\u307E\u305B\u3093"}}if(status!=="processing"){return{verdict:"\
|
|
48
48
|
lost",reason:`status=${status}\uFF08processing \u3067\u306F\u3042\u308A\u307E\u305B\u3093\uFF09`}}const itemRunner=(item.runner_id??"").trim();const itemRun=(item.run_id??"").trim();if(itemRunner===""||itemRun===""){return{verdict:"unknown",reason:"\u5FDC\u7B54\u306B runner_id / run_id \u304C\u3042\u308A\u307E\u305B\u3093"}}if(itemRunner!==runnerId){return{verdict:"lost",reason:`\u5225\u306E\u30E9\u30F3\u30CA\u30FC\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08runner=${itemRunner}\uFF09`}}
|
|
49
|
-
if(itemRun!==runId){return{verdict:"lost",reason:`\u540C\u3058\u6A5F\u4F53\u306E\u5225\u306E\u8D77\u52D5\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08run_id \u304C\u4E00\u81F4\u3057\u307E\u305B\u3093\uFF09`}}return{verdict:"held",reason:"processing \u304B\u3064 runner_id / run_id \u304C\u4E00\u81F4"}}var OWNERSHIP_CHECK_INTERVAL_SEC=60;
|
|
50
|
-
|
|
49
|
+
if(itemRun!==runId){return{verdict:"lost",reason:`\u540C\u3058\u6A5F\u4F53\u306E\u5225\u306E\u8D77\u52D5\u304C\u4FDD\u6301\u3057\u3066\u3044\u307E\u3059\uFF08run_id \u304C\u4E00\u81F4\u3057\u307E\u305B\u3093\uFF09`}}return{verdict:"held",reason:"processing \u304B\u3064 runner_id / run_id \u304C\u4E00\u81F4"}}var OWNERSHIP_CHECK_INTERVAL_SEC=60;import{createHash as createHash2}from"crypto";import fs from"fs";import path from"path";var DEFAULT_PLAN_GATE_TIMEOUT_SEC=30;var DEFAULT_PLAN_GATE_MAX_SKIP_SEC=3600;var MAX_STATE_BYTES=4096;function parsePlanGate(value,warnings){if(value===void 0||value===null)return null;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.plan_gate \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u6BCE\u56DE\u8A08\u753B\u3057\u307E\u3059\uFF09");return null}const o=value;const entry={timeout:DEFAULT_PLAN_GATE_TIMEOUT_SEC,
|
|
50
|
+
...o,id:"plan-gate"};const{hooks,warnings:w}=validateHooks([entry],"operations.plan_gate");warnings.push(...w.map(m=>`${m}\uFF08\u6BCE\u56DE\u8A08\u753B\u3057\u307E\u3059\uFF09`));const hook=hooks[0];if(!hook)return null;let maxSkipSec=DEFAULT_PLAN_GATE_MAX_SKIP_SEC;const raw=o["max_skip_sec"];if(typeof raw==="number"&&Number.isFinite(raw)&&raw>0){maxSkipSec=Math.trunc(raw)}else if(raw!==void 0&&raw!==null){warnings.push(`operations.plan_gate.max_skip_sec \u306F\u6B63\u306E\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u65E2\u5B9A\u306E ${DEFAULT_PLAN_GATE_MAX_SKIP_SEC}\
|
|
51
|
+
\u79D2\u3092\u4F7F\u3044\u307E\u3059\uFF09`)}return{hook,maxSkipSec}}function planGateStatePath(stateDir,projectKey){return path.join(stateDir,`task-loop-${projectKey}.plan-gate.json`)}function fingerprintOf(stdout){const line=stdout.split(/\r?\n/).map(l=>l.trim()).find(l=>l!=="");if(line===void 0)return null;return createHash2("sha256").update(line).digest("hex")}function readPlanGateState(statePath){try{if(fs.statSync(statePath).size>MAX_STATE_BYTES)return null;const parsed=JSON.parse(fs.readFileSync(
|
|
52
|
+
statePath,"utf8"));const fingerprint=parsed["fingerprint"];const plannedAtMs=parsed["planned_at_ms"];if(typeof fingerprint!=="string"||!/^[0-9a-f]{64}$/.test(fingerprint))return null;if(typeof plannedAtMs!=="number"||!Number.isFinite(plannedAtMs))return null;return{fingerprint,plannedAtMs}}catch{return null}}function recordPlanned(statePath,fingerprint,nowMs){const tmp=`${statePath}.${process.pid}.tmp`;try{fs.mkdirSync(path.dirname(statePath),{recursive:true});fs.writeFileSync(tmp,JSON.stringify(
|
|
53
|
+
{fingerprint,planned_at_ms:nowMs,planned_at:new Date(nowMs).toISOString()}));fs.renameSync(tmp,statePath);return true}catch{fs.rmSync(tmp,{force:true});return false}}async function evaluatePlanGate(gate,opts){const run=opts.run??((h,cwd)=>runHook(h,cwd));const outcome=await run(gate.hook,opts.cwd);if(!outcome.ok){return{skip:false,fingerprint:null,reason:`\u30D5\u30C3\u30AF\u304C\u5931\u6557\u3057\u305F\u305F\u3081\u8A08\u753B\u3057\u307E\u3059\uFF08${outcome.reason??"\u7406\u7531\u4E0D\u660E"}\uFF09`}}
|
|
54
|
+
const fingerprint=fingerprintOf(outcome.stdout);if(fingerprint===null){return{skip:false,fingerprint:null,reason:"\u30D5\u30C3\u30AF\u304C\u6307\u7D0B\u3092\u51FA\u3055\u306A\u304B\u3063\u305F\u305F\u3081\u8A08\u753B\u3057\u307E\u3059"}}const short=fingerprint.slice(0,12);const prev=readPlanGateState(opts.statePath);if(prev===null){return{skip:false,fingerprint,reason:`\u524D\u56DE\u8A08\u753B\u6642\u306E\u8A18\u9332\u304C\u7121\u3044\u305F\u3081\u8A08\u753B\u3057\u307E\u3059\uFF08\u6307\u7D0B ${short}\
|
|
55
|
+
\uFF09`}}if(prev.fingerprint!==fingerprint){return{skip:false,fingerprint,reason:`\u5165\u529B\u304C\u5909\u308F\u3063\u305F\u305F\u3081\u8A08\u753B\u3057\u307E\u3059\uFF08\u6307\u7D0B ${prev.fingerprint.slice(0,12)} \u2192 ${short}\uFF09`}}const elapsedSec=Math.trunc((opts.nowMs-prev.plannedAtMs)/1e3);if(elapsedSec<0||elapsedSec>=gate.maxSkipSec){return{skip:false,fingerprint,reason:`\u5165\u529B\u306F\u5909\u308F\u3063\u3066\u3044\u307E\u305B\u3093\u304C\u3001\u524D\u56DE\u306E\u8A08\u753B\u304B\u3089 ${elapsedSec}\
|
|
56
|
+
\u79D2\u7D4C\u904E\u3057\u305F\u305F\u3081\u8A08\u753B\u3057\u307E\u3059\uFF08max_skip_sec=${gate.maxSkipSec}\uFF09`}}return{skip:true,fingerprint,reason:`\u5165\u529B\u306B\u5909\u5316\u304C\u306A\u3044\u305F\u3081\u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u307E\u3059\uFF08\u6307\u7D0B ${short}\u30FB\u524D\u56DE\u306E\u8A08\u753B\u304B\u3089 ${elapsedSec}\u79D2\uFF09`}}var NO_OPERATIONS={exclusiveSkills:new Set,statusEndpoint:null,highRiskSkills:new Set,preflightHosts:[],releaseRecoverySkill:null,postSuccessEnqueue:new Map,contractSkills:new Set,contractLines:new Map,advancingOutcomes:new Map,zeroTargetGates:{},countHooks:new Map,planSkill:null,planGate:null};var DEFAULT_STATUS_PATH="/api/release/list";var DEFAULT_STATUS_HEADER="X-API-Key";function stringArray(value,label,warnings){if(value===void 0||value===null)return[];if(!Array.isArray(value)){warnings.push(
|
|
57
|
+
`operations.${label} \u306F\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09`);return[]}const out=[];for(const v of value){if(typeof v!=="string"||v.trim()===""){warnings.push(`operations.${label} \u306E\u8981\u7D20\u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u8981\u7D20\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}out.push(v.trim())}return out}var KEYS_LINE_RE=/^[A-Za-z][A-Za-z0-9_]*$/;
|
|
51
58
|
function parsePostSuccessEnqueue(value,warnings){const out=new Map;if(value===void 0||value===null)return out;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.post_success_enqueue \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return out}for(const[k,v]of Object.entries(value)){const label=`operations.post_success_enqueue.${k}`;if(typeof v==="string"){if(v.trim()===""){warnings.
|
|
52
59
|
push(`${label} \u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u9805\u76EE\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}out.set(k,{skill:v.trim(),keysLine:null});continue}if(typeof v!=="object"||v===null||Array.isArray(v)){warnings.push(`${label} \u306F\u6587\u5B57\u5217\u304B { skill, keys_line } \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u9805\u76EE\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);
|
|
53
60
|
continue}const o=v;const skill=typeof o["skill"]==="string"?o["skill"].trim():"";if(skill===""){warnings.push(`${label}.skill \u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u3053\u306E\u9805\u76EE\u306F\u7121\u8996\u3057\u307E\u3059\uFF09`);continue}const rawLine=o["keys_line"];let keysLine=null;if(typeof rawLine==="string"&&KEYS_LINE_RE.test(rawLine.trim())){keysLine=rawLine.trim()}else if(rawLine!==void 0&&rawLine!==null){warnings.push(
|
|
@@ -61,34 +68,35 @@ continue}const outcome=`${line}: ${rawValue.toUpperCase()}`;const prev=advancing
|
|
|
61
68
|
0&&!line.endsWith("_RESULT")){warnings.push(`operations.contract_lines.${skill}.line \u304C _RESULT \u3067\u7D42\u308F\u3089\u306A\u3044\u305F\u3081\u3001advances \u306F\u518D\u6295\u5165\u6291\u6B62\u306B\u4F7F\u3048\u307E\u305B\u3093\uFF08\u7DE0\u3081\u51E6\u7406\u306E\u5951\u7D04\u884C\u3068\u3057\u3066\u3060\u3051\u4F7F\u3044\u307E\u3059\uFF09`);for(const v2 of advances.keys())advancingOutcomes.delete(`${line}: ${v2}`)}contractLines.set(skill,{line,advances})}return{contractLines,advancingOutcomes}}
|
|
62
69
|
function parseCountHooks(value,warnings){const out=new Map;if(value===void 0||value===null)return out;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.count_hooks \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return out}for(const[key,v]of Object.entries(value)){const entry=v!==null&&typeof v==="object"&&!Array.isArray(v)?{id:`count:${key}`,...v}:v;const{hooks,warnings:w}=validateHooks(
|
|
63
70
|
[entry],`operations.count_hooks.${key}`);warnings.push(...w);const hook=hooks[0];if(hook)out.set(key,hook)}return out}function parseEndpoint(value,warnings){if(value===void 0||value===null)return null;if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations.status_endpoint \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059\uFF09");return null}const o=value;const url=typeof o["\
|
|
64
|
-
url"]==="string"?o["url"].trim():"";if(url===""){warnings.push("operations.status_endpoint.url \u304C\u7121\u3044\u305F\u3081\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059");return null}if(!/^https?:\/\//i.test(url)){warnings.push(`operations.status_endpoint.url \u306F http(s) \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${url}\uFF08\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059\uFF09`);return null}const
|
|
65
|
-
trim():DEFAULT_STATUS_PATH;const apiKeyEnvRaw=o["api_key_env"];const apiKeyEnv=typeof apiKeyEnvRaw==="string"&&apiKeyEnvRaw.trim()!==""?apiKeyEnvRaw.trim():null;const headerRaw=o["header"];const header=typeof headerRaw==="string"&&headerRaw.trim()!==""?headerRaw.trim():DEFAULT_STATUS_HEADER;return{url:url.replace(/\/+$/,""),path:
|
|
71
|
+
url"]==="string"?o["url"].trim():"";if(url===""){warnings.push("operations.status_endpoint.url \u304C\u7121\u3044\u305F\u3081\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059");return null}if(!/^https?:\/\//i.test(url)){warnings.push(`operations.status_endpoint.url \u306F http(s) \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${url}\uFF08\u6392\u4ED6\u3092\u7121\u52B9\u306B\u3057\u307E\u3059\uFF09`);return null}const path3=typeof o["path"]==="string"&&o["path"].trim()!==""?o["path"].
|
|
72
|
+
trim():DEFAULT_STATUS_PATH;const apiKeyEnvRaw=o["api_key_env"];const apiKeyEnv=typeof apiKeyEnvRaw==="string"&&apiKeyEnvRaw.trim()!==""?apiKeyEnvRaw.trim():null;const headerRaw=o["header"];const header=typeof headerRaw==="string"&&headerRaw.trim()!==""?headerRaw.trim():DEFAULT_STATUS_HEADER;return{url:url.replace(/\/+$/,""),path:path3.startsWith("/")?path3:`/${path3}`,apiKeyEnv,header}}function parseOperations(value){const warnings=[];if(value===void 0||value===null)return{operations:NO_OPERATIONS,
|
|
66
73
|
warnings};if(typeof value!=="object"||Array.isArray(value)){warnings.push("operations \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u7121\u8996\u3057\u307E\u3059\uFF09");return{operations:NO_OPERATIONS,warnings}}const o=value;const exclusiveSkills=new Set(stringArray(o["exclusive_skills"],"exclusive_skills",warnings));const statusEndpoint=parseEndpoint(o["status_endpoint"],warnings);if(exclusiveSkills.size>0&&statusEndpoint===null){warnings.
|
|
67
74
|
push("operations.exclusive_skills \u306F\u3042\u308A\u307E\u3059\u304C status_endpoint \u304C\u7121\u3044\u305F\u3081\u3001\u5B9A\u671F\u67A0\u306E\u6392\u4ED6\u306F\u884C\u3044\u307E\u305B\u3093")}if(exclusiveSkills.size===0&&statusEndpoint!==null){warnings.push("operations.status_endpoint \u306F\u3042\u308A\u307E\u3059\u304C exclusive_skills \u304C\u7A7A\u306E\u305F\u3081\u3001\u554F\u3044\u5408\u308F\u305B\u306F\u884C\u3044\u307E\u305B\u3093")}const releaseRecoveryRaw=o["release_recovery_skil\
|
|
68
75
|
l"];const releaseRecoverySkill=typeof releaseRecoveryRaw==="string"&&releaseRecoveryRaw.trim()!==""?releaseRecoveryRaw.trim():null;const planSkillRaw=o["plan_skill"];let planSkill=null;if(typeof planSkillRaw==="string"&&planSkillRaw.trim()!==""){planSkill=planSkillRaw.trim()}else if(planSkillRaw!==void 0&&planSkillRaw!==null){warnings.push("operations.plan_skill \u306F\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u884C\u3044\u307E\u305B\u3093\uFF09")}
|
|
69
|
-
const
|
|
70
|
-
operations:{exclusiveSkills,statusEndpoint,highRiskSkills:new Set(stringArray(o["high_risk_skills"],"high_risk_skills",warnings)),preflightHosts:stringArray(o["preflight_hosts"],
|
|
71
|
-
const plan=ops.planSkill?`\u8A08\u753B ${ops.planSkill}
|
|
72
|
-
|
|
73
|
-
\u3044\
|
|
76
|
+
const planGate=parsePlanGate(o["plan_gate"],warnings);if(planGate!==null&&planSkill===null){warnings.push("operations.plan_gate \u306F\u3042\u308A\u307E\u3059\u304C plan_skill \u304C\u7121\u3044\u305F\u3081\u4F7F\u308F\u308C\u307E\u305B\u3093\uFF08\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u884C\u3044\u307E\u305B\u3093\uFF09")}const{contractLines,advancingOutcomes}=parseContractLines(o["contract_lines"],warnings);const contractSkills=new Set(stringArray(o["contract_skills"],"contract_skills",warnings));
|
|
77
|
+
for(const skill of contractSkills){if(!contractLines.has(skill)){warnings.push(`operations.contract_skills \u306E ${skill} \u306B contract_lines \u306E\u63A5\u982D\u8F9E\u304C\u3042\u308A\u307E\u305B\u3093\uFF08\u7DE0\u3081\u51E6\u7406\u306F\u6C4E\u7528\u306E *_RESULT \u884C\u3092\u62FE\u3044\u307E\u3059\uFF09`)}}return{operations:{exclusiveSkills,statusEndpoint,highRiskSkills:new Set(stringArray(o["high_risk_skills"],"high_risk_skills",warnings)),preflightHosts:stringArray(o["preflight_hosts"],
|
|
78
|
+
"preflight_hosts",warnings),releaseRecoverySkill,postSuccessEnqueue:parsePostSuccessEnqueue(o["post_success_enqueue"],warnings),contractSkills,contractLines,advancingOutcomes,zeroTargetGates:parseZeroTargetGates(o["zero_target_gates"],warnings),countHooks:parseCountHooks(o["count_hooks"],warnings),planSkill,planGate},warnings}}function describeOperations(ops){const plan=ops.planSkill?`\u8A08\u753B ${ops.planSkill}${ops.planGate?`\uFF08plan_gate: \u5165\u529B\u306B\u5909\u5316\u304C\u306A\u3051\u308C\u3070\u7701\u304F\u30FB\u6700\u9577${ops.
|
|
79
|
+
planGate.maxSkipSec}\u79D2\uFF09`:""}`:"\u8A08\u753B\u30B9\u30AD\u30EB\u672A\u8A2D\u5B9A\uFF08\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u884C\u3044\u307E\u305B\u3093\uFF09";const advance=ops.advancingOutcomes.size>0?`\u518D\u6295\u5165\u6291\u6B62 ${ops.advancingOutcomes.size}\u7A2E`:"contract_lines \u672A\u8A2D\u5B9A\uFF08\u518D\u6295\u5165\u6291\u6B62\u3092\u884C\u3044\u307E\u305B\u3093\uFF09";if(ops===NO_OPERATIONS||ops.exclusiveSkills.size===0&&ops.highRiskSkills.size===0&&ops.postSuccessEnqueue.
|
|
80
|
+
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 / ${plan} / ${advance}`}const parts=[plan,advance];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`)}
|
|
81
|
+
if(ops.highRiskSkills.size>0)parts.push(`\u9AD8\u30EA\u30B9\u30AF ${ops.highRiskSkills.size}\u4EF6`);if(ops.releaseRecoverySkill)parts.push(`\u56DE\u53CE ${ops.releaseRecoverySkill}`);for(const[from,f]of ops.postSuccessEnqueue){parts.push(f.keysLine?`\u5F8C\u7D9A ${from}\u2192${f.skill}\uFF08${f.keysLine} \u884C\u306E\u30AD\u30FC\u5358\u4F4D\uFF09`:`\u5F8C\u7D9A ${from}\u2192${f.skill}\uFF08keys_line \u672A\u8A2D\u5B9A\u306E\u305F\u3081\u30AD\u30FC\u5358\u4F4D\u306E\u6295\u5165\u306F\u3057\u307E\u305B\u3093\uFF09`)}
|
|
74
82
|
return`\u904B\u7528\u8A2D\u5B9A: ${parts.join(" / ")}`}var DEFAULT_INTERVAL_SEC=300;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){
|
|
75
83
|
const t=value?.trim();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(
|
|
76
84
|
fallback):local);warn(`${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\
|
|
77
|
-
\u6587\u3092\u4F7F\u3044\u307E\u3059\uFF09`);return null}var STATE_DIR_NAME=".twp-task-loop";var LEGACY_STATE_DIR_NAME=".twp-ops";function loopStateDir(env=process.env,exists=
|
|
78
|
-
env){if(!env.TWP_OPS_STATE_DIR?.trim())env.TWP_OPS_STATE_DIR=config.stateDir;if(!env.RELEASE_OUTCOME_LOG?.trim())env.RELEASE_OUTCOME_LOG=config.releaseOutcomeLogPath}function releaseOutcomeLogPath(env=process.env,stateDir=loopStateDir(env)){const explicit=env.RELEASE_OUTCOME_LOG?.trim();if(explicit)return explicit;return
|
|
79
|
-
env){const file=localConfigPath(projectId,env);try{const parsed=JSON.parse(
|
|
80
|
-
${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:
|
|
81
|
-
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{
|
|
85
|
+
\u6587\u3092\u4F7F\u3044\u307E\u3059\uFF09`);return null}var STATE_DIR_NAME=".twp-task-loop";var LEGACY_STATE_DIR_NAME=".twp-ops";function loopStateDir(env=process.env,exists=fs2.existsSync){const explicit=env.TWP_OPS_STATE_DIR?.trim();if(explicit)return explicit;const current=path2.join(os.homedir(),STATE_DIR_NAME);if(exists(current))return current;const legacy=path2.join(os.homedir(),LEGACY_STATE_DIR_NAME);if(exists(legacy))return legacy;return current}function exportStateDirEnv(config,env=process.
|
|
86
|
+
env){if(!env.TWP_OPS_STATE_DIR?.trim())env.TWP_OPS_STATE_DIR=config.stateDir;if(!env.RELEASE_OUTCOME_LOG?.trim())env.RELEASE_OUTCOME_LOG=config.releaseOutcomeLogPath}function releaseOutcomeLogPath(env=process.env,stateDir=loopStateDir(env)){const explicit=env.RELEASE_OUTCOME_LOG?.trim();if(explicit)return explicit;return path2.join(stateDir,"release-outcomes.tsv")}function localConfigPath(projectId,env=process.env){return path2.join(twpHomeDir(env),"loops",`${projectFileKey(projectId)}.json`)}function loadLocalConfig(projectId,env=process.
|
|
87
|
+
env){const file=localConfigPath(projectId,env);try{const parsed=JSON.parse(fs2.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}
|
|
88
|
+
${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:path2.join(stateDir,"runner-id");let candidate=env.RUNNER_ID?.trim()??"";if(!candidate){try{candidate=fs2.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`;
|
|
89
|
+
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{fs2.mkdirSync(path2.dirname(file),{recursive:true,mode:448});fs2.writeFileSync(file,`${candidate}
|
|
82
90
|
`,{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){
|
|
83
91
|
const env=input.env??process.env;const warnings=[];const num2=(raw,fallback,min=1,label="")=>{const r=sanitizeInt(raw,fallback,min);if(r.warning)warnings.push(`${label}${r.warning}`);return r.value};if(input.daemon&&input.maxCycles!==void 0){warnings.push("--daemon \u3068 --max-cycles \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\uFF08--daemon \u3092\u512A\u5148\u3057\u3001--max-cycles \u306F\u7121\u8996\u3057\u307E\u3059\uFF09")}const local=loadLocalConfig(input.projectId,env);
|
|
84
92
|
if(local.schedule_command&&local.schedule_command.length>0){warnings.push("\u30ED\u30FC\u30AB\u30EB\u8A2D\u5B9A\u306E schedule_command \u306F\u4F7F\u308F\u308C\u307E\u305B\u3093\uFF08\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u306E\u5224\u5B9A\u306F twp-cli \u5185\u3067\u884C\u3044\u307E\u3059\uFF09\u3002\u8A2D\u5B9A\u304B\u3089\u524A\u9664\u3057\u3066\u304F\u3060\u3055\u3044")}if(nonEmpty(env.TWP_TASK_LOOP_SCHEDULE_CMD)){warnings.push("TWP_TASK_LOOP_SCHEDULE_CMD \u306F\u4F7F\u308F\u308C\u307E\u305B\u3093\uFF08\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u306E\u5224\u5B9A\u306F twp-c\
|
|
85
93
|
li \u5185\u3067\u884C\u3044\u307E\u3059\uFF09")}const stateDir=loopStateDir(env);const{runnerId,warning:runnerWarning}=resolveRunnerId(stateDir,env);if(runnerWarning)warnings.push(runnerWarning);const aiTimeoutSec=num2(env.AI_TIMEOUT??local.ai_timeout,4500,60,"AI_TIMEOUT=");const aiSoftDeadlineRatio=Math.min(num2(env.AI_SOFT_DEADLINE_RATIO??local.ai_soft_deadline_ratio,80,1,"AI_SOFT_DEADLINE_RATIO="),100);const planLockTtlSec=num2(env.PLAN_LOCK_TTL,1800,60,"PLAN_LOCK_TTL=");const workspace=nonEmpty(
|
|
86
94
|
local.workspace)??process.cwd();const ai=loadAiConfig(local.ai,local.ai_config_file,workspace);warnings.push(...ai.warnings);const operations=parseOperations(local.operations);warnings.push(...operations.warnings);const claudeLauncher=parseClaudeLauncher(local.claude_launcher);warnings.push(...claudeLauncher.warnings);const capacityProbe=parseCapacityProbe(local.capacity_probe);warnings.push(...capacityProbe.warnings);const prefetch=validateHooks(local.prefetch);warnings.push(...prefetch.warnings);
|
|
87
|
-
const preflight=validateHooks(local.preflight,"preflight");warnings.push(...preflight.warnings);return{projectId:input.projectId,projectRef:input.projectRef,apiUrl:input.apiUrl,runnerId,runId:buildRunId(runnerId,input.now??new Date),stateDir,logDir:nonEmpty(env.LOG_DIR)??local.log_dir??
|
|
88
|
-
daemon,maxCycles:input.daemon?Number.MAX_SAFE_INTEGER:input.maxCycles??1,intervalSec:input.intervalSec??DEFAULT_INTERVAL_SEC,intervalSource:input.intervalSec!==void 0?"cli":"default",forceRunner:input.forceRunner,engine:nonEmpty(input.engine)??nonEmpty(local.engine)??"",aiTimeoutSec,aiSoftDeadlineRatio,planTimeoutSec:num2(env.PLAN_TIMEOUT??local.plan_timeout,900,60,"PLAN_TIMEOUT="),heartbeatIntervalSec:num2(env.AGENT_LOOP_HEARTBEAT_INTERVAL,120,1,"AGENT_LOOP_HEARTBEAT_INTERVAL="),ownershipCheckIntervalSec:num2(
|
|
95
|
+
const preflight=validateHooks(local.preflight,"preflight");warnings.push(...preflight.warnings);return{projectId:input.projectId,projectRef:input.projectRef,apiUrl:input.apiUrl,runnerId,runId:buildRunId(runnerId,input.now??new Date),stateDir,logDir:nonEmpty(env.LOG_DIR)??local.log_dir??path2.join(os.homedir(),".twp-agent-loop","logs"),logRetentionDays:num2(env.LOG_RETENTION_DAYS??local.log_retention_days,7,0,"LOG_RETENTION_DAYS="),workspace,gitIdentity:local.git_identity,safeMode:input.safeMode,
|
|
96
|
+
daemon:input.daemon,maxCycles:input.daemon?Number.MAX_SAFE_INTEGER:input.maxCycles??1,intervalSec:input.intervalSec??DEFAULT_INTERVAL_SEC,intervalSource:input.intervalSec!==void 0?"cli":"default",forceRunner:input.forceRunner,engine:nonEmpty(input.engine)??nonEmpty(local.engine)??"",aiTimeoutSec,aiSoftDeadlineRatio,planTimeoutSec:num2(env.PLAN_TIMEOUT??local.plan_timeout,900,60,"PLAN_TIMEOUT="),heartbeatIntervalSec:num2(env.AGENT_LOOP_HEARTBEAT_INTERVAL,120,1,"AGENT_LOOP_HEARTBEAT_INTERVAL="),ownershipCheckIntervalSec:num2(
|
|
89
97
|
env.AGENT_LOOP_OWNERSHIP_CHECK_INTERVAL,OWNERSHIP_CHECK_INTERVAL_SEC,0,"AGENT_LOOP_OWNERSHIP_CHECK_INTERVAL="),contendedMax:num2(env.AGENT_LOOP_CONTENDED_MAX,10,1,"AGENT_LOOP_CONTENDED_MAX="),queueUndeterminedMax:num2(env.QUEUE_UNDETERMINED_MAX,5,1,"QUEUE_UNDETERMINED_MAX="),staleReclaimHours:num2(env.STALE_RECLAIM_HOURS,3,0,"STALE_RECLAIM_HOURS="),planLockTtlSec,planLockWaitMaxSec:num2(env.PLAN_LOCK_WAIT_MAX,planLockTtlSec,0,"PLAN_LOCK_WAIT_MAX="),planLockPollIntervalSec:num2(env.PLAN_LOCK_POLL_INTERVAL,
|
|
90
98
|
60,1,"PLAN_LOCK_POLL_INTERVAL="),planLockRenewIntervalSec:num2(env.PLAN_LOCK_RENEW_INTERVAL,Math.trunc(planLockTtlSec/3),1,"PLAN_LOCK_RENEW_INTERVAL="),planLockStealAttempts:num2(env.PLAN_LOCK_STEAL_ATTEMPTS,3,0,"PLAN_LOCK_STEAL_ATTEMPTS="),planLockPermanentMax:num2(env.PLAN_LOCK_PERMANENT_MAX,3,1,"PLAN_LOCK_PERMANENT_MAX="),scheduleMidcycleMax:num2(env.SCHEDULE_MIDCYCLE_MAX,6,1,"SCHEDULE_MIDCYCLE_MAX="),blockerRecoveryMaxPerDay:num2(env.BLOCKER_RECOVERY_MAX_PER_DAY,2,1,"BLOCKER_RECOVERY_MAX_PER\
|
|
91
99
|
_DAY="),releaseRerunAutoEnqueue:env.RELEASE_RERUN_AUTOENQUEUE_ENABLED!=="false",releaseRerunMaxPerCause:num2(env.RELEASE_RERUN_MAX_PER_CAUSE,2,1,"RELEASE_RERUN_MAX_PER_CAUSE="),writebackMaxAgeDays:num2(env.AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS,7,1,"AGENT_LOOP_WRITEBACK_MAX_AGE_DAYS="),scheduleTimezone:nonEmpty(env.AGENT_LOOP_SCHEDULE_TZ)??"Asia/Tokyo",counterTimezone:nonEmpty(env.AGENT_LOOP_COUNTER_TZ)??"Asia/Tokyo",compileCommand:local.compile_command!==void 0&&local.compile_command.length>0?local.
|
|
92
100
|
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(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_enab\
|
|
93
101
|
led",true,"\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u5B9F\u884C\u3057\u307E\u3059",m=>warnings.push(m)),ai:ai.config,aiSource:{inline:local.ai,file:local.ai_config_file},operations:operations.operations,claudeLauncher:claudeLauncher.launcher,capacityProbe:capacityProbe.probe,prefetch:prefetch.hooks,preflight:preflight.hooks,configHash:ai.config.hash(),version:input.version,warnings,releaseOutcomeLogPath:releaseOutcomeLogPath(env,stateDir)}}function localDate(timezone,now=new Date){const fmt=new Intl.
|
|
94
|
-
DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});return fmt.format(now)}export{runHook,runPrefetch,runPreflight,formatHookWiring,formatHookIds,CapacityReporter,parseClaudeLauncher,evaluateOwnership,describeOperations,DEFAULT_INTERVAL_SEC,STATE_DIR_NAME,LEGACY_STATE_DIR_NAME,loopStateDir,exportStateDirEnv,localConfigPath,loadLocalConfig,buildLoopConfig,localDate};
|
|
102
|
+
DateTimeFormat("en-CA",{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit"});return fmt.format(now)}export{runHook,runPrefetch,runPreflight,formatHookWiring,formatHookIds,CapacityReporter,parseClaudeLauncher,evaluateOwnership,planGateStatePath,recordPlanned,evaluatePlanGate,describeOperations,DEFAULT_INTERVAL_SEC,STATE_DIR_NAME,LEGACY_STATE_DIR_NAME,loopStateDir,exportStateDirEnv,localConfigPath,loadLocalConfig,buildLoopConfig,localDate};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{loadDomain}from"./chunk-
|
|
3
|
+
import{loadDomain}from"./chunk-YNRONUTZ.js";import{evaluateQuery}from"./chunk-GFLGXGWE.js";import{renderDocument,renderOutput}from"./chunk-YXVN6OCH.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-UFGJSWKU.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{parseOperationArgs}from"./chunk-RX5HWI4L.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-MI6HVYR2.js";import{Resolver,requireDefaultProject}from"./chunk-MYWDL3WX.js";
|
|
4
4
|
import{ResolveError}from"./chunk-HVZUXLQ4.js";import{ApiError,MultipartBody,TwpApiClient,appendQuery}from"./chunk-JA5A6UJ2.js";import{isRecord}from"./chunk-3ZRMMBP5.js";import{ApiRejectedError,ApiResponseError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,EXIT_WAIT_TIMEOUT,NetworkError,UsageError,WaitTimeoutError}from"./chunk-VFPY2A23.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-PECIBNFD.js";import{AuthSession,NotLoggedInError,SessionExpiredError,
|
|
5
5
|
loadCredentials}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,loadUserConfig,resolveConfiguredOutput,resolveProfile}from"./chunk-4VZKNEVN.js";import{HELP_TOKEN}from"./chunk-QZBE4KC2.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-74BPZOKU.js";import{stringWidth}from"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs from"fs";import path from"path";var NO_REDACT_FLAG={name:"--no-redact",summary:"\u5FDC\u7B54\u306E\u4F0F\u5B57\u5316\u3092\u89E3\u9664\u3057\u3066\u751F\u306E\u5024\u3092\u51FA\u3059\uFF08\u9375\u306E\u53D7\u3051\u53D6\u308A\u7B49\uFF09",takesValue:false};var NO_REDACT_NOTICE="\u6CE8\u8A18: --no-redact \u306E\u305F\u3081\u51FA\u529B\u3092\u4F0F\u5B57\u5316\u3057\u307E\u305B\u3093\uFF08\u7AEF\u672B\u3068\u30ED\u30B0\u306B\u5E73\u6587\u3067\u6B8B\u308A\u307E\u3059\uFF09\u3002";function withCommonFlags(flags){return flags.some(flag=>flag.
|
|
6
6
|
name===NO_REDACT_FLAG.name)?flags:[...flags,NO_REDACT_FLAG]}function alignedList(entries,indent=" "){const width=entries.reduce((max,[left])=>Math.max(max,stringWidth(left)),0);return entries.map(([left,right])=>`${indent}${left}${" ".repeat(Math.max(0,width-stringWidth(left)))} ${right}`).join("\n")}function subresourcesOf(resource){return resource.subresources??[]}function renderResourceHelp(resource,path2){const subresources=subresourcesOf(resource);const operationSection=resource.operations.length===0?"":`
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
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!=="\
|
|
4
|
+
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;
|
|
5
|
+
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\
|
|
6
|
+
\u884C\u306F\u7D99\u7D9A\u3057\u307E\u3059`)]}if(resets!==null)this.result.resetsAt=resets;this.result.rateLimited=true;return[this.line(`\u26A0\uFE0F \u30EC\u30FC\u30C8\u30EA\u30DF\u30C3\u30C8\u901A\u77E5: status=${status}${at}`)]}onAssistant(event){const out=[];for(const block of contentBlocks(event)){if(block.type==="tool_use"){const name=typeof block.name==="string"?block.name:"tool";if(typeof block.id==="string")this.toolNames.set(block.id,name);this.toolCount+=1;out.push(this.line(`>> ${name}${toolDetail(
|
|
7
|
+
name,block.input)}`))}else if(block.type==="text"&&typeof block.text==="string"&&block.text.trim()!==""){for(const l of block.text.trim().split("\n"))out.push(this.line(` \u{1F4AC} ${l}`))}}return out}onUser(event){const out=[];for(const block of contentBlocks(event)){if(block.type!=="tool_result")continue;const id=typeof block.id==="string"?block.id:"";const useId=typeof block.tool_use_id==="string"?block.tool_use_id:id;const name=this.toolNames.get(useId)??"tool";this.toolNames.delete(useId);
|
|
8
|
+
const isError=block.is_error===true;const detail=isError?firstErrorLine(block):"";out.push(this.line(`${isError?"!!":"<<"} ${name}${detail}`))}return out}onResult(event){const r=this.result;r.subtype=typeof event["subtype"]==="string"?event["subtype"]:null;r.isError=typeof event["is_error"]==="boolean"?event["is_error"]:null;r.numTurns=typeof event["num_turns"]==="number"?event["num_turns"]:null;r.costUsd=typeof event["total_cost_usd"]==="number"?event["total_cost_usd"]:null;r.durationMs=typeof event["\
|
|
9
|
+
duration_ms"]==="number"?event["duration_ms"]:null;const usage=event["usage"];if(usage!==null&&typeof usage==="object"&&!Array.isArray(usage)){const u=usage;const num=key=>typeof u[key]==="number"?u[key]:0;const hasIn=["input_tokens","cache_creation_input_tokens","cache_read_input_tokens"].some(k=>typeof u[k]==="number");r.tokensIn=hasIn?num("input_tokens")+num("cache_creation_input_tokens")+num("cache_read_input_tokens"):null;r.tokensOut=typeof u["output_tokens"]==="number"?u["output_tokens"]:null}
|
|
10
|
+
const out=[this.line(`\u5B8C\u4E86 (turns: ${r.numTurns??0}, tools: ${this.toolCount}, ${Math.round((r.durationMs??0)/1e3)}s, $${(r.costUsd??0).toFixed(3)})`)];const text=typeof event["result"]==="string"?event["result"]:"";r.finalText=text;if(text!==""){out.push(FINAL_REPORT_BEGIN,text,FINAL_REPORT_END)}return out}line(msg){const d=this.now();const ts=`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;return` [${ts}] ${msg}`}};function firstErrorLine(block){const content=block.
|
|
11
|
+
content;const text=typeof content==="string"?content:Array.isArray(content)?content.map(c=>c!==null&&typeof c==="object"&&typeof c.text==="string"?c.text:"").join(" "):"";const first=text.trim().split("\n")[0]??"";return first===""?"":` | ${first.slice(0,120)}`}function contentBlocks(event){const message=event["message"];if(message===null||typeof message!=="object")return[];const content=message["content"];if(!Array.isArray(content))return[];return content.filter(b=>b!==null&&typeof b==="object")}
|
|
12
|
+
function toolDetail(name,input){if(input===void 0||input===null)return"";const str=k=>typeof input[k]==="string"?input[k]:"";if(name==="Bash"){const cmd=str("command");return cmd===""?"":` $ ${cmd.slice(0,80)}${cmd.length>80?"...":""}`}if(name==="Read"||name==="Write"||name==="Edit"){const p=str("file_path");return p===""?"":` ${p}`}if(name==="Grep"||name==="Glob"){const p=str("pattern");return p===""?"":` '${p}'`}if(name==="Skill"){const s=str("skill");return s===""?"":` /${s}`}if(name.includes(
|
|
13
|
+
"mcp__")){const args=[];for(const k of["task_id","project_id","status_id","issue_id"]){const v=str(k);if(v!=="")args.push(`${k}=${v.slice(0,16)}`)}return args.length===0?"":` (${args.slice(0,2).join(", ")})`}return""}function pad(n){return String(n).padStart(2,"0")}function isSaneEpochSec(v){return v!==null&&Number.isFinite(v)&&Math.abs(v)<864e10}export{FINAL_REPORT_BEGIN,FINAL_REPORT_END,ClaudeStreamRenderer};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{DEFAULT_INTERVAL_SEC}from"./chunk-
|
|
3
|
+
import{DEFAULT_INTERVAL_SEC}from"./chunk-2B7A3OY7.js";import{CHAIN_KEYS,reloadAiConfig}from"./chunk-AEJHDFXB.js";import{describeError}from"./chunk-AT432SCP.js";import{isPrivateProjectId}from"./chunk-GY7KI5E5.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs from"fs";import path from"path";var PROMPT_KEYS=["charter","charter_prefix","charter_suffix","plan_preamble","step_budget","non_interactive_note","safe_mode_note"];function parseServerSettings(res){const json=res.json;if(json===null||typeof json!=="object"||Array.isArray(json))return null;const top=json;const data=top["data"];const b=data!==null&&typeof data==="object"&&!Array.isArray(data)&&"revision"in data?data:top;const revision=b["revision"];if(typeof revision!=="number"||!Number.isInteger(revision)||revision<0)return null;
|
|
4
4
|
const rawAi=b["ai"];const ai=rawAi!==null&&typeof rawAi==="object"&&!Array.isArray(rawAi)?Object.fromEntries(Object.entries(rawAi).filter(([,v])=>v!==null&&v!==void 0)):{};const prompts={};const rawPrompts=b["prompts"];if(rawPrompts!==null&&typeof rawPrompts==="object"&&!Array.isArray(rawPrompts)){for(const key of PROMPT_KEYS){const v=rawPrompts[key];if(typeof v==="string")prompts[key]=v}}const rawLoop=b["loop"];const rawInterval=rawLoop!==null&&typeof rawLoop==="object"&&!Array.isArray(rawLoop)?
|
|
5
5
|
rawLoop["interval_sec"]:void 0;const intervalSec=typeof rawInterval==="number"&&Number.isInteger(rawInterval)&&rawInterval>0?rawInterval:null;const rawOutcomes=b["outcomes"];const outcomeSkills=Array.isArray(rawOutcomes)?[...new Set(rawOutcomes.map(r=>r!==null&&typeof r==="object"?r["skill"]:void 0).filter(v=>typeof v==="string"&&v.trim()!==""))]:[];return{revision,ai,prompts,intervalSec,outcomeSkills}}function formatConfigHash(aiHash,revision,ai,charter){return`${aiHash};r=${revision};ai=${ai};\
|
|
6
6
|
charter=${charter}`}function renderStepBudget(template,vars){return template.replaceAll("{timeout_min}",String(vars.timeoutMin)).replaceAll("{soft_min}",String(vars.softMin)).replaceAll("{wrap_up_min}",String(vars.wrapUpMin))}var LoopSettingsApplier=class{constructor(deps){this.deps=deps}deps;last=null;lastWarning="";lastAiWarning="";lastSummary="";serverAiApplied=false;lastSafeWarning="";lastInterval="";async apply(){const{config,log}=this.deps;const outcome=await this.fetch();const warning=outcome.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{FINAL_REPORT_BEGIN,FINAL_REPORT_END}from"./chunk-DXUFECE7.js";import{normalizeRequiredPlatforms}from"./chunk-AT432SCP.js";import{extractLeadingTaskKey}from"./chunk-II5RVJQN.js";var LEDGER_TASK_KEY_MAX=50;var CONTROL_CHAR_RE=/[\u0000-\u001f\u007f]/;var FLAG_TOKEN_RE=/(?:^|\s)-/;function loosen(source){let t=source.replace(/^[ \t]*\/\/[^\n]*$/gm,"");t=t.replace(/\/\*[\s\S]*?\*\//g,"");t=t.replace(/,(\s*[}\]])/g,"$1");return t===source?null:t}function tryParsePlan(source){for(const candidate of[source,loosen(source)]){if(candidate===null)continue;try{const obj=JSON.parse(candidate);if(obj!==null&&typeof obj==="object"&&Array.isArray(obj.steps)){return obj}}catch{}}return null}
|
|
4
|
+
function fencedBlocks(text,tag){const re=new RegExp("```"+tag+"\\s*\\n([\\s\\S]*?)\\n```","g");const out=[];for(const m of text.matchAll(re)){if(m[1]!==void 0)out.push(m[1])}return out}function extractGeminiEnvelope(text){const anchor=/\{[^{}]*"session_id"[^{}]*"response"\s*:\s*"/g;for(const m of text.matchAll(anchor)){const start=m.index;if(start===void 0)continue;let depth=0;let inStr=false;let escape=false;for(let i=start;i<text.length;i++){const c=text[i];if(escape){escape=false;continue}if(c===
|
|
5
|
+
"\\"){escape=true;continue}if(c==='"'){inStr=!inStr;continue}if(inStr)continue;if(c==="{")depth++;else if(c==="}"){depth--;if(depth===0){try{const obj=JSON.parse(text.slice(start,i+1));if(obj!==null&&typeof obj==="object"&&typeof obj.response==="string"){return obj.response}}catch{}break}}}}return null}function matchingBrace(text,start){let depth=0;let inStr=false;let escape=false;for(let i=start;i<text.length;i++){const c=text[i];if(escape){escape=false;continue}if(inStr){if(c==="\\")escape=true;else if(c===
|
|
6
|
+
'"')inStr=false;continue}if(c==='"')inStr=true;else if(c==="{")depth++;else if(c==="}"){depth--;if(depth===0)return i}}return-1}var MAX_STEPS_ANCHORS=20;var MAX_OPEN_CANDIDATES=8;function lastStepsObject(text){const anchors=[...text.matchAll(/"steps"\s*:/g)].map(m=>m.index).filter(i=>i!==void 0);for(const at of anchors.reverse().slice(0,MAX_STEPS_ANCHORS)){let tried=0;for(let open=text.lastIndexOf("{",at);open>=0&&tried<MAX_OPEN_CANDIDATES;open=text.lastIndexOf("{",open-1)){tried++;const close=matchingBrace(
|
|
7
|
+
text,open);if(close>at){const plan=tryParsePlan(text.slice(open,close+1));if(plan)return plan}if(open===0)break}}return null}function finalReports(text){const re=new RegExp(`${FINAL_REPORT_BEGIN}\\n?([\\s\\S]*?)${FINAL_REPORT_END}`,"g");const out=[];for(const m of text.matchAll(re)){if(m[1]!==void 0)out.push(m[1])}return out.reverse()}function extractFrom(text){for(const tag of["json:execution-plan","json"]){for(const block of fencedBlocks(text,tag).reverse()){const plan=tryParsePlan(block);if(plan)
|
|
8
|
+
return plan}}const resp=extractGeminiEnvelope(text);if(resp!==null){for(const block of[...fencedBlocks(resp,"json:execution-plan"),...fencedBlocks(resp,"json")].reverse()){const plan2=tryParsePlan(block);if(plan2)return plan2}const plan=tryParsePlan(resp);if(plan)return plan}const whole=tryParsePlan(text.trim());if(whole)return whole;return lastStepsObject(text)}function extractPlanJson(rawText){const text=rawText.replace(/^\s*\[\d{2}:\d{2}:\d{2}\][ \t]*(?:💬 ?)?/gmu,"");for(const report of finalReports(
|
|
9
|
+
text)){const plan=extractFrom(report);if(plan)return plan}return extractFrom(text)}function ledgerTaskKey(args){const key=extractLeadingTaskKey(args);if(key.length>LEDGER_TASK_KEY_MAX)return"";if(CONTROL_CHAR_RE.test(key))return"";if(FLAG_TOKEN_RE.test(key))return"";return key}function placeholderTaskKey(args){for(const token of args.split(/\s+/)){if(token==="")continue;if(token.startsWith("-"))continue;const m=/^[A-Z]{2,}[A-Z0-9]*-([A-Za-z0-9_<>{}]*)$/.exec(token);if(!m)return null;if(/^\d+$/.test(
|
|
10
|
+
m[1]??""))return null;return token}return null}function stepToItem(step,assign){const skill=typeof step.skill==="string"?step.skill.trim():"";if(!skill)return null;const args=(step.args??"").trim();const priority=step.priority??"P2";const prompt=`/twp-${skill}${args?` ${args}`:""}`;let label=(step.label??"").trim();if(!label||label.startsWith("/twp-")||label.startsWith("[P"))label=prompt;const taskKey=ledgerTaskKey(args);const category=assign?.categoryForSkill(skill)??step.ai_category??"complex";
|
|
11
|
+
const display=taskKey&&!label.includes(taskKey)?`[${priority}] ${taskKey} ${label} #ai:${category}`:`[${priority}] ${label} #ai:${category}`;const item={label:display.slice(0,200),prompt,task_key:taskKey};const platforms=normalizeRequiredPlatforms(step.required_platforms);if(platforms.length>0)item.required_platforms=platforms;if(assign!==void 0){const ai=assign.selectPrimary(category,skill,priority,display);if(ai!=="")item.ai_type=ai}return item}function parsePlanExcludeKeys(prefetchSection){const m=/OPS_PLAN_EXCLUDE_KEYS\s+([^\s]*)\s+-->/.
|
|
12
|
+
exec(prefetchSection);const keys=new Set;if(!m||!m[1])return keys;for(const raw of m[1].split(",")){const key=raw.trim();if(key!=="")keys.add(key)}return keys}function excludedKeyInArgs(args,excluded){if(excluded.size===0)return null;for(const key of[...excluded].sort()){const re=new RegExp(`(?<![A-Za-z0-9-])${key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![0-9])`);if(re.test(args))return key}return null}function parseOpsCount(prefetchSection,field){const marker=/OPS_COUNTS\s+([^>]*?)-->/.exec(prefetchSection);
|
|
13
|
+
if(!marker||!marker[1])return null;const escaped=field.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const hit=new RegExp(`(?:^|\\s)${escaped}=(-?\\d+)(?:\\s|$)`).exec(marker[1]);if(!hit||hit[1]===void 0)return null;const n=Number.parseInt(hit[1],10);if(!Number.isFinite(n)||n<0)return null;return n}function releaseDeployDropReason(verifyBacklog,devVerifyPlanned){if(verifyBacklog===null){return"\u52D5\u4F5C\u78BA\u8A8D\u306E\u4EF6\u6570\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\uFF08\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u30EA\u30EA\u30FC\u30B9\u306F\u898B\u9001\u308B\uFF09"}
|
|
14
|
+
if(verifyBacklog>devVerifyPlanned){return`\u52D5\u4F5C\u78BA\u8A8D${verifyBacklog}\u4EF6 > \u8A08\u753B\u5185dev-verify${devVerifyPlanned}\u4EF6\uFF08Phase 1\u306E0\u4EF6\u898B\u8FBC\u307F\u304C\u7ACB\u305F\u306A\u3044\uFF09`}return null}function duplicateTaskKeyDropReason(enqueuedKeys,taskKey){if(!taskKey)return null;if(!enqueuedKeys.has(taskKey))return null;return`${taskKey} \u306F\u672C\u8A08\u753B\u3067\u65E2\u306B\u6295\u5165\u6E08\u307F\uFF08\u540C\u4E00\u30AD\u30FC\u306F1\u8A08\u753B1\u4EF6\uFF09`}
|
|
15
|
+
var NO_ZERO_TARGET_GATES={};function zeroTargetDropReasons(prefetchSection,gates=NO_ZERO_TARGET_GATES){const reasons=new Map;for(const[skill,gate]of Object.entries(gates)){const n=parseOpsCount(prefetchSection,gate.field);if(n===null)reasons.set(skill,`${gate.label}\u4EF6\u6570\u304C\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u898B\u9001\u308A`);else if(n===0)reasons.set(skill,`${gate.label}0\u4EF6\u306E\u305F\u3081\u5BFE\u8C61\u306A\u3057`)}return reasons}export{extractPlanJson,placeholderTaskKey,stepToItem,parsePlanExcludeKeys,excludedKeyInArgs,parseOpsCount,releaseDeployDropReason,duplicateTaskKeyDropReason,zeroTargetDropReasons};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
var LOADERS={agent:async()=>(await import("./agent-TLKSUAYA.js")).agentDomain,"agent-loop":async()=>(await import("./agent-loop-
|
|
3
|
+
var LOADERS={agent:async()=>(await import("./agent-TLKSUAYA.js")).agentDomain,"agent-loop":async()=>(await import("./agent-loop-SWXPY3OD.js")).agentLoopDomain,"ai-review-reason":async()=>(await import("./sales-ai-review-IVRISSWX.js")).aiReviewReasonDomain,analysis:async()=>(await import("./analysis-XO3WRAJR.js")).analysisDomain,announcement:async()=>(await import("./announcement-LNG32J6X.js")).announcementDomain,attendance:async()=>(await import("./attendance-correct-3C2BHJQG.js")).attendanceDomainWithRecords,
|
|
4
4
|
backlog:async()=>(await import("./backlog-D5LZIEN4.js")).backlogDomain,budget:async()=>(await import("./budget-RENLLCYQ.js")).budgetDomain,"business-place":async()=>(await import("./sales-master-BGVF2AZL.js")).businessPlaceDomain,company:async()=>(await import("./company-F3IGQMOJ.js")).companyDomain,contract:async()=>(await import("./contract-OWR27GIO.js")).contractDomain,customer:async()=>(await import("./company-F3IGQMOJ.js")).customerDomain,department:async()=>(await import("./department-3QDHMZ5P.js")).
|
|
5
5
|
departmentDomain,deposit:async()=>(await import("./deposit-IPYESXIQ.js")).depositDomain,estimate:async()=>(await import("./estimate-4P67OZWB.js")).estimateDomain,evaluation:async()=>(await import("./evaluation-ZA23GR7P.js")).evaluationDomain,expense:async()=>(await import("./expense-GEOAM7B3.js")).expenseDomain,"goal-sheet":async()=>(await import("./evaluation-ZA23GR7P.js")).goalSheetDomain,inquiry:async()=>(await import("./inquiry-3SCMJOEM.js")).inquiryDomain,invoice:async()=>(await import("./invoice-ONTG53HY.js")).
|
|
6
|
-
invoiceDomain,"job-title":async()=>(await import("./job-title-OQQH5W6C.js")).jobTitleDomain,leave:async()=>(await import("./leave-7HMMZPCR.js")).leaveDomain,media:async()=>(await import("./media-
|
|
6
|
+
invoiceDomain,"job-title":async()=>(await import("./job-title-OQQH5W6C.js")).jobTitleDomain,leave:async()=>(await import("./leave-7HMMZPCR.js")).leaveDomain,media:async()=>(await import("./media-GAL5WENN.js")).mediaDomain,meeting:async()=>(await import("./knowledge-IX7AZIBJ.js")).meetingDomain,note:async()=>(await import("./knowledge-IX7AZIBJ.js")).noteDomain,notification:async()=>(await import("./notification-ZT23M4R6.js")).notificationDomain,onedrive:async()=>(await import("./onedrive-ZY3GTU26.js")).
|
|
7
7
|
onedriveDomain,outlook:async()=>(await import("./outlook-AAS5DXYQ.js")).outlookDomain,payee:async()=>(await import("./sales-master-BGVF2AZL.js")).payeeDomain,position:async()=>(await import("./position-HWBHYAD2.js")).positionDomain,project:async()=>(await import("./project-3ROID2HA.js")).projectDomain,prospect:async()=>(await import("./prospect-7B5UWFLH.js")).prospectDomain,purchase:async()=>(await import("./purchase-QVINV4TM.js")).purchaseDomain,qualification:async()=>(await import("./skill-S7EPMW5Z.js")).
|
|
8
8
|
qualificationDomain,receivable:async()=>(await import("./receivable-66MYAIVR.js")).receivableDomain,report:async()=>(await import("./report-XFTM4GCX.js")).reportDomain,"rounding-setting":async()=>(await import("./sales-numbering-4423JWN6.js")).roundingSettingDomain,"seal-impression":async()=>(await import("./sales-master-BGVF2AZL.js")).sealImpressionDomain,search:async()=>(await import("./search-TMROBRYD.js")).searchDomain,shift:async()=>(await import("./attendance-lists-VMOIE3XO.js")).shiftDomain,
|
|
9
9
|
skill:async()=>(await import("./skill-S7EPMW5Z.js")).skillDomain,storage:async()=>(await import("./storage-AQDCEBDJ.js")).storageDomain,"supplier-payment":async()=>(await import("./supplier-payment-O7GZSKGD.js")).supplierPaymentDomain,support:async()=>(await import("./support-U3VY5JI5.js")).supportDomain,task:async()=>(await import("./task-EQBPQ7H4.js")).taskDomain,teams:async()=>(await import("./teams-GPJ6HMIX.js")).teamsDomain,user:async()=>(await import("./user-XYUB54QT.js")).
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
3
3
|
const require = __twpCreateRequire(import.meta.url);
|
|
4
|
-
import{GLOBAL_OPTIONS_HELP}from"./chunk-PECIBNFD.js";import{parseArgv}from"./chunk-5BDE3A3N.js";import"./chunk-2LOT54OO.js";import"./chunk-QZBE4KC2.js";import"./chunk-QQRJLH6B.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.
|
|
4
|
+
import{GLOBAL_OPTIONS_HELP}from"./chunk-PECIBNFD.js";import{parseArgv}from"./chunk-5BDE3A3N.js";import"./chunk-2LOT54OO.js";import"./chunk-QZBE4KC2.js";import"./chunk-QQRJLH6B.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.62.0":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
|
|
5
5
|
|
|
6
6
|
\u4F7F\u3044\u65B9:
|
|
7
7
|
twp \u5BFE\u8A71 TUI \u3092\u8D77\u52D5
|
|
@@ -1122,14 +1122,14 @@ TUI \u5185:
|
|
|
1122
1122
|
\u4F1A\u8A71\u30FB\u30ED\u30FC\u30AB\u30EB\u30C4\u30FC\u30EB\uFF08\u30D5\u30A1\u30A4\u30EB\u30FB\u30B3\u30DE\u30F3\u30C9\u30FBgit\uFF09\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u3067\u5B9F\u969B\u306B\u52D5\u304D\u307E\u3059\u3002
|
|
1123
1123
|
`;function ignoreEpipe(stream){stream.on("error",err=>{if(err.code==="EPIPE")process.exit(0);throw err})}async function main(){const nodeMajor=Number(process.versions.node.split(".")[0]);if(nodeMajor<22){process.stderr.write(`twp-cli \u306B\u306F Node.js 22 \u4EE5\u4E0A\u304C\u5FC5\u8981\u3067\u3059\uFF08\u73FE\u5728: ${process.versions.node}\uFF09
|
|
1124
1124
|
`);process.exit(1)}ignoreEpipe(process.stdout);ignoreEpipe(process.stderr);if(process.env["TWP_AUTO_UPDATE_WORKER"]==="1"){const{runAutoUpdateWorker}=await import("./auto-update-worker-VG77U4UA.js");await runAutoUpdateWorker().catch(()=>void 0);return}const[first,...rest]=process.argv.slice(2);if(first==="__complete"||first==="completion"){const completion=await import("./completion-WKXK7VGT.js");if(first==="completion"){process.exitCode=completion.runCompletion(rest,process.stdout,process.stderr);return}
|
|
1125
|
-
const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-
|
|
1125
|
+
const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-JABWR2GZ.js"),import("./config-3CNEQ7KN.js")]);process.exitCode=await completion.runComplete(rest,process.stdout,{loadDomain,profileNames:()=>Object.keys(loadUserConfig().profiles??{})});return}if(first==="configure"){const autoUpdate2=await import("./auto-update-YMI3F44R.js");autoUpdate2.registerRunning();autoUpdate2.onStartup(VERSION);const{runConfigure}=await import("./configure-3H3CGGBI.js");process.exitCode=
|
|
1126
1126
|
await runConfigure(rest);return}const args=parseArgv(process.argv.slice(2));if(args.command==="version"){process.stdout.write(`${VERSION}
|
|
1127
1127
|
`);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(" ")}
|
|
1128
1128
|
|
|
1129
|
-
${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-YMI3F44R.js");autoUpdate.registerRunning();if(args.command==="task-loop"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-
|
|
1130
|
-
domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-
|
|
1131
|
-
void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes},version:VERSION});return}if(args.command==="update"){const{runUpdate}=await import("./update-NCAVUXSX.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-
|
|
1132
|
-
const options={profile:args.profile,method:args.loginMethod,tenant:args.tenant,noBrowser:args.loginNoBrowser,cliVersion:VERSION,force:args.logoutForce,...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{}};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-
|
|
1129
|
+
${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-YMI3F44R.js");autoUpdate.registerRunning();if(args.command==="task-loop"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-5COXNYKX.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:{},argv:args.domainArgv,help:args.
|
|
1130
|
+
domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-G2TNSWKE.js");process.exitCode=await runApiCommand({argv:args.domainArgv,help:args.domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==
|
|
1131
|
+
void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes},version:VERSION});return}if(args.command==="update"){const{runUpdate}=await import("./update-NCAVUXSX.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-WIQVCMQE.js");
|
|
1132
|
+
const options={profile:args.profile,method:args.loginMethod,tenant:args.tenant,noBrowser:args.loginNoBrowser,cliVersion:VERSION,force:args.logoutForce,...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{}};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-RCCF5ZRU.js");process.exitCode=await runTaskLoop(
|
|
1133
1133
|
{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.engine,version:VERSION,verbose:args.verbose,scheduleNow:args.scheduleNow,scheduleCounts:args.scheduleCounts,scheduleGate:args.scheduleGate,charterOp:args.charterOp,charterInput:args.charterFile,charterOutput:args.charterOut,charterRevision:args.charterRevision,
|
|
1134
1134
|
skillOp:args.skillOp,skillName:args.skillName,skillAll:args.skillAll,skillDir:args.skillDir,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-4NIS4J4S.js");process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.permissionMode}:{},allowedTools:args.
|
|
1135
|
-
allowedTools,disallowedTools:args.disallowedTools,...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-
|
|
1135
|
+
allowedTools,disallowedTools:args.disallowedTools,...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-AOB26ORS.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{ScheduleApi,collectDue,gateStatus,nowInZone,parseCounts,promptSection}from"./chunk-S5DEP2HA.js";import{InstanceLock,buildLockOwner,defaultIsLoopProcess,writeLockOwner}from"./chunk-3WHC4FSG.js";import{LoopSettingsApplier,renderStepBudget}from"./chunk-
|
|
4
|
-
import{ServerSkillCatalog,formatSkillOrigins}from"./chunk-MPEHKAAL.js";import"./chunk-YJZT3UD3.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import{duplicateTaskKeyDropReason,excludedKeyInArgs,extractPlanJson,parseOpsCount,parsePlanExcludeKeys,placeholderTaskKey,releaseDeployDropReason,stepToItem,zeroTargetDropReasons}from"./chunk-
|
|
5
|
-
localDate,loopStateDir,runHook,runPrefetch,runPreflight}from"./chunk-
|
|
6
|
-
import{ULID_RE,loopProjectIdPolicy,resolveProjectRef}from"./chunk-HVZUXLQ4.js";import{isTaskKey}from"./chunk-II5RVJQN.js";import"./chunk-VFPY2A23.js";import{joinFor}from"./chunk-PMOUHEJQ.js";import{AuthSession}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{compareVersionCores,parseVersionCore}from"./chunk-DXXFUNYN.js";import"./chunk-5WGOHFAS.js";
|
|
7
|
-
twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs10 from"fs";import path8 from"path";import fs from"fs";import path from"path";var LoopLogger=class{constructor(runnerId,logFile,out=process.stdout,now=()=>new Date){this.runnerId=runnerId;this.out=out;this.now=now;if(logFile){fs.mkdirSync(path.dirname(logFile),{recursive:true});this.stream=fs.createWriteStream(logFile,{flags:"a"})}}runnerId;out;now;stream=null;log(message){const d=this.now();const ts=`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;const line=`[${ts}] [${this.runnerId}] ${stripTerminalControls(
|
|
3
|
+
import{ScheduleApi,collectDue,gateStatus,nowInZone,parseCounts,promptSection}from"./chunk-S5DEP2HA.js";import{InstanceLock,buildLockOwner,defaultIsLoopProcess,writeLockOwner}from"./chunk-3WHC4FSG.js";import{LoopSettingsApplier,renderStepBudget}from"./chunk-NXWXTUU6.js";import{EngineNotConfiguredError,NoopEngine,UnknownEngineError,aiUnavailableLabel,assertKnownEngine,failureHint,isAiUnavailable,needsHumanToRestoreAi}from"./chunk-ZOOEH7ZE.js";import{claudeConfigDir,resolveDetectDeps}from"./chunk-T4QZO6RQ.js";
|
|
4
|
+
import{ServerSkillCatalog,formatSkillOrigins}from"./chunk-MPEHKAAL.js";import"./chunk-YJZT3UD3.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import{duplicateTaskKeyDropReason,excludedKeyInArgs,extractPlanJson,parseOpsCount,parsePlanExcludeKeys,placeholderTaskKey,releaseDeployDropReason,stepToItem,zeroTargetDropReasons}from"./chunk-QEWCTKPV.js";import{CapacityReporter,buildLoopConfig,describeOperations,evaluateOwnership,evaluatePlanGate,exportStateDirEnv,
|
|
5
|
+
formatHookIds,formatHookWiring,localDate,loopStateDir,planGateStatePath,recordPlanned,runHook,runPrefetch,runPreflight}from"./chunk-2B7A3OY7.js";import"./chunk-DXUFECE7.js";import{exclusiveInflightEntries,formatExclusiveEntry,normalizeSkillName,skillOfItem,spawnSyncResolved}from"./chunk-AEJHDFXB.js";import{killProcessTree}from"./chunk-N2UVRM3Z.js";import{AgentLoopApi,describeError,filterByStatus,isPermanent,pick,pickString}from"./chunk-AT432SCP.js";import{PRIVATE_PROJECT_REF,
|
|
6
|
+
isPrivateProjectId,isPrivateProjectRef,privateProjectId,projectFileKey}from"./chunk-GY7KI5E5.js";import{ULID_RE,loopProjectIdPolicy,resolveProjectRef}from"./chunk-HVZUXLQ4.js";import{isTaskKey}from"./chunk-II5RVJQN.js";import"./chunk-VFPY2A23.js";import{joinFor}from"./chunk-PMOUHEJQ.js";import{AuthSession}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{compareVersionCores,parseVersionCore}from"./chunk-DXXFUNYN.js";import"./chunk-5WGOHFAS.js";
|
|
7
|
+
import{effectiveApiUrl,resolveProfile}from"./chunk-4VZKNEVN.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs10 from"fs";import path8 from"path";import fs from"fs";import path from"path";var LoopLogger=class{constructor(runnerId,logFile,out=process.stdout,now=()=>new Date){this.runnerId=runnerId;this.out=out;this.now=now;if(logFile){fs.mkdirSync(path.dirname(logFile),{recursive:true});this.stream=fs.createWriteStream(logFile,{flags:"a"})}}runnerId;out;now;stream=null;log(message){const d=this.now();const ts=`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;const line=`[${ts}] [${this.runnerId}] ${stripTerminalControls(
|
|
8
8
|
message)}
|
|
9
9
|
`;this.out.write(line);this.stream?.write(line)}separator(){this.log("=".repeat(60))}close(){this.stream?.end();this.stream=null}};function pad(n){return String(n).padStart(2,"0")}function rotateLogs(dir,retentionDays,now=Date.now()){if(retentionDays<=0)return;const cutoff=now-retentionDays*864e5;let entries;try{entries=fs.readdirSync(dir)}catch{return}for(const name of entries){if(!/^(agent-loop|task-loop|step|plan|schedule-enqueued)-.*\.(log|txt)$/.test(name))continue;const file=path.join(dir,
|
|
10
10
|
name);try{if(fs.statSync(file).mtimeMs<cutoff)fs.rmSync(file,{force:true})}catch{}}}import fs7 from"fs";import path5 from"path";var MAX_OUTCOME_DETAIL_LENGTH=1e3;function parseOutcomeDetail(logText){const matches=[...logText.matchAll(/\b[A-Z][A-Z0-9_]*_RESULT:[^\n]*/g)];const line=matches.at(-1)?.[0];if(line===void 0)return null;const sep=line.indexOf("|");if(sep<0)return null;const detail=line.slice(sep+1).split("|").map(s=>s.trim()).filter(s=>s!=="").join(" | ");return detail===""?null:detail.slice(0,MAX_OUTCOME_DETAIL_LENGTH)}var str=v=>typeof v==="string"&&v!==""?v:null;function toRun(v){if(v===null||typeof v!=="obje\
|
|
@@ -181,7 +181,7 @@ api.update(itemId,rest,runId||this.config.runId);if(res.ok){fs6.rmSync(file,{for
|
|
|
181
181
|
var ABORT_DRAIN_TIMEOUT_MS=15e3;function lastContractLine(logText,line){const prefix=line!==null&&/^[A-Z][A-Z0-9_]*$/.test(line)?line:"[A-Z][A-Z0-9_]*_RESULT";return[...logText.matchAll(new RegExp(`^(?:${prefix}):[^\\n]*`,"gm"))].at(-1)?.[0]??""}var TaskLoop=class{constructor(deps){this.deps=deps;this.writeback=new Writeback(deps.api,deps.config,deps.log);this.schedule=new ScheduleBridge({config:deps.config,log:deps.log,api:new ScheduleApi(deps.api),fetchCount:async(key,statusId)=>{const{total,error}=await deps.
|
|
182
182
|
projectApi.countByStatus(deps.config.projectId,statusId);if(error){deps.log.log(` \u26A0\uFE0F require_zero\u300C${key}\u300D\u306E\u4EF6\u6570\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08${error}\uFF09\u3002\u3053\u306E\u67A0\u306F\u767A\u706B\u3057\u307E\u305B\u3093\uFF08fail-closed\uFF09`)}const refined=await refineCount(key,total,deps.config.operations.countHooks,deps.config.workspace);if(refined.note)deps.log.log(` ${refined.note}`);return refined.total}});this.
|
|
183
183
|
engine=deps.engine;this.releaseLog=new ReleaseOutcomeLog(deps.config.releaseOutcomeLogPath);this.postDeps={api:deps.api,config:deps.config,log:deps.log,releaseLog:this.releaseLog};this.planLock=new PlanLock({api:deps.api,config:deps.config,log:deps.log,runner:deps.runner,hasPendingItems:async()=>await this.hasPendingItems()&&!this.nothingClaimableBacklog,reregister:async()=>{deps.runner.registered=false;await deps.runner.registerOrThrow()},...deps.sleepFn?{sleepFn:deps.sleepFn}:{}});this.trustGate=
|
|
184
|
-
deps.trustGate??new TrustGate({enabled:()=>deps.config.ai.usesAi("claude"),check:()=>checkWorkspaceTrust(deps.config.workspace,{launcherBin:deps.config.claudeLauncher.bin})});this.timestamp=new Date().toISOString().replace(/[-:]/g,"").replace(/\..*$/,"");this.settings=deps.settings??new LoopSettingsApplier({api:deps.api,config:deps.config,log:m=>deps.log.log(m)});this.skills=deps.skills??new ServerSkillCatalog({api:deps.api,config:deps.config,log:m=>deps.log.log(m)})}deps;writeback;schedule;planLock;engine;releaseLog;postDeps;timestamp;deferredIds=new Set;midcycleEnqueued=0;aborting=false;draining=false;nothingClaimableBacklog=false;drainExitCode=0;drainWaiters=new Set;itemInFlight=null;ownershipLostItemId=null;abortDrained=null;cyclePreflightSection="";trustGate;settings;skills;sleep(ms){
|
|
184
|
+
deps.trustGate??new TrustGate({enabled:()=>deps.config.ai.usesAi("claude"),check:()=>checkWorkspaceTrust(deps.config.workspace,{launcherBin:deps.config.claudeLauncher.bin})});this.timestamp=new Date().toISOString().replace(/[-:]/g,"").replace(/\..*$/,"");this.settings=deps.settings??new LoopSettingsApplier({api:deps.api,config:deps.config,log:m=>deps.log.log(m)});this.skills=deps.skills??new ServerSkillCatalog({api:deps.api,config:deps.config,log:m=>deps.log.log(m)})}deps;planGateFingerprint=null;lastPlanWasEmpty=false;writeback;schedule;planLock;engine;releaseLog;postDeps;timestamp;deferredIds=new Set;midcycleEnqueued=0;aborting=false;draining=false;nothingClaimableBacklog=false;drainExitCode=0;drainWaiters=new Set;itemInFlight=null;ownershipLostItemId=null;abortDrained=null;cyclePreflightSection="";trustGate;settings;skills;sleep(ms){
|
|
185
185
|
return(this.deps.sleepFn??sleep)(ms)}sleepUnlessDraining(ms){if(this.draining)return Promise.resolve();return new Promise(resolve=>{let timer=null;let settled=false;const wake=()=>{if(settled)return;settled=true;if(timer!==null)clearTimeout(timer);this.drainWaiters.delete(wake);resolve()};this.drainWaiters.add(wake);const injected=this.deps.sleepFn;if(injected)void injected(ms).then(wake);else timer=setTimeout(wake,ms)})}requestDrain(reason,exitCode=0){if(this.draining)return;this.draining=true;
|
|
186
186
|
this.drainExitCode=exitCode;const running=this.itemInFlight;const why=reason.trim()===""?"\u7406\u7531\u4E0D\u660E":reason;this.deps.log.log(running===null?`\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u53D6\u308A\u307E\u3057\u305F\uFF08${why}\uFF09\u3002\u5B9F\u884C\u4E2D\u306E\u30A2\u30A4\u30C6\u30E0\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u65B0\u3057\u3044\u30A2\u30A4\u30C6\u30E0\u3092\u53D6\u3089\u305A\u306B\u7D42\u4E86\u3057\u307E\u3059\u3002`:`\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u53D6\u308A\u307E\u3057\u305F\uFF08${why}\
|
|
187
187
|
\uFF09\u3002\u5B9F\u884C\u4E2D\u306E\u30A2\u30A4\u30C6\u30E0\uFF08${running}\uFF09\u3092\u5B8C\u8D70\u3055\u305B\u3066\u304B\u3089\u7D42\u4E86\u3057\u307E\u3059\u3002`);const waiters=[...this.drainWaiters];this.drainWaiters.clear();for(const w of waiters)w()}cooldownNote(outcome){if(outcome!=="rate-limited")return"";const remaining=this.deps.config.ai.minCooldownRemainingSec();return remaining===null?"":`\uFF08\u6700\u77ED\u306E\u89E3\u9664\u307E\u3067\u7D04${remaining}\u79D2\uFF09`}startOwnershipWatch(itemId){
|
|
@@ -193,29 +193,30 @@ resolve()},ABORT_DRAIN_TIMEOUT_MS);timer.unref?.()})]);if(timer!==null)clearTime
|
|
|
193
193
|
if(!config.planEnabled){log.log("\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u306F\u7121\u52B9\u3067\u3059\uFF08plan_enabled=false\uFF09\u3002\u30AD\u30E5\u30FC\u304C\u7A7A\u3067\u3082\u8A08\u753BAI\u3092\u8D77\u52D5\u305B\u305A\u3001\u7A4D\u307E\u308C\u305F\u4ED5\u4E8B\u306E\u5B9F\u884C\u3060\u3051\u3092\u884C\u3044\u307E\u3059\u3002")}let cycle=0;let noProgressStreak=0;let unavailableStreak=0;let undeterminedStreak=0;let exitCode=0;while(cycle<config.maxCycles){if(this.aborting){log.log("\u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u3092\u53D7\u3051\u3066\u3044\u308B\
|
|
194
194
|
\u305F\u3081\u3001\u65B0\u3057\u3044\u30B5\u30A4\u30AF\u30EB\u3092\u958B\u59CB\u3057\u307E\u305B\u3093\u3002");break}if(this.draining){log.log(`\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u3066\u3044\u308B\u305F\u3081\u3001\u65B0\u3057\u3044\u30B5\u30A4\u30AF\u30EB\u3092\u958B\u59CB\u3057\u307E\u305B\u3093\uFF08\u7D42\u4E86\u30B3\u30FC\u30C9 ${this.drainExitCode}\uFF09\u3002`);exitCode=this.drainExitCode;break}cycle+=1;const cycleStart=Date.now();log.separator();log.log(`========== Cy\
|
|
195
195
|
cle ${cycle}${config.daemon?"":`/${config.maxCycles}`} \u958B\u59CB ==========`);log.separator();await runner.beat("idle");log.log(formatHookWiring(config.prefetch,config.preflight));if(config.preflight.length>0){log.log(`\u74B0\u5883\u306E\u524D\u63D0\u6761\u4EF6\u3092\u78BA\u8A8D\u4E2D\uFF08\u30D5\u30C3\u30AF ${config.preflight.length}\u4EF6\uFF09...`)}this.cyclePreflightSection=await runPreflight(config.preflight,config.workspace,m=>log.log(m));await this.settings.apply();await this.skills.refresh();
|
|
196
|
-
try{await this.engine.healthCheck?.({cwd:config.workspace,logFilePrefix:path5.join(config.logDir,`health-${this.timestamp}-${cycle}`)})}catch(err){log.log(` \u26A0\uFE0F AI\u30D8\u30EB\u30B9\u30C1\u30A7\u30C3\u30AF\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${err.message}\uFF09\u3002\u9396\u306F\u305D\u306E\u307E\u307E\u4F7F\u3044\u307E\u3059`)}for(const line of normalizeGitIdentity(config.workspace,config.gitIdentity).logs)log.log(line);let planSkippedNoLock=false;
|
|
197
|
-
writeback.retryPending();for(const itemId of resent)await this.schedule.recordByItem(itemId,"completed");const reclaimRes=await this.deps.api.reclaim();if(!reclaimRes.ok){log.log(` \u26A0\uFE0F \u6B7B\u3093\u3060\u30E9\u30F3\u30CA\u30FC\u306E\u30A2\u30A4\u30C6\u30E0\u56DE\u53CEAPI\u304C\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${describeError(reclaimRes)}\uFF09\u3002\u53D6\u308A\u6B8B\u3057\u304C\u6B8B\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059`)}await this.reclaimStaleProcessing();
|
|
196
|
+
try{await this.engine.healthCheck?.({cwd:config.workspace,logFilePrefix:path5.join(config.logDir,`health-${this.timestamp}-${cycle}`)})}catch(err){log.log(` \u26A0\uFE0F AI\u30D8\u30EB\u30B9\u30C1\u30A7\u30C3\u30AF\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${err.message}\uFF09\u3002\u9396\u306F\u305D\u306E\u307E\u307E\u4F7F\u3044\u307E\u3059`)}for(const line of normalizeGitIdentity(config.workspace,config.gitIdentity).logs)log.log(line);let planSkippedNoLock=false;let planSkippedNoChange=false;
|
|
197
|
+
const resent=await this.writeback.retryPending();for(const itemId of resent)await this.schedule.recordByItem(itemId,"completed");const reclaimRes=await this.deps.api.reclaim();if(!reclaimRes.ok){log.log(` \u26A0\uFE0F \u6B7B\u3093\u3060\u30E9\u30F3\u30CA\u30FC\u306E\u30A2\u30A4\u30C6\u30E0\u56DE\u53CEAPI\u304C\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${describeError(reclaimRes)}\uFF09\u3002\u53D6\u308A\u6B8B\u3057\u304C\u6B8B\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059`)}await this.reclaimStaleProcessing();
|
|
198
198
|
const trust=this.trustGate.evaluate();for(const line of trust.logs)log.log(line);if(trust.note!==null){this.cyclePreflightSection=this.cyclePreflightSection===""?trust.note:`${this.cyclePreflightSection}
|
|
199
199
|
|
|
200
200
|
${trust.note}`}if(trust.wait){await runner.beat("waiting");if(cycle<config.maxCycles)await this.sleepUnlessDraining(config.intervalSec*1e3);continue}const pendingListed=await this.hasPendingItems();const hadPending=pendingListed&&!this.nothingClaimableBacklog;if(pendingListed&&!hadPending){log.log("pending \u306F\u3053\u306E\u6A5F\u4F53\u304C\u53D6\u308C\u306A\u3044\u3082\u306E\uFF08\u524D\u63D0\u672A\u5145\u8DB3\u30FB\u5225\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0\u5C02\u7528\uFF09\u3060\u3051\u3067\u3059\uFF08\u524D\u56DE\u306E claim \u306E\u5224\u5B9A\uFF09\u3002\u30AD\u30E5\u30FC\u304C\u7A7A\u306E\u3068\u304D\u3068\u540C\u3058\u304F\u8A08\u753B\u3057\u307E\u3059\u3002")}
|
|
201
201
|
this.midcycleEnqueued=0;this.deferredIds=new Set;await this.enqueueDueScheduled(false);const planSkippedDisabled=!hadPending&&(!config.planEnabled||config.operations.planSkill===null);if(hadPending){log.log("\u30AD\u30E5\u30FC\u306Bpending\u30A2\u30A4\u30C6\u30E0\u304C\u3042\u308A\u307E\u3059\u3002\u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3066\u5B9F\u884C\u306B\u9032\u307F\u307E\u3059\u3002")}else if(planSkippedDisabled){log.log(`\u30AD\u30E5\u30FC\u306F\u7A7A\u3067\u3059\u304C\u3001\u3053\u306E\u6A5F\u4F53\u306F\u8A08\u753B\u3092\u7ACB\u3066\u306A\u3044\u8A2D\u5B9A\u3067\u3059\uFF08${config.
|
|
202
|
-
planEnabled?"operations.plan_skill \u672A\u8A2D\u5B9A":"plan_enabled=false"}\uFF09\u3002AI \u3092\u8D77\u52D5\u305B\u305A\u30AD\u30E5\u30FC\u306E\u5B9F\u884C\u3078\u9032\u307F\u307E\u3059\u3002`)}else{log.log("\u30AD\u30E5\u30FC\u304C\u7A7A\u3067\u3059\u3002\u8A08\u753B\u3092\u7ACB\u6848\u3057\u3066\u30A8\u30F3\u30AD\u30E5\u30FC\u3057\u307E\u3059\u3002")}if(planSkippedDisabled){}else if(!hadPending&&this.draining){log.log("\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u3066\u3044\u308B\u305F\u3081\u3001\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u5B9F\u884C\u3057\u307E\u305B\u3093\u3002")}else if(!hadPending
|
|
203
|
-
const acquired=await this.planLock.acquire();if(acquired!=="acquired"){planSkippedNoLock=true;log.log("\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3066\u30AD\u30E5\u30FC\u306E\u5B9F\u884C\u3078\u9032\u307F\u307E\u3059\u3002")}else{
|
|
204
|
-
if(planResult==="aborted"){log.log("\u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u306B\u3088\u308A\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u6253\u3061\u5207\u308A\u307E\u3057\u305F\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002");
|
|
205
|
-
)`);log.log(` ${AI_RECOVERY_HINT}`);if(unavailableStreak>=3){exitCode=1;log.log("\u26D4 AI \u30921\u3064\u3082\u8D77\u52D5\u3067\u304D\u306A\u3044\u72B6\u614B\u304C\u7D9A\u3044\u3066\u3044\u307E\u3059\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\uFF08\u7D42\u4E86\u30B3\u30FC\u30C91\uFF09");
|
|
206
|
-
break}}else{unavailableStreak=0;log.log(`\u26A0\uFE0F ${aiUnavailableLabel(planResult)}\u3067\u8A08\u753B\u3067\u304D\u307E\u305B\u3093${this.cooldownNote(planResult)}\uFF08\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\u30FB\u6B21\u30B5\u30A4\u30AF\u30EB\u3067\u518D\u5224\u5B9A\uFF09`)}
|
|
207
|
-
if(config.daemon){log.log(`\u30C7\u30FC\u30E2\u30F3\u30E2\u30FC\u30C9\u306E\u305F\u3081 ${config.intervalSec}\u79D2\u5F8C\u306B\u30EA\u30C8\u30E9\u30A4...`);await runner.beat("waiting");await this.sleepUnlessDraining(config.intervalSec*1e3);continue}break}}}const outcome=await this.
|
|
208
|
-
\u30A4\u30C6\u30E0\u306F\u5B8C\u8D70\u6E08\u307F\u30FB\u7D42\u4E86\u30B3\u30FC\u30C9 ${this.drainExitCode}\uFF09\u3002`:"/stop \u30B3\u30DE\u30F3\u30C9\u306B\u3088\u308A\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002");
|
|
209
|
-
unexecuted>0&&outcome.needsHuman){undeterminedStreak=0;
|
|
210
|
-
\u4EF6\u3092\
|
|
211
|
-
emptyQueue&&planSkippedDisabled){undeterminedStreak=0;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u8A08\u753B\u3092\u7ACB\u3066\u306A\u3044\u8A2D\u5B9A\u3067\u30AD\u30E5\u30FC\u3082\u7A7A\u3067\u3057\u305F\uFF08\u5F85\u6A5F\u30FB\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\uFF09`)}else if(outcome.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
)
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
202
|
+
planEnabled?"operations.plan_skill \u672A\u8A2D\u5B9A":"plan_enabled=false"}\uFF09\u3002AI \u3092\u8D77\u52D5\u305B\u305A\u30AD\u30E5\u30FC\u306E\u5B9F\u884C\u3078\u9032\u307F\u307E\u3059\u3002`)}else{log.log("\u30AD\u30E5\u30FC\u304C\u7A7A\u3067\u3059\u3002\u8A08\u753B\u3092\u7ACB\u6848\u3057\u3066\u30A8\u30F3\u30AD\u30E5\u30FC\u3057\u307E\u3059\u3002")}if(planSkippedDisabled){}else if(!hadPending&&this.draining){log.log("\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u3066\u3044\u308B\u305F\u3081\u3001\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u5B9F\u884C\u3057\u307E\u305B\u3093\u3002")}else if(!hadPending&&
|
|
203
|
+
await this.planGateSaysSkip()){planSkippedNoChange=true;log.log("\u8A08\u753B\u306E AI \u3092\u8D77\u52D5\u305B\u305A\u30AD\u30E5\u30FC\u306E\u5B9F\u884C\u3078\u9032\u307F\u307E\u3059\uFF08\u5165\u529B\u306B\u5909\u5316\u306A\u3057\uFF09\u3002")}else if(!hadPending){const acquired=await this.planLock.acquire();if(acquired!=="acquired"){planSkippedNoLock=true;log.log("\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3066\u30AD\u30E5\u30FC\u306E\u5B9F\u884C\u3078\u9032\u307F\u307E\u3059\u3002")}else{
|
|
204
|
+
await runner.beat("plan");this.planLock.startRenewWorker();let planResult="failed";try{planResult=await this.runPlanAndEnqueue(cycle)}finally{await this.planLock.release(planResult==="ok"?"completed":"failed");this.planLock.reportIfLost()}if(planResult==="ok"&&this.lastPlanWasEmpty)this.recordPlanGateFingerprint();if(planResult==="aborted"){log.log("\u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u306B\u3088\u308A\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u3092\u6253\u3061\u5207\u308A\u307E\u3057\u305F\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002");
|
|
205
|
+
break}if(planResult!=="ok"&&isAiUnavailable(planResult)){undeterminedStreak=0;if(needsHumanToRestoreAi(planResult)){noProgressStreak+=1;unavailableStreak+=1;log.log(`\u26D4 ${aiUnavailableLabel(planResult)}\u305F\u3081\u8A08\u753B\u3067\u304D\u307E\u305B\u3093 (\u9023\u7D9A: ${unavailableStreak})`);log.log(` ${AI_RECOVERY_HINT}`);if(unavailableStreak>=3){exitCode=1;log.log("\u26D4 AI \u30921\u3064\u3082\u8D77\u52D5\u3067\u304D\u306A\u3044\u72B6\u614B\u304C\u7D9A\u3044\u3066\u3044\u307E\u3059\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\uFF08\u7D42\u4E86\u30B3\u30FC\u30C91\uFF09");
|
|
206
|
+
log.log(" **\u518D\u30ED\u30B0\u30A4\u30F3\uFF0F\u30C8\u30FC\u30AF\u30F3\u6295\u5165\u307E\u3067\u518D\u8D77\u52D5\u3057\u3066\u3082\u540C\u3058\u7D50\u679C\u306B\u306A\u308A\u307E\u3059**");break}}else{unavailableStreak=0;log.log(`\u26A0\uFE0F ${aiUnavailableLabel(planResult)}\u3067\u8A08\u753B\u3067\u304D\u307E\u305B\u3093${this.cooldownNote(planResult)}\uFF08\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\u30FB\u6B21\u30B5\u30A4\u30AF\u30EB\u3067\u518D\u5224\u5B9A\uFF09`)}
|
|
207
|
+
if(cycle<config.maxCycles){await runner.beat("waiting");await this.sleepUnlessDraining(config.intervalSec*1e3)}continue}if(planResult!=="ok"){log.log("\u8A08\u753B\u30D5\u30A7\u30FC\u30BA\u304C\u5931\u6557\u3057\u307E\u3057\u305F");if(config.daemon){log.log(`\u30C7\u30FC\u30E2\u30F3\u30E2\u30FC\u30C9\u306E\u305F\u3081 ${config.intervalSec}\u79D2\u5F8C\u306B\u30EA\u30C8\u30E9\u30A4...`);await runner.beat("waiting");await this.sleepUnlessDraining(config.intervalSec*1e3);continue}break}}}const outcome=await this.
|
|
208
|
+
runDequeueLoop(cycle);if(outcome.stop){log.log(this.aborting?"\u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u306B\u3088\u308A\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002":this.draining?`\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u306B\u3088\u308A\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\uFF08\u5B9F\u884C\u4E2D\u306E\u30A2\u30A4\u30C6\u30E0\u306F\u5B8C\u8D70\u6E08\u307F\u30FB\u7D42\u4E86\u30B3\u30FC\u30C9 ${this.drainExitCode}\uFF09\u3002`:"/stop \u30B3\u30DE\u30F3\u30C9\u306B\u3088\u308A\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002");
|
|
209
|
+
if(this.draining)exitCode=this.drainExitCode;break}unavailableStreak=outcome.unexecuted>0&&outcome.needsHuman?unavailableStreak+1:0;if(outcome.progress){noProgressStreak=0;undeterminedStreak=0;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u9032\u6357\u3042\u308A`)}else if(outcome.unexecuted>0&&outcome.needsHuman){undeterminedStreak=0;noProgressStreak+=1;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: AI \u30921\u3064\u3082\u8D77\u52D5\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08${outcome.unexecuted}\
|
|
210
|
+
\u4EF6\u3092\u30AD\u30E5\u30FC\u3078\u8FD4\u5374\u30FB\u9023\u7D9A: ${noProgressStreak}\uFF09`);log.log(` ${AI_RECOVERY_HINT}`)}else if(outcome.unexecuted>0){undeterminedStreak=0;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: AI \u5074\u306E\u90FD\u5408\u3067 ${outcome.unexecuted}\u4EF6\u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F${this.cooldownNote("rate-limited")}\uFF08\u30AD\u30E5\u30FC\u3078\u8FD4\u5374\u30FB\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\uFF09`)}else if(outcome.
|
|
211
|
+
deferred>0){log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u6642\u9593\u5E2F\u30B2\u30FC\u30C8\u3067\u5F85\u6A5F\u4E2D\uFF08${outcome.deferred}\u4EF6\u3092\u5F8C\u56DE\u3057\u30FB\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\uFF09`)}else if(outcome.emptyQueue&&planSkippedDisabled){undeterminedStreak=0;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u8A08\u753B\u3092\u7ACB\u3066\u306A\u3044\u8A2D\u5B9A\u3067\u30AD\u30E5\u30FC\u3082\u7A7A\u3067\u3057\u305F\uFF08\u5F85\u6A5F\u30FB\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\uFF09`)}else if(outcome.
|
|
212
|
+
emptyQueue&&planSkippedNoChange){undeterminedStreak=0;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u5165\u529B\u306B\u5909\u5316\u304C\u306A\u3044\u305F\u3081\u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3001\u30AD\u30E5\u30FC\u3082\u7A7A\u3067\u3057\u305F\uFF08\u5F85\u6A5F\u30FB\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\uFF09`)}else if(outcome.emptyQueue&&planSkippedNoLock){undeterminedStreak=0;if(this.planLock.permanentFail&&this.planLock.failStreak>=config.planLockPermanentMax){
|
|
213
|
+
noProgressStreak+=1;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u8A08\u753B\u30ED\u30C3\u30AF\u306E\u53D6\u5F97\u304C\u6052\u4E45\u30A8\u30E9\u30FC\uFF084xx\uFF09\u3067 ${this.planLock.failStreak}\u30B5\u30A4\u30AF\u30EB\u9023\u7D9A\u3057\u3066\u3044\u307E\u3059`);log.log(` **\u518D\u8A66\u884C\u3067\u306F\u89E3\u6D88\u3057\u306A\u3044\u305F\u3081\u3001\u9032\u6357\u306A\u3057\u3068\u3057\u3066\u6570\u3048\u307E\u3059** (\u9023\u7D9A: ${noProgressStreak})`)}else{log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}\
|
|
214
|
+
: \u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3001\u30AD\u30E5\u30FC\u3082\u7A7A\u3067\u3057\u305F\uFF08\u9023\u7D9A\u30AB\u30A6\u30F3\u30C8\u306F\u52A0\u7B97\u3057\u306A\u3044\u30FB\u6B21\u30B5\u30A4\u30AF\u30EB\u3067\u518D\u5224\u5B9A\uFF09`)}}else if(outcome.undetermined){undeterminedStreak+=1;log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u30AD\u30E5\u30FC\u306E\u72B6\u614B\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08${undeterminedStreak}\u30B5\u30A4\u30AF\u30EB\u9023\u7D9A\u30FB\u9032\u6357\u306A\u3057\u306B\u306F\u6570\u3048\u306A\u3044\uFF09`);
|
|
215
|
+
if(undeterminedStreak>=config.queueUndeterminedMax){log.log(`\u26D4 claim API\u306E\u969C\u5BB3\u304C ${undeterminedStreak} \u30B5\u30A4\u30AF\u30EB\u7D9A\u3044\u3066\u3044\u307E\u3059\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\uFF08\u7D42\u4E86\u30B3\u30FC\u30C91\uFF09`);log.log(" \u78BA\u8A8D: API\u306E\u758E\u901A\uFF0F\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\uFF0F--project \u306E\u6307\u5B9A\u3002\u5FA9\u65E7\u5F8C\u306B\u518D\u8D77\u52D5\u3057\u3066\u304F\u3060\u3055\u3044");
|
|
216
|
+
exitCode=1;break}}else{undeterminedStreak=0;noProgressStreak+=1;log.log(outcome.emptyQueue?`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u30AD\u30E5\u30FC\u304C\u7A7A\u3067\u3057\u305F (\u9023\u7D9A: ${noProgressStreak})`:`\u30B5\u30A4\u30AF\u30EB ${cycle}: \u9032\u6357\u306A\u3057 (\u9023\u7D9A: ${noProgressStreak})`)}log.log(`\u30B5\u30A4\u30AF\u30EB ${cycle} \u5B8C\u4E86 (duration: ${Math.trunc((Date.now()-cycleStart)/1e3)}s)`);if(noProgressStreak>=3){log.log("3\u30B5\u30A4\u30AF\u30EB\u9023\u7D9A\u3067\u9032\u6357\u306A\u3057\u3002\u30EB\u30FC\u30D7\u3092\u7D42\u4E86\u3057\u307E\u3059\u3002");
|
|
217
|
+
if(unavailableStreak>=3){exitCode=1;log.log("\u26D4 \u539F\u56E0\u306F\u300CAI \u30921\u3064\u3082\u8D77\u52D5\u3067\u304D\u306A\u3044\u300D\u3053\u3068\u3067\u3059\uFF08\u672A\u30ED\u30B0\u30A4\u30F3\u7B49\uFF09\u3002");log.log(` ${AI_RECOVERY_HINT}`);log.log(" **\u8CC7\u683C\u60C5\u5831\u3092\u76F4\u3059\u307E\u3067\u518D\u8D77\u52D5\u3057\u3066\u3082\u540C\u3058\u7D50\u679C\u306B\u306A\u308A\u307E\u3059**")}if(this.planLock.permanentFail){log.log("\u26D4 \u539F\u56E0\u306F\u8A08\u753B\u30ED\u30C3\u30AFAPI\u306E\u6052\u4E45\u30A8\u30E9\u30FC\uFF084xx\uFF09\u3067\u3059\u3002**\u8A2D\u5B9A\u3092\u76F4\u3059\u307E\u3067\u518D\u8D77\u52D5\u3057\u3066\
|
|
218
|
+
\u3082\u540C\u3058\u7D50\u679C\u306B\u306A\u308A\u307E\u3059**");exitCode=1}break}if(cycle<config.maxCycles){log.log(`\u6B21\u30B5\u30A4\u30AF\u30EB\u307E\u3067 ${config.intervalSec}\u79D2 \u5F85\u6A5F...`);await runner.beat("waiting");await this.sleepUnlessDraining(config.intervalSec*1e3)}}log.separator();this.abortDrained?.();log.log("twp task-loop \u7D42\u4E86");log.log(` \u7DCF\u30B5\u30A4\u30AF\u30EB\u6570: ${cycle}`);log.log(` \u30ED\u30B0: ${config.logDir}`);log.separator();return exitCode}async hasPendingItems(){
|
|
219
|
+
const res=await this.deps.api.list({status:"pending",limit:1});if(!res.ok){this.deps.log.log(` \u26A0\uFE0F pending\u4EF6\u6570\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08${describeError(res)}\uFF09\u3002\u5B89\u5168\u5074\u306B\u5012\u3057\u3066\u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u307E\u3059\u3002`);return true}const items=pick(res.json,"items");if(!Array.isArray(items)){this.deps.log.log(` \u26A0\uFE0F pending\u4EF6\u6570\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.
|
|
219
220
|
raw.slice(0,120)}\uFF09\u3002\u5B89\u5168\u5074\u306B\u5012\u3057\u3066\u8A08\u753B\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u307E\u3059\u3002`);return true}return filterByStatus(items,"pending").length>0}async reclaimStaleProcessing(){const{config,log,api}=this.deps;if(config.staleReclaimHours<=0)return;const floorH=staleFloorHours(config.aiTimeoutSec);let hours=config.staleReclaimHours;if(hours<floorH){log.log(` \u2139\uFE0F STALE_RECLAIM_HOURS=${hours}h \u306F\u6700\u9577\u5B9F\u884C\u6642\u9593(AI_TIMEOUT\xD72=${floorH}\
|
|
220
221
|
h)\u3092\u4E0B\u56DE\u308B\u305F\u3081 ${floorH}h \u3092\u4F7F\u3044\u307E\u3059`);hours=floorH}const thresholdMs=hours*36e5;const now=Date.now();const stale=[];let cursor;for(let page=0;page<50;page++){const res=await api.list({status:"processing",limit:200,cursor});if(!res.ok){log.log(` \u26A0\uFE0F stale processing \u306E\u8D70\u67FB\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${describeError(res)}\uFF09\u3002`);log.log(" \u53D6\u308A\u6B8B\u3057\u306E\u56DE\u53CE\u306F\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u884C\u308F\u308C\u3066\u3044\u307E\u305B\u3093");
|
|
221
222
|
return}const items=pick(res.json,"items");if(!Array.isArray(items)){log.log(` \u26A0\uFE0F stale processing \u306E\u4E00\u89A7\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.raw.slice(0,120)}\uFF09\u3002`);log.log(" \u53D6\u308A\u6B8B\u3057\u306E\u56DE\u53CE\u306F\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u884C\u308F\u308C\u3066\u3044\u307E\u305B\u3093");return}for(const it of filterByStatus(items,"processing")){if(it.runner_id)continue;
|
|
@@ -233,15 +234,17 @@ led \u3068\u3057\u3066\u8FD4\u3057\u307E\u305B\u3093**")}else{await this.schedul
|
|
|
233
234
|
scheduleId}] ${row.windowKey} \u2192 ${itemId}\uFF09`);log.log(" **\u30EA\u30FC\u30B9\u671F\u9650\u5F8C\u306B\u540C\u3058\u67A0\u304C\u518D\u6295\u5165\u3055\u308C\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059**\u3002\u5B9A\u671F\u67A0\u304C\u672C\u756A\u30EA\u30EA\u30FC\u30B9\u306A\u3089\u4E8C\u91CD\u5B9F\u884C\u306B\u306A\u308A\u307E\u3059")}if(exclusiveSkill!==null)exclusiveEnqueued.add(exclusiveSkill);enqueuedLines.push(`- [${row.priority}] ${row.label} \u2192 ${prompt}`);log.log(
|
|
234
235
|
` \u5B9A\u671F\u30A8\u30F3\u30AD\u30E5\u30FC: [${row.priority}] ${row.label} \u2192 ${prompt}`);count+=1}if(count>0){log.log(midcycle?`\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\uFF08\u4E2D\u9593\u5224\u5B9A\uFF09: ${count}\u4EF6\u3092\u30AD\u30E5\u30FC\u306B\u6295\u5165\u3057\u307E\u3057\u305F`:`\u5B9A\u671F\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB: ${count}\u4EF6\u3092\u30AD\u30E5\u30FC\u306B\u6295\u5165\u3057\u307E\u3057\u305F`);this.midcycleEnqueued+=count}else if(!midcycle){log.log("\u5B9A\u671F\u30B9\u30B1\u30B8\
|
|
235
236
|
\u30E5\u30FC\u30EB: \u4ECA\u30B5\u30A4\u30AF\u30EB\u3067\u767A\u706B\u3057\u305F\u5B9A\u671F\u30BF\u30B9\u30AF\u306F\u3042\u308A\u307E\u305B\u3093")}if(!midcycle){const file=path5.join(this.deps.config.logDir,`schedule-enqueued-${this.timestamp}.txt`);try{fs7.mkdirSync(path5.dirname(file),{recursive:true});fs7.writeFileSync(file,enqueuedLines.join("\n"))}catch{}}}async maybeEnqueueDueMidcycle(){const res=await this.deps.api.reclaim();if(!res.ok){this.deps.log.log(` \u26A0\uFE0F \u6B7B\u3093\u3060\u30E9\u30F3\u30CA\u30FC\u306E\u30A2\u30A4\u30C6\u30E0\u56DE\u53CEAPI\u304C\u5931\u6557\u3057\u307E\u3057\u305F\uFF08${describeError(
|
|
236
|
-
res)}\uFF09`)}if(this.midcycleEnqueued>=this.deps.config.scheduleMidcycleMax)return;await this.enqueueDueScheduled(true)}async
|
|
237
|
-
|
|
238
|
-
|
|
237
|
+
res)}\uFF09`)}if(this.midcycleEnqueued>=this.deps.config.scheduleMidcycleMax)return;await this.enqueueDueScheduled(true)}async planGateSaysSkip(){const{config,log}=this.deps;this.planGateFingerprint=null;const gate=config.operations.planGate;if(gate===null)return false;const decision=await evaluatePlanGate(gate,{cwd:config.workspace,statePath:planGateStatePath(config.stateDir,projectFileKey(config.projectId)),nowMs:Date.now()});log.log(` plan_gate: ${decision.reason}`);this.planGateFingerprint=
|
|
238
|
+
decision.fingerprint;return decision.skip}recordPlanGateFingerprint(){const{config,log}=this.deps;const fingerprint=this.planGateFingerprint;this.planGateFingerprint=null;if(fingerprint===null)return;const statePath=planGateStatePath(config.stateDir,projectFileKey(config.projectId));if(!recordPlanned(statePath,fingerprint,Date.now())){log.log(` \u26A0\uFE0F plan_gate: \u8A08\u753B\u6642\u306E\u6307\u7D0B\u3092 ${statePath} \u306B\u8A18\u9332\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u6B21\u30B5\u30A4\u30AF\u30EB\u3082\u8A08\u753B\u3057\u307E\u3059\uFF09`)}}async runPlanAndEnqueue(cycle){
|
|
239
|
+
const{config,log}=this.deps;this.lastPlanWasEmpty=false;const planSkill=config.operations.planSkill;if(planSkill===null)return"failed";log.separator();log.log("Phase 1: \u8A08\u753B\u3092\u7ACB\u6848\u3057\u3066\u30AD\u30E5\u30FC\u306B\u683C\u7D0D...");log.separator();const planLogFile=path5.join(config.logDir,`plan-${this.timestamp}-${cycle}.log`);const enqueuedFile=path5.join(config.logDir,`schedule-enqueued-${this.timestamp}.txt`);const scheduleSection=await this.schedule.promptSection(enqueuedFile);
|
|
240
|
+
if(config.prefetch.length>0)log.log(`\u8A08\u753B\u7528\u30C7\u30FC\u30BF\u3092\u4E8B\u524D\u53D6\u5F97\u4E2D\uFF08\u30D5\u30C3\u30AF ${config.prefetch.length}\u4EF6\uFF09...`);const prefetchSection=await runPrefetch(config.prefetch,config.workspace,m=>log.log(m));const excludeKeys=parsePlanExcludeKeys(prefetchSection);if(excludeKeys.size>0){log.log(` \u8A08\u753B\u5019\u88DC\u304B\u3089\u5916\u3059\u30BF\u30B9\u30AF\uFF08\u672A\u56DE\u7B54\u306E\u8CEA\u554F\u3042\u308A\uFF09: ${[...excludeKeys].
|
|
241
|
+
sort().join(", ")}`)}const taskStatusSnapshot=parseTaskStatusSnapshot(prefetchSection);if(taskStatusSnapshot===null){log.log(" \u26A0\uFE0F prefetch \u306B OPS_TASK_STATUS \u30DE\u30FC\u30AB\u30FC\u304C\u3042\u308A\u307E\u305B\u3093");log.log(" \u300C\u524D\u56DE\u304C\u72B6\u614B\u3092\u9032\u3081\u305F\u5834\u5408\u306E\u518D\u6295\u5165\u6291\u6B62\u300D\u306F**\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u7121\u52B9**\u3067\u3059\uFF08\u6295\u5165\u306F\u6B62\u3081\u307E\u305B\u3093\uFF09")}else if(!taskStatusSnapshot.
|
|
239
242
|
complete){log.log(" \u26A0\uFE0F \u30BF\u30B9\u30AF\u306E\u30B9\u30C6\u30FC\u30BF\u30B9\u3092\u4E00\u90E8\u53D6\u5F97\u3067\u304D\u3066\u3044\u307E\u305B\u3093\uFF08complete=0\uFF09\u2192 \u518D\u6295\u5165\u6291\u6B62\u306F\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u7121\u52B9\u3067\u3059")}const outcomeReports=await fetchOutcomeReports(this.deps.api,config.outcomeSkills??[]);for(const w of outcomeStreakWarnings(outcomeReports))log.log(` \u26A0\uFE0F ${w}`);const outcomeSection=renderOutcomeSection(
|
|
240
243
|
outcomeReports);const result=await this.engine.run({prompt:buildPlanPrompt(config,planSkill,scheduleSection,prefetchSection,outcomeSection),promptPrefix:this.cyclePreflightSection,logFile:planLogFile,timeoutSec:config.planTimeoutSec,cwd:config.workspace,skill:normalizeSkillName(planSkill.replace(/^\//,"")),validate:output=>extractPlanJson(output)!==null});writeLogFile(planLogFile,result.output);if(result.outcome==="aborted"){log.log(" \u23F9 \u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u306B\u3088\u308A\u8A08\u753B\u3092\u6253\u3061\u5207\u308A\u307E\u3057\u305F");
|
|
241
244
|
return"aborted"}if(result.outcome!=="ok"){if(isAiUnavailable(result.outcome)){log.log(` \u23ED AI \u3092\u8D77\u52D5\u3067\u304D\u306A\u3044\u305F\u3081\u8A08\u753B\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08outcome=${result.outcome}\uFF09`);return result.outcome}log.log(` \u26D4 \u8A08\u753B\u306E\u5B9F\u884C\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08outcome=${result.outcome}\uFF09`);return"failed"}if(this.planLock.isLost()){log.log(` \u26D4 \u8A08\u753B\u4E2D\u306B\u8A08\u753B\u30ED\u30C3\u30AF\u3092\u5931\u3044\u307E\u3057\u305F\uFF08reason=${this.
|
|
242
|
-
planLock.lostReasonText()}\uFF09`);log.log(" **\u30A8\u30F3\u30AD\u30E5\u30FC\u3092\u4E2D\u6B62\u3057\u307E\u3059**\u3002\u8A08\u753B\u7D50\u679C\u306F\u7834\u68C4\u3057\u3001\u6B21\u30B5\u30A4\u30AF\u30EB\u3067\u53D6\u308A\u76F4\u3057\u307E\u3059");return"ok"}const plan=extractPlanJson(result.output);if(!plan||plan.steps.length===0){log.log("\u8A08\u753B\u306Bsteps\u304C\u3042\u308A\u307E\u305B\u3093");return"ok"}const verifyBacklog=parseOpsCount(prefetchSection,"
|
|
243
|
-
steps.filter(s=>(s.skill??"").trim()==="dev-verify").length;const releaseDeployDrop=releaseDeployDropReason(verifyBacklog,devVerifyPlanned);if(releaseDeployDrop!==null&&plan.steps.some(s=>normalizeSkillName(s.skill??"")==="release-deploy")){log.log(` release-deploy \u306F\u8A08\u753B\u304B\u3089\u9664\u5916\u3057\u307E\u3059\uFF08\u7A7A\u632F\u308A\u9632\u6B62\u30AC\u30FC\u30C9\uFF09: ${releaseDeployDrop}`)}const zeroTargetDrops=zeroTargetDropReasons(prefetchSection,
|
|
244
|
-
for(const[skill,reason]of zeroTargetDrops){if(plan.steps.some(s=>normalizeSkillName(s.skill??"")===skill)){log.log(` ${skill} \u306F\u8A08\u753B\u304B\u3089\u9664\u5916\u3057\u307E\u3059\uFF08\u5BFE\u8C61\u8AAD\u307F\u66FF\u3048\u9632\u6B62\u30AC\u30FC\u30C9\uFF09: ${reason}`)}}const processing=await this.deps.api.processingSnapshot();const inflightKeys=new Set;if(processing===null){log.log(" \u26A0\uFE0F \u51E6\u7406\u4E2D\u30A2\u30A4\u30C6\u30E0\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F");
|
|
245
|
+
planLock.lostReasonText()}\uFF09`);log.log(" **\u30A8\u30F3\u30AD\u30E5\u30FC\u3092\u4E2D\u6B62\u3057\u307E\u3059**\u3002\u8A08\u753B\u7D50\u679C\u306F\u7834\u68C4\u3057\u3001\u6B21\u30B5\u30A4\u30AF\u30EB\u3067\u53D6\u308A\u76F4\u3057\u307E\u3059");return"ok"}const plan=extractPlanJson(result.output);if(!plan||plan.steps.length===0){log.log("\u8A08\u753B\u306Bsteps\u304C\u3042\u308A\u307E\u305B\u3093");this.lastPlanWasEmpty=true;return"ok"}const verifyBacklog=parseOpsCount(prefetchSection,"\
|
|
246
|
+
verify");const devVerifyPlanned=plan.steps.filter(s=>(s.skill??"").trim()==="dev-verify").length;const releaseDeployDrop=releaseDeployDropReason(verifyBacklog,devVerifyPlanned);if(releaseDeployDrop!==null&&plan.steps.some(s=>normalizeSkillName(s.skill??"")==="release-deploy")){log.log(` release-deploy \u306F\u8A08\u753B\u304B\u3089\u9664\u5916\u3057\u307E\u3059\uFF08\u7A7A\u632F\u308A\u9632\u6B62\u30AC\u30FC\u30C9\uFF09: ${releaseDeployDrop}`)}const zeroTargetDrops=zeroTargetDropReasons(prefetchSection,
|
|
247
|
+
config.operations.zeroTargetGates);for(const[skill,reason]of zeroTargetDrops){if(plan.steps.some(s=>normalizeSkillName(s.skill??"")===skill)){log.log(` ${skill} \u306F\u8A08\u753B\u304B\u3089\u9664\u5916\u3057\u307E\u3059\uFF08\u5BFE\u8C61\u8AAD\u307F\u66FF\u3048\u9632\u6B62\u30AC\u30FC\u30C9\uFF09: ${reason}`)}}const processing=await this.deps.api.processingSnapshot();const inflightKeys=new Set;if(processing===null){log.log(" \u26A0\uFE0F \u51E6\u7406\u4E2D\u30A2\u30A4\u30C6\u30E0\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F");
|
|
245
248
|
log.log(" \u540C\u4E00\u30BF\u30B9\u30AF\u306E\u4E8C\u91CD\u7740\u624B\u30AC\u30FC\u30C9\u306F**\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u7121\u52B9**\u3067\u3059\uFF08\u6295\u5165\u306F\u6B62\u3081\u307E\u305B\u3093\uFF09")}else{const entries=inflightEntries(processing,new Date,inflightStaleHours(config.aiTimeoutSec));for(const entry of entries)inflightKeys.add(entry.key);if(entries.length>0){log.log(" \u4ED6\u30E9\u30F3\u30CA\u30FC\u304C\u51E6\u7406\u4E2D\u306E task_key\uFF08\u3053\u306E\u8A08\u753B\u304B\u3089\u306F\u9664\u5916\u3057\u307E\u3059\uFF09:");
|
|
246
249
|
for(const entry of entries)log.log(` - ${formatInflightEntry(entry)}`)}}let pendingCache=null;let pendingFetched=false;const pendingOnce=async()=>{if(!pendingFetched){pendingFetched=true;pendingCache=await this.deps.api.pendingSnapshot()}return pendingCache};let pendingKeys=null;let pendingKeysResolved=false;const queuedPendingKeys=async()=>{if(pendingKeysResolved)return pendingKeys;pendingKeysResolved=true;const pending=await pendingOnce();if(pending===null){log.log(" \u26A0\uFE0F pending \u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\
|
|
247
250
|
\u3093\u3067\u3057\u305F");log.log(" \u30AD\u30E5\u30FC\u5F85\u3061\u30AD\u30FC\u306E\u7A4D\u307F\u76F4\u3057\u6291\u6B62\u306F**\u3053\u306E\u30B5\u30A4\u30AF\u30EB\u7121\u52B9**\u3067\u3059\uFF08\u6295\u5165\u306F\u6B62\u3081\u307E\u305B\u3093\uFF09");return null}pendingKeys=new Set(pending.map(p=>(p.task_key??"").trim()).filter(k=>k!==""));return pendingKeys};let exclusiveQueued=null;let exclusiveFetched=false;const exclusiveInflight=async()=>{if(exclusiveFetched)return exclusiveQueued;exclusiveFetched=
|
|
@@ -329,12 +332,12 @@ const startedAtMs=now();let warned="";let done=false;const check=()=>{if(done)re
|
|
|
329
332
|
decision.key)return;warned=decision.key;handlers.onWarn(decision.reason);return}done=true;const recorded=writeRestartAttempt(opts.stateDir,opts.projectKey,{from:decision.from,to:decision.to,at:new Date(now()).toISOString()},opts.store);if(!recorded){handlers.onWarn(`\u518D\u8D77\u52D5\u8A18\u9332\u3092\u66F8\u3051\u307E\u305B\u3093\u3067\u3057\u305F\uFF08${restartAttemptPath(opts.stateDir,opts.projectKey)}\uFF09\u3002\u540C\u3058\u7248\u30C9\u30EA\u30D5\u30C8\u304C\u89E3\u6D88\u3057\u306A\u3044\u5834\u5408\u3001\u518D\u8D77\u52D5\u3092\u7E70\u308A\u8FD4\u3059\u9632\u6CE2\u5824\u304C\u52B9\u304D\u307E\u305B\u3093`)}
|
|
330
333
|
handlers.onRestart({from:decision.from,to:decision.to})};const timer=setInterval(check,opts.intervalMs??DRIFT_POLL_MS);timer.unref?.();return{stop:()=>{done=true;clearInterval(timer)},check}}import fs9 from"fs";import path7 from"path";var POLL_MS=1e3;var MAX_STOP_BYTES=4096;var MAX_AT_LENGTH=64;function markerPath(lockDir2,kind){return path7.join(lockDir2,kind)}function requestMarker(lockDir2,kind,pid,deps={}){const target=markerPath(lockDir2,kind);const write=deps.writeFileSync??((p,d)=>fs9.writeFileSync(p,d,{flag:"wx",mode:384}));const now=deps.now??(()=>new Date);clearMarker(lockDir2,kind,deps);try{write(target,`${JSON.stringify({pid,at:now().toISOString()})}
|
|
331
334
|
`);return{ok:true}}catch(err){const e=err;return{ok:false,reason:e.code??"UNKNOWN"}}}function readMarker(lockDir2,kind,deps={}){const target=markerPath(lockDir2,kind);const read=deps.readFileSync??(p=>fs9.readFileSync(p,"utf8"));const size=deps.statSize??(p=>fs9.statSync(p).size);let raw;try{if(size(target)>MAX_STOP_BYTES)return null;raw=read(target)}catch{return null}if(raw.length>MAX_STOP_BYTES)return null;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return null;const pid=parsed.pid;const at=parsed.at;if(typeof pid!=="number"||!Number.isInteger(pid)||
|
|
332
|
-
pid<=0)return null;return{pid,at:sanitizeAt(at)}}catch{return null}}function sanitizeAt(at){if(typeof at!=="string")return"";return at.replace(/[\u0000-\u001f\u007f]/g," ").slice(0,MAX_AT_LENGTH)}function clearMarker(lockDir2,kind,deps={}){const rm=deps.rmSync??(p=>fs9.rmSync(p,{recursive:true,force:true}));try{rm(markerPath(lockDir2,kind))}catch{}}function watchMarker(lockDir2,kind,selfPid,onStop,deps={}){let fired=false;const timer=setInterval(()=>{if(fired)return;const req=readMarker(lockDir2,kind,deps);if(req===null||req.pid!==selfPid)return;fired=true;onStop(req)},deps.intervalMs??POLL_MS);timer.unref?.();return()=>{fired=true;clearInterval(timer)}}function safe(s){return stripTerminalControls(s)}function compactTimestamp(at=new Date){const p2=n=>String(n).padStart(2,"0");return`${at.getFullYear()}${p2(at.getMonth()+1)}${p2(at.getDate())}-${p2(at.getHours())}${p2(at.getMinutes())}${p2(at.getSeconds())}`}async function buildEngine(config,log){if(config.engine==="noop")return new NoopEngine;const{DispatchEngine}=await import("./ai-dispatch-
|
|
335
|
+
pid<=0)return null;return{pid,at:sanitizeAt(at)}}catch{return null}}function sanitizeAt(at){if(typeof at!=="string")return"";return at.replace(/[\u0000-\u001f\u007f]/g," ").slice(0,MAX_AT_LENGTH)}function clearMarker(lockDir2,kind,deps={}){const rm=deps.rmSync??(p=>fs9.rmSync(p,{recursive:true,force:true}));try{rm(markerPath(lockDir2,kind))}catch{}}function watchMarker(lockDir2,kind,selfPid,onStop,deps={}){let fired=false;const timer=setInterval(()=>{if(fired)return;const req=readMarker(lockDir2,kind,deps);if(req===null||req.pid!==selfPid)return;fired=true;onStop(req)},deps.intervalMs??POLL_MS);timer.unref?.();return()=>{fired=true;clearInterval(timer)}}function safe(s){return stripTerminalControls(s)}function compactTimestamp(at=new Date){const p2=n=>String(n).padStart(2,"0");return`${at.getFullYear()}${p2(at.getMonth()+1)}${p2(at.getDate())}-${p2(at.getHours())}${p2(at.getMinutes())}${p2(at.getSeconds())}`}async function buildEngine(config,log){if(config.engine==="noop")return new NoopEngine;const{DispatchEngine}=await import("./ai-dispatch-EEX3FOFD.js");const{DEFAULT_PREFLIGHT_HOSTS}=await import("./ai-dispatch-EEX3FOFD.js");const extraHosts=config.
|
|
333
336
|
operations.preflightHosts;return new DispatchEngine(config.ai,log,{workspace:config.workspace,charterFile:config.charterFile??void 0,charterEnabled:config.charterEnabled,...config.charterPrefix===null?{}:{charterPrefix:config.charterPrefix},...config.charterSuffix===null?{}:{charterSuffix:config.charterSuffix},serverPrompts:()=>config.serverPrompts??{},compileCommand:config.compileCommand??void 0,skillOverlayDir:path8.join(config.stateDir,"skill-overlay",projectFileKey(config.projectId)),launcherBin:config.
|
|
334
337
|
claudeLauncher.bin,...extraHosts.length>0?{preflightHosts:[...DEFAULT_PREFLIGHT_HOSTS,...extraHosts]}:{}})}function lockDir(config){return path8.join(config.stateDir,`task-loop-${projectFileKey(config.projectId)}.lock.d`)}async function runTaskLoop(opts){if(opts.action==="stop")return await stopLoop(opts);const profile=resolveProfile(opts.profile);let creds;try{creds=new AuthSession(profile.name,profile.apiUrl).loadOrThrow()}catch(err){process.stderr.write(`${err.message}
|
|
335
338
|
`);return 1}const apiUrl=effectiveApiUrl(profile,creds.api_url);const session=new AuthSession(profile.name,apiUrl);const projectRef=opts.project??process.env.TWP_PROJECT??"";if(projectRef===""){process.stderr.write("--project <\u30AD\u30FC|UUID> \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08TWP_PROJECT \u3067\u3082\u53EF\uFF09\n");return 2}const projectApi=new ProjectApi(apiUrl,session);let project;try{project=await projectApi.resolve(projectRef)}catch(err){process.stderr.write(`${err.
|
|
336
339
|
message}
|
|
337
|
-
`);return 1}const projectId=project.id;if(opts.action==="setup"){const{runSetup,parseAiList}=await import("./setup-
|
|
340
|
+
`);return 1}const projectId=project.id;if(opts.action==="setup"){const{runSetup,parseAiList}=await import("./setup-U22KITRG.js");let ais;if(opts.ais!==void 0&&opts.ais.length>0){const parsed=parseAiList(opts.ais.join(","));if(parsed.unknown.length>0){process.stderr.write(`--ai \u306B\u672A\u77E5\u306E\u5024\u304C\u3042\u308A\u307E\u3059: ${parsed.unknown.join(" / ")}
|
|
338
341
|
`);return 2}ais=parsed.ais}return runSetup({projectId,projectRef,projectName:project.name===project.id?projectRef:`${project.code} / ${project.name}`,apiUrl,yes:opts.yes===true,...ais!==void 0?{ais}:{},...opts.workspace!==void 0?{workspace:opts.workspace}:{},...opts.aiConfigFile!==void 0?{aiConfigFile:opts.aiConfigFile}:{},...opts.noAiConfigFile===true?{noAiConfigFile:true}:{},...opts.profile!==void 0?{profile:opts.profile}:{}})}if(opts.action==="charter"){if(opts.charterOp===void 0){process.stderr.
|
|
339
342
|
write("charter \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}if(isPrivateProjectId(projectId)){process.stderr.write("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30E5\u30FC\uFF08--project __private__\uFF09\u306B\u306F\u61B2\u7AE0\u306E\u8A2D\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093\n");return 2}const{runCharterCommand}=await import("./charter-command-LIX2JXRJ.js");return runCharterCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.
|
|
340
343
|
charterOp,file:opts.charterInput,out:opts.charterOutput,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}if(opts.action==="skill"){if(opts.skillOp===void 0){process.stderr.write("skill \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}if(isPrivateProjectId(projectId)){process.stderr.write("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30E5\u30FC\uFF08--project __private__\uFF09\u306B\u306F\u30B9\u30AD\u30EB\u5B9A\u7FA9\u306E\u8A2D\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093\n");
|
|
@@ -356,7 +359,7 @@ log.log("\u4E2D\u65AD\u30B7\u30B0\u30CA\u30EB\u3092\u53D7\u4FE1\u3057\u307E\u305
|
|
|
356
359
|
"\u6642\u523B\u4E0D\u660E"}\uFF09\u3002\u7D42\u4E86\u3057\u307E\u3059...`);stopWatcher?.();drainWatcher?.();driftWatcher?.();void shutdown().catch(()=>void 0).then(()=>process.exit(130))});drainWatcher=watchMarker(lockDir(config),"drain",process.pid,req=>{drainWatcher?.();if(loop===null){pendingDrain.value={reason:`stop --drain\u30FB${req.at||"\u6642\u523B\u4E0D\u660E"}`,exitCode:0};log.log(`\u30C9\u30EC\u30A4\u30F3\u8981\u6C42\u3092\u53D7\u3051\u53D6\u308A\u307E\u3057\u305F\uFF08${req.at||"\u6642\u523B\u4E0D\u660E"}\
|
|
357
360
|
\uFF09\u3002\u8D77\u52D5\u51E6\u7406\u306E\u5B8C\u4E86\u5F8C\u306B\u53CD\u6620\u3057\u307E\u3059\u3002`);return}loop.requestDrain(`stop --drain\u30FB${req.at||"\u6642\u523B\u4E0D\u660E"}`)});if(installed!==null){const watch=watchVersionDrift({runningVersion:opts.version,stateDir:config.stateDir,projectKey:projectFileKey(config.projectId),supervised:autoRestart.supervised,disabled:autoRestart.disabled},{onWarn:reason=>log.log(`\u26A0\uFE0F ${reason}`),onRestart:({from,to})=>{driftWatcher?.();log.
|
|
358
361
|
log(`\u7248\u30C9\u30EA\u30D5\u30C8\u3092\u691C\u51FA\u3057\u307E\u3057\u305F\uFF08${from} \u2192 ${to}\uFF09\u3002`);log.log(` \u5B9F\u884C\u4E2D\u306E\u30A2\u30A4\u30C6\u30E0\u3092\u5B8C\u8D70\u3055\u305B\u3066\u304B\u3089\u7D42\u4E86\u3057\u307E\u3059\uFF08\u7D42\u4E86\u30B3\u30FC\u30C9 ${EXIT_VERSION_DRIFT}\uFF09\u3002\u518D\u8D77\u52D5\u306F systemd\uFF08Restart=always\uFF09\u304C\u884C\u3044\u307E\u3059`);const reason=`\u7248\u30C9\u30EA\u30D5\u30C8 ${from} \u2192 ${to} \u306B\u3088\u308B\u81EA\u52D5\u518D\u8D77\u52D5`;
|
|
359
|
-
if(loop===null)pendingDrain.value={reason,exitCode:EXIT_VERSION_DRIFT};else loop.requestDrain(reason,EXIT_VERSION_DRIFT)}});driftWatcher=watch.stop}try{const{LoopSettingsApplier:LoopSettingsApplier2}=await import("./server-settings-
|
|
362
|
+
if(loop===null)pendingDrain.value={reason,exitCode:EXIT_VERSION_DRIFT};else loop.requestDrain(reason,EXIT_VERSION_DRIFT)}});driftWatcher=watch.stop}try{const{LoopSettingsApplier:LoopSettingsApplier2}=await import("./server-settings-3YD7RR3A.js");const settings=new LoopSettingsApplier2({api,config,log:m=>log.log(m)});await settings.apply();const{ServerSkillCatalog:ServerSkillCatalog2}=await import("./server-skills-5CKBIIQ4.js");const skills=new ServerSkillCatalog2({api,config,log:m=>log.log(m)});await skills.
|
|
360
363
|
refresh();await runner.checkHeartbeatInterval();await runner.registerOrThrow();runner.startHeartbeatWorker();log.log(` heartbeat: ${config.heartbeatIntervalSec}\u79D2\u3054\u3068\u306B\u9001\u4FE1${runner.heartbeatTimeoutServer?`\uFF08\u30B5\u30FC\u30D0\u306E\u6B7B\u6D3B\u3057\u304D\u3044\u5024 ${runner.heartbeatTimeoutServer}\u79D2\uFF09`:""}`);loop=new TaskLoop({api,projectApi,config,log,runner,engine:await buildEngine(config,m=>log.log(m)),settings,skills});if(pendingDrain.value!==null){loop.
|
|
361
364
|
requestDrain(pendingDrain.value.reason,pendingDrain.value.exitCode)}exitCode=await loop.run()}catch(err){if(err instanceof RunnerRegistrationError){exitCode=1}else{log.log(`\u26D4 \u4E88\u671F\u3057\u306A\u3044\u30A8\u30E9\u30FC\u3067\u7D42\u4E86\u3057\u307E\u3059: ${err.message}`);exitCode=1}}finally{await shutdown()}return exitCode}async function showStatus(api,config){const out={write:text=>process.stdout.write(stripTerminalControls(text))};out.write(`\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8: ${config.
|
|
362
365
|
projectRef}\uFF08${config.projectId}\uFF09
|
|
@@ -50,7 +50,7 @@ ${err.hint?`${err.hint}
|
|
|
50
50
|
`);return 1}writeErr(`\u30A8\u30E9\u30FC: ${err.message}
|
|
51
51
|
`);return 1}}async function runLogin(options){return run(async()=>{const profile=resolveProfile(options.profile);const io=makeIo(options.cliVersion);if(options.method==="password"){await passwordLogin(profile,{tenantCode:options.tenant??void 0},process.env,io)}else if(options.method==="token"){await tokenLogin(profile,process.env,io)}else{await browserLogin(profile,process.env,io,{noBrowser:options.noBrowser})}})}async function runLogout(options){return run(async()=>{const profile=resolveProfile(
|
|
52
52
|
options.profile);const creds=loadCredentials(profile.name);if(!creds){writeOut(`\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u300C${profile.name}\u300D\u306F\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093\u3002
|
|
53
|
-
`);return}const{describeLogoutImpact,findLoopsUsingProfile}=await import("./logout-guard-
|
|
53
|
+
`);return}const{describeLogoutImpact,findLoopsUsingProfile}=await import("./logout-guard-GQBF3GQH.js");const found=findLoopsUsingProfile(profile.name,options.logoutGuard);if(found.users.length>0||found.undetermined.length>0){writeErr(describeLogoutImpact(profile.name,found,options.force===true));if(options.force!==true)throw new LogoutRefusedError}const apiUrl=effectiveApiUrl(profile,creds.api_url);const revoked=await httpFetch(`${apiUrl}/api/v2/auth/logout`,{method:"POST",headers:{Accept:"applic\
|
|
54
54
|
ation/json",Authorization:`Bearer ${creds.token}`}}).then(res=>res.ok,()=>false);await deleteCredentials(profile.name);writeOut(`\u2705 \u30ED\u30B0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F\uFF08\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB: ${profile.name} / \u30C8\u30FC\u30AF\u30F3: ${maskToken(creds.token)}\uFF09
|
|
55
55
|
`);if(!revoked){writeOut("\u26A0 \u30B5\u30FC\u30D0\u5074\u306E\u30C8\u30FC\u30AF\u30F3\u5931\u52B9\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08\u30AA\u30D5\u30E9\u30A4\u30F3\u7B49\uFF09\u3002TWP \u306E\u300C\u8A2D\u5B9A > CLI\u7AEF\u672B\u300D\u304B\u3089\u3082\u5931\u52B9\u3067\u304D\u307E\u3059\u3002\n")}})}async function runWhoami(options){return run(async()=>{const profile=resolveProfile(options.profile);const structured=options.output!==void 0||options.query!==void 0;let format=null;if(structured){
|
|
56
56
|
const{resolveOutputFormat,OUTPUT_FORMATS}=await import("./format-F6PPBPY5.js");format=resolveOutputFormat({...options.output!==void 0?{flag:options.output}:{},isTty:process.stdout.isTTY===true});if(format===null){throw new UsageError(`--output \u306B\u300C${options.output??""}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${OUTPUT_FORMATS.join(" / ")} \u3067\u3059`)}}const stored=loadCredentials(profile.name);const apiUrl=effectiveApiUrl(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{defaultIsLoopProcess,readLockOwner,sameTwpHome}from"./chunk-3WHC4FSG.js";import{LEGACY_STATE_DIR_NAME,STATE_DIR_NAME,loopStateDir}from"./chunk-
|
|
3
|
+
import{defaultIsLoopProcess,readLockOwner,sameTwpHome}from"./chunk-3WHC4FSG.js";import{LEGACY_STATE_DIR_NAME,STATE_DIR_NAME,loopStateDir}from"./chunk-2B7A3OY7.js";import"./chunk-AEJHDFXB.js";import"./chunk-N2UVRM3Z.js";import"./chunk-GY7KI5E5.js";import"./chunk-PMOUHEJQ.js";import"./chunk-5WGOHFAS.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs from"fs";import os from"os";import path from"path";var PIDLESS_GRACE_MS=6e4;function defaultStateDirs(env){const home=os.homedir();const dirs=[loopStateDir(env),path.join(home,STATE_DIR_NAME),path.join(home,LEGACY_STATE_DIR_NAME)].map(d=>path.resolve(d));return[...new Set(dirs)]}function readPidFile(lockDir){try{const raw=fs.readFileSync(path.join(lockDir,"pid"),"utf8").split("\n")[0]?.trim()??"";const n=Number.parseInt(raw,10);return{pid:Number.isInteger(n)&&n>0?n:null,error:null}}catch(err){const code=err.code;return{pid:null,error:code==="ENO\
|
|
4
4
|
ENT"?null:code??err.message}}}function findLoopsUsingProfile(profileName,deps={}){const env=deps.env??process.env;const now=deps.now??Date.now;const isLoopProcess=deps.isLoopProcess??defaultIsLoopProcess;const myHome=twpHomeDir(env);const result={users:[],undetermined:[]};for(const stateDir of deps.stateDirs??defaultStateDirs(env)){let dirs;try{dirs=fs.readdirSync(stateDir).filter(d=>/^task-loop-.*\.lock\.d$/.test(d))}catch(err){if(err.code==="ENOENT")continue;result.undetermined.push({pid:null,
|
|
5
5
|
lockDir:stateDir,reason:`\u30ED\u30C3\u30AF\u306E\u7F6E\u304D\u5834\u6240\u3092\u8AAD\u3081\u307E\u305B\u3093\uFF08${err.code??err.message}\uFF09`});continue}for(const dir of dirs){const lockDir=path.join(stateDir,dir);const pidFile=readPidFile(lockDir);if(pidFile.error!==null){result.undetermined.push({pid:null,lockDir,reason:`pid \u3092\u8AAD\u3081\u307E\u305B\u3093\uFF08${pidFile.error}\uFF09`});continue}const owner=readLockOwner(lockDir);let pid=pidFile.pid;if(pid===null){if(owner.ok){pid=owner.
|
|
6
6
|
owner.pid}else{let ageMs=null;try{ageMs=now()-fs.statSync(lockDir).mtimeMs}catch{}if(ageMs!==null&&ageMs>=PIDLESS_GRACE_MS)continue;result.undetermined.push({pid:null,lockDir,reason:"\u30ED\u30C3\u30AF\u306B pid \u304C\u3042\u308A\u307E\u305B\u3093\uFF08\u8D77\u52D5\u76F4\u5F8C\u306E\u53EF\u80FD\u6027\uFF09"});continue}}if(!isLoopProcess(pid))continue;if(!owner.ok){result.undetermined.push({pid,lockDir,reason:owner.reason});continue}if(owner.owner.pid!==pid){result.undetermined.push({pid,lockDir,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";import{checkOutTarget}from"./chunk-
|
|
3
|
+
import{parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";import{checkOutTarget}from"./chunk-3YG7EN3Y.js";import"./chunk-YNRONUTZ.js";import"./chunk-GFLGXGWE.js";import"./chunk-YXVN6OCH.js";import"./chunk-UFGJSWKU.js";import"./chunk-Q3B65OFC.js";import{contentTypeFor,inspectLocalFile}from"./chunk-I4TR55UF.js";import{checkUploadQuota}from"./chunk-V64CGX7V.js";import"./chunk-GY7KI5E5.js";import{repeatedValues}from"./chunk-RX5HWI4L.js";
|
|
4
4
|
import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger,readEnvelopeCursor,shellQuote}from"./chunk-MI6HVYR2.js";import{readBody}from"./chunk-6LSQCOCJ.js";import"./chunk-MYWDL3WX.js";import{collapsesInUrlPath,isSafePathSegment}from"./chunk-HVZUXLQ4.js";import{ApiError}from"./chunk-JA5A6UJ2.js";import"./chunk-H4CDX4TX.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";import"./chunk-II5RVJQN.js";import{acknowledgement,
|
|
5
5
|
isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiRejectedError,ApiResponseError,NetworkError,UsageError,WaitTimeoutError}from"./chunk-VFPY2A23.js";import"./chunk-PECIBNFD.js";import"./chunk-XNLIEUAW.js";import"./chunk-J7QYPKVK.js";import"./chunk-4VZKNEVN.js";import"./chunk-RZVI6PMW.js";import"./chunk-QZBE4KC2.js";import"./chunk-QQRJLH6B.js";import"./chunk-74BPZOKU.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";
|
|
6
6
|
import"./chunk-VSJBJXZO.js";import crypto2 from"crypto";import fs2 from"fs";import path from"path";var SCOPE_PERSONAL="personal";var SCOPE_PROJECT="project";var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var FORBIDDEN_NAME=/[/\\:*?"<>|]/;var NAME_MAX=255;var ROW_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","updated_at"];var TRASH_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","deleted_at"];function folderRows(raw){return raw.map(row=>{const id=row["id"];const name=row["name"];const parentId=row["parent_id"];if(typeof id!==
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{loadDomain}from"./chunk-
|
|
3
|
+
import{loadDomain}from"./chunk-YNRONUTZ.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-
|
|
3
|
+
import{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-3YG7EN3Y.js";import"./chunk-YNRONUTZ.js";import"./chunk-GFLGXGWE.js";import"./chunk-YXVN6OCH.js";import"./chunk-UFGJSWKU.js";import"./chunk-Q3B65OFC.js";import"./chunk-RX5HWI4L.js";import"./chunk-MI6HVYR2.js";import"./chunk-MYWDL3WX.js";import"./chunk-HVZUXLQ4.js";import"./chunk-JA5A6UJ2.js";
|
|
4
4
|
import"./chunk-H4CDX4TX.js";import"./chunk-II5RVJQN.js";import"./chunk-3ZRMMBP5.js";import"./chunk-VFPY2A23.js";import"./chunk-PECIBNFD.js";import"./chunk-XNLIEUAW.js";import"./chunk-J7QYPKVK.js";import"./chunk-4VZKNEVN.js";import"./chunk-RZVI6PMW.js";import"./chunk-QZBE4KC2.js";import"./chunk-QQRJLH6B.js";import"./chunk-74BPZOKU.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{LoopSettingsApplier,PROMPT_KEYS,formatConfigHash,parseServerSettings,renderStepBudget}from"./chunk-
|
|
3
|
+
import{LoopSettingsApplier,PROMPT_KEYS,formatConfigHash,parseServerSettings,renderStepBudget}from"./chunk-NXWXTUU6.js";import"./chunk-2B7A3OY7.js";import"./chunk-AEJHDFXB.js";import"./chunk-N2UVRM3Z.js";import"./chunk-AT432SCP.js";import"./chunk-GY7KI5E5.js";import"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{LoopSettingsApplier,PROMPT_KEYS,formatConfigHash,parseServerSettings,renderStepBudget};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{PromptAbortedError,promptText}from"./chunk-L37NS5L2.js";import{detectAiClis,formatDetection,isDetectableAi,isSelectable}from"./chunk-T4QZO6RQ.js";import{localConfigPath,parseClaudeLauncher}from"./chunk-
|
|
3
|
+
import{PromptAbortedError,promptText}from"./chunk-L37NS5L2.js";import{detectAiClis,formatDetection,isDetectableAi,isSelectable}from"./chunk-T4QZO6RQ.js";import{localConfigPath,parseClaudeLauncher}from"./chunk-2B7A3OY7.js";import{AiConfig}from"./chunk-AEJHDFXB.js";import"./chunk-N2UVRM3Z.js";import"./chunk-GY7KI5E5.js";import"./chunk-PMOUHEJQ.js";import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";
|
|
4
4
|
import"./chunk-VSJBJXZO.js";import fs from"fs";import path from"path";var RECOMMENDED_ROTATION={complex:["claude"],verify:["claude"],security:["claude"],support:["claude"],triage:["claude"],search:["claude"],simple:["claude"]};var RECOMMENDED_CHAINS={complex:["claude","codex"],verify:["claude","codex","copilot"],security:["claude","codex","copilot"],support:["claude","codex","copilot"],triage:["codex","gemini","copilot","claude"],search:["codex","gemini","copilot","claude"],simple:["codex","gemini","copilot","claude"]};var PREFERENCE=["claude","codex","gemini","co\
|
|
5
5
|
pilot"];function buildAiAssignment(selected){if(selected.length===0)throw new Error("\u9078\u629E\u3055\u308C\u305FAI\u304C\u7A7A\u3067\u3059");const fallbackOrder=PREFERENCE.filter(ai=>selected.includes(ai));for(const ai of selected)if(!fallbackOrder.includes(ai))fallbackOrder.push(ai);const chains={};const rotation={};for(const category of Object.keys(RECOMMENDED_CHAINS)){const filtered=(RECOMMENDED_CHAINS[category]??[]).filter(ai=>selected.includes(ai));const chain=filtered.length>0?filtered:
|
|
6
6
|
[...fallbackOrder];chains[category]=chain;const rot=(RECOMMENDED_ROTATION[category]??[]).filter(ai=>selected.includes(ai));const head=chain[0];rotation[category]=rot.length>0?rot:head===void 0?[...fallbackOrder]:[head]}return{primary_rotation:rotation,fallback_chains:chains}}var SETUP_EXIT_NO_CLI=3;var SETUP_EXIT_ABORTED=130;async function runSetup(opts){const env=opts.env??process.env;const rawOut=opts.out??(t=>void process.stdout.write(t));const rawErr=opts.err??(t=>void process.stderr.write(t));
|
package/package.json
CHANGED
package/dist/chunk-OLASZWF5.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
-
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{normalizeRequiredPlatforms}from"./chunk-AT432SCP.js";import{extractLeadingTaskKey}from"./chunk-II5RVJQN.js";var LEDGER_TASK_KEY_MAX=50;var CONTROL_CHAR_RE=/[\u0000-\u001f\u007f]/;var FLAG_TOKEN_RE=/(?:^|\s)-/;function loosen(source){let t=source.replace(/^[ \t]*\/\/[^\n]*$/gm,"");t=t.replace(/\/\*[\s\S]*?\*\//g,"");t=t.replace(/,(\s*[}\]])/g,"$1");return t===source?null:t}function tryParsePlan(source){for(const candidate of[source,loosen(source)]){if(candidate===null)continue;try{const obj=JSON.parse(candidate);if(obj!==null&&typeof obj==="object"&&Array.isArray(obj.steps)){return obj}}catch{}}return null}
|
|
4
|
-
function fencedBlocks(text,tag){const re=new RegExp("```"+tag+"\\s*\\n([\\s\\S]*?)\\n```","g");const out=[];for(const m of text.matchAll(re)){if(m[1]!==void 0)out.push(m[1])}return out}function extractGeminiEnvelope(text){const anchor=/\{[^{}]*"session_id"[^{}]*"response"\s*:\s*"/g;for(const m of text.matchAll(anchor)){const start=m.index;if(start===void 0)continue;let depth=0;let inStr=false;let escape=false;for(let i=start;i<text.length;i++){const c=text[i];if(escape){escape=false;continue}if(c===
|
|
5
|
-
"\\"){escape=true;continue}if(c==='"'){inStr=!inStr;continue}if(inStr)continue;if(c==="{")depth++;else if(c==="}"){depth--;if(depth===0){try{const obj=JSON.parse(text.slice(start,i+1));if(obj!==null&&typeof obj==="object"&&typeof obj.response==="string"){return obj.response}}catch{}break}}}}return null}function extractPlanJson(rawText){const text=rawText.replace(/^\s*\[\d{2}:\d{2}:\d{2}\]\s*/gm,"");for(const tag of["json:execution-plan","json"]){for(const block of fencedBlocks(text,tag).reverse()){
|
|
6
|
-
const plan=tryParsePlan(block);if(plan)return plan}}const resp=extractGeminiEnvelope(text);if(resp!==null){for(const block of[...fencedBlocks(resp,"json:execution-plan"),...fencedBlocks(resp,"json")].reverse()){const plan2=tryParsePlan(block);if(plan2)return plan2}const plan=tryParsePlan(resp);if(plan)return plan}const whole=tryParsePlan(text.trim());if(whole)return whole;for(const m of[...text.matchAll(/\{[^{}]*"steps"[^{}]*\[[\s\S]*?\][\s\S]*?\}/g)].reverse()){const plan=tryParsePlan(m[0]);if(plan)
|
|
7
|
-
return plan}return null}function ledgerTaskKey(args){const key=extractLeadingTaskKey(args);if(key.length>LEDGER_TASK_KEY_MAX)return"";if(CONTROL_CHAR_RE.test(key))return"";if(FLAG_TOKEN_RE.test(key))return"";return key}function placeholderTaskKey(args){for(const token of args.split(/\s+/)){if(token==="")continue;if(token.startsWith("-"))continue;const m=/^[A-Z]{2,}[A-Z0-9]*-([A-Za-z0-9_<>{}]*)$/.exec(token);if(!m)return null;if(/^\d+$/.test(m[1]??""))return null;return token}return null}function stepToItem(step,assign){
|
|
8
|
-
const skill=typeof step.skill==="string"?step.skill.trim():"";if(!skill)return null;const args=(step.args??"").trim();const priority=step.priority??"P2";const prompt=`/twp-${skill}${args?` ${args}`:""}`;let label=(step.label??"").trim();if(!label||label.startsWith("/twp-")||label.startsWith("[P"))label=prompt;const taskKey=ledgerTaskKey(args);const category=assign?.categoryForSkill(skill)??step.ai_category??"complex";const display=taskKey&&!label.includes(taskKey)?`[${priority}] ${taskKey} ${label}\
|
|
9
|
-
#ai:${category}`:`[${priority}] ${label} #ai:${category}`;const item={label:display.slice(0,200),prompt,task_key:taskKey};const platforms=normalizeRequiredPlatforms(step.required_platforms);if(platforms.length>0)item.required_platforms=platforms;if(assign!==void 0){const ai=assign.selectPrimary(category,skill,priority,display);if(ai!=="")item.ai_type=ai}return item}function parsePlanExcludeKeys(prefetchSection){const m=/OPS_PLAN_EXCLUDE_KEYS\s+([^\s]*)\s+-->/.exec(prefetchSection);const keys=new Set;
|
|
10
|
-
if(!m||!m[1])return keys;for(const raw of m[1].split(",")){const key=raw.trim();if(key!=="")keys.add(key)}return keys}function excludedKeyInArgs(args,excluded){if(excluded.size===0)return null;for(const key of[...excluded].sort()){const re=new RegExp(`(?<![A-Za-z0-9-])${key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![0-9])`);if(re.test(args))return key}return null}function parseOpsCount(prefetchSection,field){const marker=/OPS_COUNTS\s+([^>]*?)-->/.exec(prefetchSection);if(!marker||!marker[1])return null;
|
|
11
|
-
const escaped=field.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const hit=new RegExp(`(?:^|\\s)${escaped}=(-?\\d+)(?:\\s|$)`).exec(marker[1]);if(!hit||hit[1]===void 0)return null;const n=Number.parseInt(hit[1],10);if(!Number.isFinite(n)||n<0)return null;return n}function releaseDeployDropReason(verifyBacklog,devVerifyPlanned){if(verifyBacklog===null){return"\u52D5\u4F5C\u78BA\u8A8D\u306E\u4EF6\u6570\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\uFF08\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u30EA\u30EA\u30FC\u30B9\u306F\u898B\u9001\u308B\uFF09"}
|
|
12
|
-
if(verifyBacklog>devVerifyPlanned){return`\u52D5\u4F5C\u78BA\u8A8D${verifyBacklog}\u4EF6 > \u8A08\u753B\u5185dev-verify${devVerifyPlanned}\u4EF6\uFF08Phase 1\u306E0\u4EF6\u898B\u8FBC\u307F\u304C\u7ACB\u305F\u306A\u3044\uFF09`}return null}function duplicateTaskKeyDropReason(enqueuedKeys,taskKey){if(!taskKey)return null;if(!enqueuedKeys.has(taskKey))return null;return`${taskKey} \u306F\u672C\u8A08\u753B\u3067\u65E2\u306B\u6295\u5165\u6E08\u307F\uFF08\u540C\u4E00\u30AD\u30FC\u306F1\u8A08\u753B1\u4EF6\uFF09`}
|
|
13
|
-
var NO_ZERO_TARGET_GATES={};function zeroTargetDropReasons(prefetchSection,gates=NO_ZERO_TARGET_GATES){const reasons=new Map;for(const[skill,gate]of Object.entries(gates)){const n=parseOpsCount(prefetchSection,gate.field);if(n===null)reasons.set(skill,`${gate.label}\u4EF6\u6570\u304C\u5224\u5B9A\u4E0D\u80FD\u306E\u305F\u3081\u898B\u9001\u308A`);else if(n===0)reasons.set(skill,`${gate.label}0\u4EF6\u306E\u305F\u3081\u5BFE\u8C61\u306A\u3057`)}return reasons}export{extractPlanJson,placeholderTaskKey,stepToItem,parsePlanExcludeKeys,excludedKeyInArgs,parseOpsCount,releaseDeployDropReason,duplicateTaskKeyDropReason,zeroTargetDropReasons};
|