iktisad 0.1.0__tar.gz
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.
- iktisad-0.1.0/PKG-INFO +183 -0
- iktisad-0.1.0/README.md +161 -0
- iktisad-0.1.0/iktisad/__init__.py +110 -0
- iktisad-0.1.0/iktisad/cli.py +195 -0
- iktisad-0.1.0/iktisad/core.py +994 -0
- iktisad-0.1.0/iktisad/gateway.py +802 -0
- iktisad-0.1.0/iktisad.egg-info/PKG-INFO +183 -0
- iktisad-0.1.0/iktisad.egg-info/SOURCES.txt +11 -0
- iktisad-0.1.0/iktisad.egg-info/dependency_links.txt +1 -0
- iktisad-0.1.0/iktisad.egg-info/entry_points.txt +3 -0
- iktisad-0.1.0/iktisad.egg-info/top_level.txt +1 -0
- iktisad-0.1.0/pyproject.toml +45 -0
- iktisad-0.1.0/setup.cfg +4 -0
iktisad-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: iktisad
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-waste, frugal runtime & quota engine for AI agents — Token Governors, Bandwidth Circuit Breakers & Low-Quota Caching
|
|
5
|
+
Author-email: Kenz Labs <oss@kenz.tech>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/autonomy-corp/iktisad
|
|
8
|
+
Project-URL: Repository, https://github.com/autonomy-corp/iktisad
|
|
9
|
+
Project-URL: Funding, https://polar.sh/autonomy-corp
|
|
10
|
+
Keywords: ai-agents,token-efficiency,frugalgpt,bandwidth-guard,circuit-breaker,llm-routing,context-window,iktisad
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Topic :: System :: Networking :: Monitoring
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# İktisad (`iktisad`)
|
|
24
|
+
|
|
25
|
+
> **Zero-waste, frugal runtime & quota engine for AI agents — Token Governors, Bandwidth Circuit Breakers & Low-Quota Caching.**
|
|
26
|
+
> *Doctrinal & Fiqh Basis: Bey' al-Mülk & 19. Lem'a (İktisad Risalesi) — Build once, distribute infinitely at 0 marginal tokens and 0 wasted bandwidth.*
|
|
27
|
+
|
|
28
|
+
[](https://www.python.org/downloads/)
|
|
29
|
+
[](https://opensource.org/licenses/MIT)
|
|
30
|
+
[]()
|
|
31
|
+
[](https://pypi.org/project/iktisad/)
|
|
32
|
+
[](https://polar.sh/autonomy-corp)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## 🎯 The Problem: $O(T^2)$ Token Bleed & Unbounded Quota Burn
|
|
37
|
+
|
|
38
|
+
Autonomous developer agents (Claude Code, SWE-bench runners, OpenHands, custom subagent teams) hemorrhage **80–90% of their operational budget** on:
|
|
39
|
+
1. **Noisy Terminal Dumps**: Repetitive pytest tracebacks, ANSI color codes, spinners, and pip logs injected raw into LLM context.
|
|
40
|
+
2. **Brute-Force Code Reads**: Ingesting 2,500-line Python files into context windows just to discover a function signature or method boundary.
|
|
41
|
+
3. **Model Misrouting**: Using expensive frontier reasoning models (Opus / Gemini Pro / Argon) for trivial regex, linting, or deterministic queries.
|
|
42
|
+
4. **Context Cliff Collapse**: Hitting long-context cliffs where quadratic attention costs degrade model intelligence and spike latency.
|
|
43
|
+
5. **Bandwidth Profligacy**: Uncached HTTP queries, downloading heavy media/images, and blowing through metered data allowances.
|
|
44
|
+
|
|
45
|
+
**`iktisad` solves this deterministically in pure Python with ZERO third-party dependencies.**
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## ⚡ Core Engines
|
|
50
|
+
|
|
51
|
+
- 🛡️ **Deterministic CLI Output Firewall**: Compresses noisy pytest/compiler outputs by **80–97%**, collapsing clean runs to a single `OK` status line and extracting only critical traceback frames.
|
|
52
|
+
- 🗺️ **Zero-Token AST Code Skeletonizer**: Extracts class/function signatures, line numbers, and docstring outlines at **0 LLM tokens**.
|
|
53
|
+
- 🚪 **Bezos Type-1 vs. Type-2 Dynamic Router**: Routes reversible mechanical tasks to lightweight/flash models, reserving frontier reasoning models strictly for irreversible decisions under the **Sandwich Protocol** (Flash prep `<600` tokens -> 1-shot Frontier decision -> Flash execution).
|
|
54
|
+
- 📉 **Context Compaction Gate**: Audits session transcripts to prevent quadratic KV-cache degradation and detect transcript cliffs before token blowout occurs.
|
|
55
|
+
- 🌐 **Bandwidth Circuit Breaker & SQLite Caching (`BandwidthGuard`)**: Enforces hard daily transfer quotas (e.g. 15.0 MB daily limit), blocks bloated media (`.mp4`, `.png`, `.woff2`), and deduplicates HTTP requests with SQLite ETag caching.
|
|
56
|
+
- ⚖️ **19. Lem'a Zaruret vs. İsraf Gate**: Prohibits compute or network spend if a deterministic zero-cost alternative exists or if risk-adjusted expected utility is non-positive.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 📦 Installation
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install iktisad
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
*Or install directly from source:*
|
|
67
|
+
```bash
|
|
68
|
+
git clone https://github.com/autonomy-corp/iktisad.git
|
|
69
|
+
cd iktisad
|
|
70
|
+
pip install .
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## 🚀 CLI Usage
|
|
76
|
+
|
|
77
|
+
The package installs both `iktisad` and `iktisad-guard` command line binaries.
|
|
78
|
+
|
|
79
|
+
### 1. Compress Noisy CLI / Test Logs
|
|
80
|
+
```bash
|
|
81
|
+
iktisad --compress-log pytest_output.log
|
|
82
|
+
```
|
|
83
|
+
*Output:*
|
|
84
|
+
```text
|
|
85
|
+
Original: 14,280 chars -> Compressed: 380 chars (97.3% savings)
|
|
86
|
+
--------------------------------------------------
|
|
87
|
+
OK: 99 passed in 2.53s
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Extract AST Code Skeleton (Zero Tokens)
|
|
91
|
+
```bash
|
|
92
|
+
iktisad --ast-skeleton src/my_service.py
|
|
93
|
+
```
|
|
94
|
+
*Output:*
|
|
95
|
+
```text
|
|
96
|
+
# File: src/my_service.py
|
|
97
|
+
"""User authentication and billing gateway."""
|
|
98
|
+
# (Imports: 6 modules)
|
|
99
|
+
L15-L45: class BillingEngine
|
|
100
|
+
L18-L24: def charge_card(...) - Process card payment
|
|
101
|
+
L26-L40: def refund(...) - Issue refund
|
|
102
|
+
L48-L60: def verify_webhook(...) - Check HMAC signature
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### 3. Dynamic Model Routing
|
|
106
|
+
```bash
|
|
107
|
+
# Reversible mechanical task -> Flash-Lite
|
|
108
|
+
iktisad --route-task lint_check --heaviness 2.0 --importance 3.0
|
|
109
|
+
|
|
110
|
+
# Irreversible Type-1 one-way door -> Argon Sandwich Protocol
|
|
111
|
+
iktisad --route-task deploy_production_db --heaviness 8.5 --importance 9.0 --irreversible
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 4. Audit Context Transcript
|
|
115
|
+
```bash
|
|
116
|
+
iktisad --audit-transcript session_transcript.jsonl
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### 5. Check Bandwidth Usage & Quota Ledger
|
|
120
|
+
```bash
|
|
121
|
+
iktisad --bandwidth-usage
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 🐍 Python API
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from iktisad import (
|
|
130
|
+
BandwidthGuard,
|
|
131
|
+
extract_python_ast_skeleton,
|
|
132
|
+
compress_cli_observation,
|
|
133
|
+
select_model_dynamically,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# 1. Compress terminal tool outputs before injecting into LLM context
|
|
137
|
+
obs = compress_cli_observation(raw_terminal_stream)
|
|
138
|
+
if obs.has_error:
|
|
139
|
+
feed_to_agent_context(obs.pruned_text)
|
|
140
|
+
else:
|
|
141
|
+
feed_to_agent_context(f"Tests passed ({obs.savings_pct:.1f}% context tokens saved)")
|
|
142
|
+
|
|
143
|
+
# 2. Extract AST skeleton for fast agent codebase reconnaissance
|
|
144
|
+
skeleton = extract_python_ast_skeleton("src/engine.py")
|
|
145
|
+
print(skeleton.render_compact())
|
|
146
|
+
|
|
147
|
+
# 3. Dynamic model routing (Bezos Type-1 vs. Type-2 doors)
|
|
148
|
+
decision = select_model_dynamically(
|
|
149
|
+
task_kind="fix_security_flaw",
|
|
150
|
+
heaviness=8.0,
|
|
151
|
+
importance=9.0,
|
|
152
|
+
is_irreversible=True,
|
|
153
|
+
)
|
|
154
|
+
print(f"Tier {decision.tier}: {decision.model_name} via {decision.execution_pattern}")
|
|
155
|
+
|
|
156
|
+
# 4. Bandwidth Circuit Breaker & Local SQLite Caching
|
|
157
|
+
guard = BandwidthGuard(db_path=".cache/network.db", daily_limit_mb=15.0)
|
|
158
|
+
|
|
159
|
+
# Check media blockade
|
|
160
|
+
if guard.is_blocked("https://example.com/huge_banner.png"):
|
|
161
|
+
print("Blocked bloated media asset at 0 wire bytes.")
|
|
162
|
+
|
|
163
|
+
# Check remaining quota before network query
|
|
164
|
+
guard.check_quota(anticipated_bytes=10_240)
|
|
165
|
+
summary = guard.get_usage()
|
|
166
|
+
print(f"Remaining daily quota: {summary.remaining_megabytes:.2f} MB")
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## 🏛️ Theoretical Foundations
|
|
172
|
+
|
|
173
|
+
1. **Risale-i Nur (19. Lem'a - İktisad Risalesi)**: Prohibits resource squandering (*israf*) and demands strict necessity (*zaruret*) before compute/bandwidth consumption.
|
|
174
|
+
2. **Stafford Beer's Cybernetic Algedonic Filter**: Collapses operational routine noise and escalates only anomalous pain signals (tracebacks, assertion errors) to the executive decision core.
|
|
175
|
+
3. **Bezos Two-Way Door Heuristic**: Fast-paths reversible (Type-2) queries to sub-cent lightweight models while reserving frontier reasoning models for irreversible (Type-1) decisions under the **Sandwich Protocol**.
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## 📜 License & Support
|
|
180
|
+
|
|
181
|
+
- **License**: MIT License.
|
|
182
|
+
- **Commercial Support & Sponsorship**: Support ongoing development or sponsor micro-features via [Polar.sh/autonomy-corp](https://polar.sh/autonomy-corp).
|
|
183
|
+
- Built by **Kenz Labs** ("Kırk Düşün, Bir Kes").
|
iktisad-0.1.0/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# İktisad (`iktisad`)
|
|
2
|
+
|
|
3
|
+
> **Zero-waste, frugal runtime & quota engine for AI agents — Token Governors, Bandwidth Circuit Breakers & Low-Quota Caching.**
|
|
4
|
+
> *Doctrinal & Fiqh Basis: Bey' al-Mülk & 19. Lem'a (İktisad Risalesi) — Build once, distribute infinitely at 0 marginal tokens and 0 wasted bandwidth.*
|
|
5
|
+
|
|
6
|
+
[](https://www.python.org/downloads/)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
[]()
|
|
9
|
+
[](https://pypi.org/project/iktisad/)
|
|
10
|
+
[](https://polar.sh/autonomy-corp)
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 🎯 The Problem: $O(T^2)$ Token Bleed & Unbounded Quota Burn
|
|
15
|
+
|
|
16
|
+
Autonomous developer agents (Claude Code, SWE-bench runners, OpenHands, custom subagent teams) hemorrhage **80–90% of their operational budget** on:
|
|
17
|
+
1. **Noisy Terminal Dumps**: Repetitive pytest tracebacks, ANSI color codes, spinners, and pip logs injected raw into LLM context.
|
|
18
|
+
2. **Brute-Force Code Reads**: Ingesting 2,500-line Python files into context windows just to discover a function signature or method boundary.
|
|
19
|
+
3. **Model Misrouting**: Using expensive frontier reasoning models (Opus / Gemini Pro / Argon) for trivial regex, linting, or deterministic queries.
|
|
20
|
+
4. **Context Cliff Collapse**: Hitting long-context cliffs where quadratic attention costs degrade model intelligence and spike latency.
|
|
21
|
+
5. **Bandwidth Profligacy**: Uncached HTTP queries, downloading heavy media/images, and blowing through metered data allowances.
|
|
22
|
+
|
|
23
|
+
**`iktisad` solves this deterministically in pure Python with ZERO third-party dependencies.**
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## ⚡ Core Engines
|
|
28
|
+
|
|
29
|
+
- 🛡️ **Deterministic CLI Output Firewall**: Compresses noisy pytest/compiler outputs by **80–97%**, collapsing clean runs to a single `OK` status line and extracting only critical traceback frames.
|
|
30
|
+
- 🗺️ **Zero-Token AST Code Skeletonizer**: Extracts class/function signatures, line numbers, and docstring outlines at **0 LLM tokens**.
|
|
31
|
+
- 🚪 **Bezos Type-1 vs. Type-2 Dynamic Router**: Routes reversible mechanical tasks to lightweight/flash models, reserving frontier reasoning models strictly for irreversible decisions under the **Sandwich Protocol** (Flash prep `<600` tokens -> 1-shot Frontier decision -> Flash execution).
|
|
32
|
+
- 📉 **Context Compaction Gate**: Audits session transcripts to prevent quadratic KV-cache degradation and detect transcript cliffs before token blowout occurs.
|
|
33
|
+
- 🌐 **Bandwidth Circuit Breaker & SQLite Caching (`BandwidthGuard`)**: Enforces hard daily transfer quotas (e.g. 15.0 MB daily limit), blocks bloated media (`.mp4`, `.png`, `.woff2`), and deduplicates HTTP requests with SQLite ETag caching.
|
|
34
|
+
- ⚖️ **19. Lem'a Zaruret vs. İsraf Gate**: Prohibits compute or network spend if a deterministic zero-cost alternative exists or if risk-adjusted expected utility is non-positive.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 📦 Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install iktisad
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
*Or install directly from source:*
|
|
45
|
+
```bash
|
|
46
|
+
git clone https://github.com/autonomy-corp/iktisad.git
|
|
47
|
+
cd iktisad
|
|
48
|
+
pip install .
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 🚀 CLI Usage
|
|
54
|
+
|
|
55
|
+
The package installs both `iktisad` and `iktisad-guard` command line binaries.
|
|
56
|
+
|
|
57
|
+
### 1. Compress Noisy CLI / Test Logs
|
|
58
|
+
```bash
|
|
59
|
+
iktisad --compress-log pytest_output.log
|
|
60
|
+
```
|
|
61
|
+
*Output:*
|
|
62
|
+
```text
|
|
63
|
+
Original: 14,280 chars -> Compressed: 380 chars (97.3% savings)
|
|
64
|
+
--------------------------------------------------
|
|
65
|
+
OK: 99 passed in 2.53s
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 2. Extract AST Code Skeleton (Zero Tokens)
|
|
69
|
+
```bash
|
|
70
|
+
iktisad --ast-skeleton src/my_service.py
|
|
71
|
+
```
|
|
72
|
+
*Output:*
|
|
73
|
+
```text
|
|
74
|
+
# File: src/my_service.py
|
|
75
|
+
"""User authentication and billing gateway."""
|
|
76
|
+
# (Imports: 6 modules)
|
|
77
|
+
L15-L45: class BillingEngine
|
|
78
|
+
L18-L24: def charge_card(...) - Process card payment
|
|
79
|
+
L26-L40: def refund(...) - Issue refund
|
|
80
|
+
L48-L60: def verify_webhook(...) - Check HMAC signature
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### 3. Dynamic Model Routing
|
|
84
|
+
```bash
|
|
85
|
+
# Reversible mechanical task -> Flash-Lite
|
|
86
|
+
iktisad --route-task lint_check --heaviness 2.0 --importance 3.0
|
|
87
|
+
|
|
88
|
+
# Irreversible Type-1 one-way door -> Argon Sandwich Protocol
|
|
89
|
+
iktisad --route-task deploy_production_db --heaviness 8.5 --importance 9.0 --irreversible
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### 4. Audit Context Transcript
|
|
93
|
+
```bash
|
|
94
|
+
iktisad --audit-transcript session_transcript.jsonl
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 5. Check Bandwidth Usage & Quota Ledger
|
|
98
|
+
```bash
|
|
99
|
+
iktisad --bandwidth-usage
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 🐍 Python API
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from iktisad import (
|
|
108
|
+
BandwidthGuard,
|
|
109
|
+
extract_python_ast_skeleton,
|
|
110
|
+
compress_cli_observation,
|
|
111
|
+
select_model_dynamically,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# 1. Compress terminal tool outputs before injecting into LLM context
|
|
115
|
+
obs = compress_cli_observation(raw_terminal_stream)
|
|
116
|
+
if obs.has_error:
|
|
117
|
+
feed_to_agent_context(obs.pruned_text)
|
|
118
|
+
else:
|
|
119
|
+
feed_to_agent_context(f"Tests passed ({obs.savings_pct:.1f}% context tokens saved)")
|
|
120
|
+
|
|
121
|
+
# 2. Extract AST skeleton for fast agent codebase reconnaissance
|
|
122
|
+
skeleton = extract_python_ast_skeleton("src/engine.py")
|
|
123
|
+
print(skeleton.render_compact())
|
|
124
|
+
|
|
125
|
+
# 3. Dynamic model routing (Bezos Type-1 vs. Type-2 doors)
|
|
126
|
+
decision = select_model_dynamically(
|
|
127
|
+
task_kind="fix_security_flaw",
|
|
128
|
+
heaviness=8.0,
|
|
129
|
+
importance=9.0,
|
|
130
|
+
is_irreversible=True,
|
|
131
|
+
)
|
|
132
|
+
print(f"Tier {decision.tier}: {decision.model_name} via {decision.execution_pattern}")
|
|
133
|
+
|
|
134
|
+
# 4. Bandwidth Circuit Breaker & Local SQLite Caching
|
|
135
|
+
guard = BandwidthGuard(db_path=".cache/network.db", daily_limit_mb=15.0)
|
|
136
|
+
|
|
137
|
+
# Check media blockade
|
|
138
|
+
if guard.is_blocked("https://example.com/huge_banner.png"):
|
|
139
|
+
print("Blocked bloated media asset at 0 wire bytes.")
|
|
140
|
+
|
|
141
|
+
# Check remaining quota before network query
|
|
142
|
+
guard.check_quota(anticipated_bytes=10_240)
|
|
143
|
+
summary = guard.get_usage()
|
|
144
|
+
print(f"Remaining daily quota: {summary.remaining_megabytes:.2f} MB")
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## 🏛️ Theoretical Foundations
|
|
150
|
+
|
|
151
|
+
1. **Risale-i Nur (19. Lem'a - İktisad Risalesi)**: Prohibits resource squandering (*israf*) and demands strict necessity (*zaruret*) before compute/bandwidth consumption.
|
|
152
|
+
2. **Stafford Beer's Cybernetic Algedonic Filter**: Collapses operational routine noise and escalates only anomalous pain signals (tracebacks, assertion errors) to the executive decision core.
|
|
153
|
+
3. **Bezos Two-Way Door Heuristic**: Fast-paths reversible (Type-2) queries to sub-cent lightweight models while reserving frontier reasoning models for irreversible (Type-1) decisions under the **Sandwich Protocol**.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## 📜 License & Support
|
|
158
|
+
|
|
159
|
+
- **License**: MIT License.
|
|
160
|
+
- **Commercial Support & Sponsorship**: Support ongoing development or sponsor micro-features via [Polar.sh/autonomy-corp](https://polar.sh/autonomy-corp).
|
|
161
|
+
- Built by **Kenz Labs** ("Kırk Düşün, Bir Kes").
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""İktisad: Zero-waste, frugal runtime & quota engine for AI agents.
|
|
2
|
+
|
|
3
|
+
Token Governors, Bandwidth Circuit Breakers & Low-Quota Caching.
|
|
4
|
+
Rooted in the 19th Lem'a (İktisad Risalesi) and Stafford Beer's Algedonic Filter.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from iktisad.core import (
|
|
10
|
+
BLOCKED_MEDIA_EXTENSIONS,
|
|
11
|
+
BandwidthCacheEntry,
|
|
12
|
+
BandwidthGuard,
|
|
13
|
+
BandwidthProfile,
|
|
14
|
+
BandwidthUsageSummary,
|
|
15
|
+
BlockedResourceError,
|
|
16
|
+
CLIPrunedObservation,
|
|
17
|
+
DynamicModelDecision,
|
|
18
|
+
FetchResult,
|
|
19
|
+
IktisadResourceCheck,
|
|
20
|
+
PythonASTSkeleton,
|
|
21
|
+
QuotaExceededError,
|
|
22
|
+
SymbolSpan,
|
|
23
|
+
TranscriptHealthReport,
|
|
24
|
+
audit_transcript_health,
|
|
25
|
+
check_quota_available,
|
|
26
|
+
compress_cli_observation,
|
|
27
|
+
evaluate_iktisad_resource_skepticism,
|
|
28
|
+
extract_python_ast_skeleton,
|
|
29
|
+
fetch_url_efficiently,
|
|
30
|
+
get_daily_usage,
|
|
31
|
+
hash_url,
|
|
32
|
+
init_bandwidth_db,
|
|
33
|
+
is_media_blocked,
|
|
34
|
+
lookup_cache_entry,
|
|
35
|
+
record_bandwidth_usage,
|
|
36
|
+
select_model_dynamically,
|
|
37
|
+
store_cache_entry,
|
|
38
|
+
)
|
|
39
|
+
from iktisad.gateway import (
|
|
40
|
+
GatewayCompletionResult,
|
|
41
|
+
GatewayConfig,
|
|
42
|
+
GatewayUsageStats,
|
|
43
|
+
apply_preflight_frugality,
|
|
44
|
+
compress_message_content,
|
|
45
|
+
compress_python_blocks_in_text,
|
|
46
|
+
create_gateway_handler,
|
|
47
|
+
create_gateway_server,
|
|
48
|
+
default_mock_forwarder,
|
|
49
|
+
estimate_prompt_tokens,
|
|
50
|
+
estimate_token_count,
|
|
51
|
+
get_gateway_daily_stats,
|
|
52
|
+
http_upstream_forwarder,
|
|
53
|
+
init_gateway_db,
|
|
54
|
+
is_token_budget_exceeded,
|
|
55
|
+
process_chat_completion,
|
|
56
|
+
record_gateway_token_usage,
|
|
57
|
+
serve_gateway,
|
|
58
|
+
skeletonize_python_source,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
__version__ = "0.1.0"
|
|
62
|
+
__all__ = [
|
|
63
|
+
"BLOCKED_MEDIA_EXTENSIONS",
|
|
64
|
+
"BandwidthCacheEntry",
|
|
65
|
+
"BandwidthGuard",
|
|
66
|
+
"BandwidthProfile",
|
|
67
|
+
"BandwidthUsageSummary",
|
|
68
|
+
"BlockedResourceError",
|
|
69
|
+
"CLIPrunedObservation",
|
|
70
|
+
"DynamicModelDecision",
|
|
71
|
+
"FetchResult",
|
|
72
|
+
"GatewayCompletionResult",
|
|
73
|
+
"GatewayConfig",
|
|
74
|
+
"GatewayUsageStats",
|
|
75
|
+
"IktisadResourceCheck",
|
|
76
|
+
"PythonASTSkeleton",
|
|
77
|
+
"QuotaExceededError",
|
|
78
|
+
"SymbolSpan",
|
|
79
|
+
"TranscriptHealthReport",
|
|
80
|
+
"apply_preflight_frugality",
|
|
81
|
+
"audit_transcript_health",
|
|
82
|
+
"check_quota_available",
|
|
83
|
+
"compress_cli_observation",
|
|
84
|
+
"compress_message_content",
|
|
85
|
+
"compress_python_blocks_in_text",
|
|
86
|
+
"create_gateway_handler",
|
|
87
|
+
"create_gateway_server",
|
|
88
|
+
"default_mock_forwarder",
|
|
89
|
+
"estimate_prompt_tokens",
|
|
90
|
+
"estimate_token_count",
|
|
91
|
+
"evaluate_iktisad_resource_skepticism",
|
|
92
|
+
"extract_python_ast_skeleton",
|
|
93
|
+
"fetch_url_efficiently",
|
|
94
|
+
"get_daily_usage",
|
|
95
|
+
"get_gateway_daily_stats",
|
|
96
|
+
"hash_url",
|
|
97
|
+
"http_upstream_forwarder",
|
|
98
|
+
"init_bandwidth_db",
|
|
99
|
+
"init_gateway_db",
|
|
100
|
+
"is_media_blocked",
|
|
101
|
+
"is_token_budget_exceeded",
|
|
102
|
+
"lookup_cache_entry",
|
|
103
|
+
"process_chat_completion",
|
|
104
|
+
"record_bandwidth_usage",
|
|
105
|
+
"record_gateway_token_usage",
|
|
106
|
+
"select_model_dynamically",
|
|
107
|
+
"serve_gateway",
|
|
108
|
+
"skeletonize_python_source",
|
|
109
|
+
"store_cache_entry",
|
|
110
|
+
]
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""CLI entry point for iktisad."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from iktisad.core import (
|
|
10
|
+
BandwidthGuard,
|
|
11
|
+
audit_transcript_health,
|
|
12
|
+
compress_cli_observation,
|
|
13
|
+
extract_python_ast_skeleton,
|
|
14
|
+
is_media_blocked,
|
|
15
|
+
select_model_dynamically,
|
|
16
|
+
)
|
|
17
|
+
from iktisad.gateway import (
|
|
18
|
+
GatewayConfig,
|
|
19
|
+
serve_gateway,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
24
|
+
"""Build CLI argument parser."""
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
prog="iktisad",
|
|
27
|
+
description="Zero-waste, frugal runtime & quota engine for AI agents",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"--compress-log",
|
|
31
|
+
metavar="FILE",
|
|
32
|
+
help="Compress terminal or pytest stdout log, stripping ANSI codes and boilerplate",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--ast-skeleton",
|
|
36
|
+
metavar="FILE",
|
|
37
|
+
help="Extract compact AST signature skeleton from a Python source file",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--route-task",
|
|
41
|
+
metavar="KIND",
|
|
42
|
+
help="Route an agent task dynamically (e.g. 'swe_bug_fix', 'code_review')",
|
|
43
|
+
)
|
|
44
|
+
parser.add_argument(
|
|
45
|
+
"--heaviness",
|
|
46
|
+
type=float,
|
|
47
|
+
default=5.0,
|
|
48
|
+
help="Reasoning heaviness (0.0 to 10.0, default: 5.0)",
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"--importance",
|
|
52
|
+
type=float,
|
|
53
|
+
default=5.0,
|
|
54
|
+
help="Strategic importance (0.0 to 10.0, default: 5.0)",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--irreversible",
|
|
58
|
+
action="store_true",
|
|
59
|
+
help="Flag as Bezos Type-1 irreversible one-way door (enforces Sandwich Protocol)",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--audit-transcript",
|
|
63
|
+
metavar="FILE",
|
|
64
|
+
help="Audit transcript JSONL for long-context bloat and cliff risk",
|
|
65
|
+
)
|
|
66
|
+
parser.add_argument(
|
|
67
|
+
"--bandwidth-usage",
|
|
68
|
+
action="store_true",
|
|
69
|
+
help="Check and display daily bandwidth consumption from local SQLite cache",
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--check-media-url",
|
|
73
|
+
metavar="URL",
|
|
74
|
+
help="Check whether a URL is blocked under the Bandwidth Miser Protocol",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--db-path",
|
|
78
|
+
default=".cache/iktisad_cache.db",
|
|
79
|
+
help="SQLite database path for bandwidth accounting (default: .cache/iktisad_cache.db)",
|
|
80
|
+
)
|
|
81
|
+
# Kenz Cloud Gateway arguments
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--serve-gateway",
|
|
84
|
+
action="store_true",
|
|
85
|
+
help="Launch Kenz Cloud Gateway reverse-proxy server (/v1/chat/completions)",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument(
|
|
88
|
+
"--port",
|
|
89
|
+
type=int,
|
|
90
|
+
default=8000,
|
|
91
|
+
help="Port to bind Kenz Cloud Gateway (default: 8000)",
|
|
92
|
+
)
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
"--host",
|
|
95
|
+
default="127.0.0.1",
|
|
96
|
+
help="Host interface to bind Kenz Cloud Gateway (default: 127.0.0.1)",
|
|
97
|
+
)
|
|
98
|
+
parser.add_argument(
|
|
99
|
+
"--daily-token-budget",
|
|
100
|
+
type=int,
|
|
101
|
+
default=1_000_000,
|
|
102
|
+
help="Daily token budget before circuit breaker trips (default: 1,000,000)",
|
|
103
|
+
)
|
|
104
|
+
parser.add_argument(
|
|
105
|
+
"--no-block",
|
|
106
|
+
action="store_true",
|
|
107
|
+
help="Run gateway server without blocking main thread",
|
|
108
|
+
)
|
|
109
|
+
return parser
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main(args: list[str] | None = None) -> int:
|
|
113
|
+
"""Run iktisad CLI."""
|
|
114
|
+
parser = build_parser()
|
|
115
|
+
parsed_args = parser.parse_args(args)
|
|
116
|
+
|
|
117
|
+
if parsed_args.serve_gateway:
|
|
118
|
+
config = GatewayConfig(
|
|
119
|
+
host=parsed_args.host,
|
|
120
|
+
port=parsed_args.port,
|
|
121
|
+
daily_token_budget=parsed_args.daily_token_budget,
|
|
122
|
+
db_path=parsed_args.db_path,
|
|
123
|
+
)
|
|
124
|
+
block = not parsed_args.no_block
|
|
125
|
+
serve_gateway(config=config, block=block)
|
|
126
|
+
return 0
|
|
127
|
+
|
|
128
|
+
if parsed_args.compress_log:
|
|
129
|
+
path = Path(parsed_args.compress_log)
|
|
130
|
+
if not path.is_file():
|
|
131
|
+
print(f"Error: file not found: {parsed_args.compress_log}", file=sys.stderr)
|
|
132
|
+
return 1
|
|
133
|
+
raw = path.read_text(encoding="utf-8", errors="replace")
|
|
134
|
+
obs = compress_cli_observation(raw)
|
|
135
|
+
print(f"Original: {obs.raw_chars:,} chars -> Compressed: {obs.compressed_chars:,} chars ({obs.savings_pct:.1f}% savings)")
|
|
136
|
+
print("-" * 50)
|
|
137
|
+
print(obs.pruned_text)
|
|
138
|
+
return 0
|
|
139
|
+
|
|
140
|
+
if parsed_args.ast_skeleton:
|
|
141
|
+
path = Path(parsed_args.ast_skeleton)
|
|
142
|
+
if not path.is_file():
|
|
143
|
+
print(f"Error: file not found: {parsed_args.ast_skeleton}", file=sys.stderr)
|
|
144
|
+
return 1
|
|
145
|
+
skel = extract_python_ast_skeleton(path)
|
|
146
|
+
print(skel.render_compact())
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
if parsed_args.route_task:
|
|
150
|
+
dec = select_model_dynamically(
|
|
151
|
+
task_kind=parsed_args.route_task,
|
|
152
|
+
heaviness=parsed_args.heaviness,
|
|
153
|
+
importance=parsed_args.importance,
|
|
154
|
+
is_irreversible=parsed_args.irreversible,
|
|
155
|
+
)
|
|
156
|
+
print(f"Task: {parsed_args.route_task}")
|
|
157
|
+
print(f"Recommended Tier: {dec.tier} ({dec.tier_name})")
|
|
158
|
+
print(f"Model: {dec.model_name}")
|
|
159
|
+
print(f"Argon Allowed: {dec.argon_allowed}")
|
|
160
|
+
print(f"Execution Pattern: {dec.execution_pattern}")
|
|
161
|
+
print(f"Rationale: {dec.reason}")
|
|
162
|
+
return 0
|
|
163
|
+
|
|
164
|
+
if parsed_args.audit_transcript:
|
|
165
|
+
path = Path(parsed_args.audit_transcript)
|
|
166
|
+
rep = audit_transcript_health(path)
|
|
167
|
+
print(f"Transcript: {rep.transcript_path}")
|
|
168
|
+
print(f"File Size: {rep.file_size_bytes:,} bytes")
|
|
169
|
+
print(f"Health Status: {rep.health_status}")
|
|
170
|
+
print(f"Recommendation: {rep.recommendation}")
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
if parsed_args.bandwidth_usage:
|
|
174
|
+
guard = BandwidthGuard(db_path=parsed_args.db_path)
|
|
175
|
+
summary = guard.get_usage()
|
|
176
|
+
print(f"Bandwidth Usage Report ({summary.date_str}):")
|
|
177
|
+
print(f" Total Transferred: {summary.total_megabytes_transferred:.3f} MB / {summary.max_daily_megabytes:.1f} MB")
|
|
178
|
+
print(f" Remaining Quota: {summary.remaining_megabytes:.3f} MB")
|
|
179
|
+
print(f" Network Requests: {summary.network_requests}")
|
|
180
|
+
print(f" Cache Hits: {summary.cached_hits}")
|
|
181
|
+
print(f" Quota Breached: {summary.quota_exceeded}")
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
if parsed_args.check_media_url:
|
|
185
|
+
blocked = is_media_blocked(parsed_args.check_media_url)
|
|
186
|
+
print(f"URL: {parsed_args.check_media_url}")
|
|
187
|
+
print(f"Media Blocked: {blocked}")
|
|
188
|
+
return 0
|
|
189
|
+
|
|
190
|
+
parser.print_help()
|
|
191
|
+
return 0
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
sys.exit(main())
|